-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathdeferred.py
More file actions
3733 lines (3323 loc) · 124 KB
/
deferred.py
File metadata and controls
3733 lines (3323 loc) · 124 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021-2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import weakref
from collections import Counter
from collections.abc import Iterable
from enum import IntEnum, unique
from functools import reduce, wraps
from inspect import signature
from itertools import chain, product
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Optional,
Sequence,
TypeVar,
Union,
cast,
)
import legate.core.types as ty
import numpy as np
from legate.core import Annotation, Future, ReductionOp, Store
from legate.core.store import RegionField
from legate.core.utils import OrderedSet
from numpy.core.numeric import ( # type: ignore [attr-defined]
normalize_axis_tuple,
)
from typing_extensions import ParamSpec
from .config import (
BinaryOpCode,
BitGeneratorDistribution,
BitGeneratorOperation,
Bitorder,
ConvertCode,
CuNumericOpCode,
RandGenCode,
UnaryOpCode,
UnaryRedCode,
)
from .linalg.cholesky import cholesky
from .linalg.solve import solve
from .sort import sort
from .thunk import NumPyThunk
from .utils import is_advanced_indexing, to_core_dtype
if TYPE_CHECKING:
import numpy.typing as npt
from legate.core import FieldID, Region
from legate.core.operation import AutoTask, ManualTask
from .config import BitGeneratorType, FFTDirection, FFTType, WindowOpCode
from .runtime import Runtime
from .types import (
BitOrder,
ConvolveMode,
NdShape,
OrderType,
SelectKind,
SortSide,
SortType,
)
_COMPLEX_FIELD_DTYPES = {
ty.complex64: ty.float32,
ty.complex128: ty.float64,
}
def _prod(tpl: Sequence[int]) -> int:
return reduce(lambda a, b: a * b, tpl, 1)
R = TypeVar("R")
P = ParamSpec("P")
def auto_convert(
*thunk_params: str,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""
Converts all named parameters to DeferredArrays.
"""
keys = OrderedSet(thunk_params)
assert len(keys) == len(thunk_params)
def decorator(func: Callable[P, R]) -> Callable[P, R]:
assert not hasattr(
func, "__wrapped__"
), "this decorator must be the innermost"
# For each parameter specified by name, also consider the case where
# it's passed as a positional parameter.
params = signature(func).parameters
extra = keys - OrderedSet(params)
assert len(extra) == 0, f"unknown parameter(s): {extra}"
indices = {idx for (idx, param) in enumerate(params) if param in keys}
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> R:
# Convert relevant arguments to DeferredArrays
self = args[0]
args = tuple(
self.runtime.to_deferred_array(arg)
if idx in indices and arg is not None
else arg
for (idx, arg) in enumerate(args)
)
for k, v in kwargs.items():
if k in keys and v is not None:
kwargs[k] = self.runtime.to_deferred_array(v)
return func(*args, **kwargs)
return wrapper
return decorator
# This is a dummy object that is only used as an initializer for the
# RegionField object above. It is thrown away as soon as the
# RegionField is constructed.
class _CuNumericNDarray(object):
__slots__ = ["__array_interface__"]
def __init__(
self,
shape: NdShape,
field_type: Any,
base_ptr: Any,
strides: tuple[int, ...],
read_only: bool,
) -> None:
# See: https://docs.scipy.org/doc/numpy/reference/arrays.interface.html
self.__array_interface__ = {
"version": 3,
"shape": shape,
"typestr": field_type.str,
"data": (base_ptr, read_only),
"strides": strides,
}
_UNARY_RED_TO_REDUCTION_OPS: Dict[int, int] = {
UnaryRedCode.SUM: ReductionOp.ADD,
UnaryRedCode.SUM_SQUARES: ReductionOp.ADD,
UnaryRedCode.VARIANCE: ReductionOp.ADD,
UnaryRedCode.PROD: ReductionOp.MUL,
UnaryRedCode.MAX: ReductionOp.MAX,
UnaryRedCode.MIN: ReductionOp.MIN,
UnaryRedCode.ARGMAX: ReductionOp.MAX,
UnaryRedCode.ARGMIN: ReductionOp.MIN,
UnaryRedCode.NANARGMAX: ReductionOp.MAX,
UnaryRedCode.NANARGMIN: ReductionOp.MIN,
UnaryRedCode.NANMAX: ReductionOp.MAX,
UnaryRedCode.NANMIN: ReductionOp.MIN,
UnaryRedCode.NANPROD: ReductionOp.MUL,
UnaryRedCode.NANSUM: ReductionOp.ADD,
UnaryRedCode.CONTAINS: ReductionOp.ADD,
UnaryRedCode.COUNT_NONZERO: ReductionOp.ADD,
UnaryRedCode.ALL: ReductionOp.MUL,
UnaryRedCode.ANY: ReductionOp.ADD,
}
def max_identity(
ty: np.dtype[Any],
) -> Union[int, np.floating[Any], bool, np.complexfloating[Any, Any]]:
if ty.kind == "i" or ty.kind == "u":
return np.iinfo(ty).min
elif ty.kind == "f":
return np.finfo(ty).min
elif ty.kind == "c":
return np.finfo(np.float64).min + np.finfo(np.float64).min * 1j
elif ty.kind == "b":
return False
else:
raise ValueError(f"Unsupported dtype: {ty}")
def min_identity(
ty: np.dtype[Any],
) -> Union[int, np.floating[Any], bool, np.complexfloating[Any, Any]]:
if ty.kind == "i" or ty.kind == "u":
return np.iinfo(ty).max
elif ty.kind == "f":
return np.finfo(ty).max
elif ty.kind == "c":
return np.finfo(np.float64).max + np.finfo(np.float64).max * 1j
elif ty.kind == "b":
return True
else:
raise ValueError(f"Unsupported dtype: {ty}")
_UNARY_RED_IDENTITIES: Dict[UnaryRedCode, Callable[[Any], Any]] = {
UnaryRedCode.SUM: lambda _: 0,
UnaryRedCode.SUM_SQUARES: lambda _: 0,
UnaryRedCode.VARIANCE: lambda _: 0,
UnaryRedCode.PROD: lambda _: 1,
UnaryRedCode.MIN: min_identity,
UnaryRedCode.MAX: max_identity,
UnaryRedCode.ARGMAX: lambda ty: (np.iinfo(np.int64).min, max_identity(ty)),
UnaryRedCode.ARGMIN: lambda ty: (np.iinfo(np.int64).min, min_identity(ty)),
UnaryRedCode.CONTAINS: lambda _: False,
UnaryRedCode.COUNT_NONZERO: lambda _: 0,
UnaryRedCode.ALL: lambda _: True,
UnaryRedCode.ANY: lambda _: False,
UnaryRedCode.NANARGMAX: lambda ty: (
np.iinfo(np.int64).min,
max_identity(ty),
),
UnaryRedCode.NANARGMIN: lambda ty: (
np.iinfo(np.int64).min,
min_identity(ty),
),
UnaryRedCode.NANMAX: max_identity,
UnaryRedCode.NANMIN: min_identity,
UnaryRedCode.NANPROD: lambda _: 1,
UnaryRedCode.NANSUM: lambda _: 0,
}
@unique
class BlasOperation(IntEnum):
VV = 1
MV = 2
MM = 3
class DeferredArray(NumPyThunk):
"""This is a deferred thunk for describing NumPy computations.
It is backed by either a Legion logical region or a Legion future
for describing the result of a computation.
:meta private:
"""
def __init__(
self,
runtime: Runtime,
base: Store,
numpy_array: Optional[npt.NDArray[Any]] = None,
) -> None:
super().__init__(runtime, base.type.to_numpy_dtype())
assert base is not None
assert isinstance(base, Store)
self.base = base # a Legate Store
self.numpy_array = (
None if numpy_array is None else weakref.ref(numpy_array)
)
def __str__(self) -> str:
return f"DeferredArray(base: {self.base})"
@property
def storage(self) -> Union[Future, tuple[Region, Union[int, FieldID]]]:
storage = self.base.storage
if self.base.kind == Future:
assert isinstance(storage, Future)
return storage
else:
assert isinstance(storage, RegionField)
return (storage.region, storage.field.field_id)
@property
def shape(self) -> NdShape:
return tuple(self.base.shape)
@property
def ndim(self) -> int:
return len(self.shape)
def _copy_if_overlapping(self, other: DeferredArray) -> DeferredArray:
if not self.base.overlaps(other.base):
return self
copy = cast(
DeferredArray,
self.runtime.create_empty_thunk(
self.shape,
self.base.type,
inputs=[self],
),
)
copy.copy(self, deep=True)
return copy
def __numpy_array__(self) -> npt.NDArray[Any]:
if self.numpy_array is not None:
result = self.numpy_array()
if result is not None:
return result
elif self.size == 0:
# Return an empty array with the right number of dimensions
# and type
return np.empty(shape=self.shape, dtype=self.dtype)
if self.scalar:
result = np.full(
self.shape,
self.get_scalar_array(),
dtype=self.dtype,
)
else:
alloc = self.base.get_inline_allocation()
def construct_ndarray(
shape: NdShape, address: Any, strides: tuple[int, ...]
) -> npt.NDArray[Any]:
initializer = _CuNumericNDarray(
shape, self.dtype, address, strides, False
)
result = np.asarray(initializer)
if self.shape == ():
result = result.reshape(())
return result
result = cast("npt.NDArray[Any]", alloc.consume(construct_ndarray))
self.numpy_array = weakref.ref(result)
return result
# TODO: We should return a view of the field instead of a copy
def imag(self) -> NumPyThunk:
result = self.runtime.create_empty_thunk(
self.shape,
dtype=_COMPLEX_FIELD_DTYPES[self.base.type],
inputs=[self],
)
result.unary_op(
UnaryOpCode.IMAG,
self,
True,
[],
)
return result
# TODO: We should return a view of the field instead of a copy
def real(self) -> NumPyThunk:
result = self.runtime.create_empty_thunk(
self.shape,
dtype=_COMPLEX_FIELD_DTYPES[self.base.type],
inputs=[self],
)
result.unary_op(
UnaryOpCode.REAL,
self,
True,
[],
)
return result
def conj(self) -> NumPyThunk:
result = self.runtime.create_empty_thunk(
self.shape,
dtype=self.base.type,
inputs=[self],
)
result.unary_op(
UnaryOpCode.CONJ,
self,
True,
[],
)
return result
# Copy source array to the destination array
@auto_convert("rhs")
def copy(self, rhs: Any, deep: bool = False) -> None:
if self.scalar and rhs.scalar:
self.base.set_storage(rhs.base.storage)
return
self.unary_op(
UnaryOpCode.COPY,
rhs,
True,
[],
)
@property
def scalar(self) -> bool:
return self.base.scalar
def get_scalar_array(self) -> npt.NDArray[Any]:
assert self.scalar
assert isinstance(self.base.storage, Future)
buf = self.base.storage.get_buffer(self.dtype.itemsize)
result = np.frombuffer(buf, dtype=self.dtype, count=1)
return result.reshape(())
def _zip_indices(
self, start_index: int, arrays: tuple[Any, ...]
) -> DeferredArray:
if not isinstance(arrays, tuple):
raise TypeError("zip_indices expects tuple of arrays")
# start_index is the index from witch indices arrays are passed
# for example of arr[:, indx, :], start_index =1
if start_index == -1:
start_index = 0
new_arrays: tuple[Any, ...] = tuple()
# check array's type and convert them to deferred arrays
for a in arrays:
a = self.runtime.to_deferred_array(a)
data_type = a.dtype
if data_type != np.int64:
raise TypeError("index arrays should be int64 type")
new_arrays += (a,)
arrays = new_arrays
# find a broadcasted shape for all arrays passed as indices
shapes = tuple(a.shape for a in arrays)
if len(arrays) > 1:
from .module import broadcast_shapes
b_shape = broadcast_shapes(*shapes)
else:
b_shape = arrays[0].shape
# key dim - dimension of indices arrays
key_dim = len(b_shape)
out_shape = b_shape
# broadcast shapes
new_arrays = tuple()
for a in arrays:
if a.shape != b_shape:
new_arrays += (a._broadcast(b_shape),)
else:
new_arrays += (a.base,)
arrays = new_arrays
if len(arrays) < self.ndim:
# the case when # of arrays passed is smaller than dimension of
# the input array
N = len(arrays)
# output shape
out_shape = (
tuple(self.shape[i] for i in range(0, start_index))
+ b_shape
+ tuple(
self.shape[i] for i in range(start_index + N, self.ndim)
)
)
new_arrays = tuple()
# promote all index arrays to have the same shape as output
for a in arrays:
for i in range(0, start_index):
a = a.promote(i, self.shape[i])
for i in range(start_index + N, self.ndim):
a = a.promote(key_dim + i - N, self.shape[i])
new_arrays += (a,)
arrays = new_arrays
elif len(arrays) > self.ndim:
raise ValueError("wrong number of index arrays passed")
# create output array which will store Point<N> field where
# N is number of index arrays
# shape of the output array should be the same as the shape of each
# index array
# NOTE: We need to instantiate a RegionField of non-primitive
# dtype, to store N-dimensional index points, to be used as the
# indirection field in a copy.
N = self.ndim
pointN_dtype = self.runtime.get_point_type(N)
output_arr = cast(
DeferredArray,
self.runtime.create_empty_thunk(
shape=out_shape,
dtype=pointN_dtype,
inputs=[self],
),
)
# call ZIP function to combine index arrays into a singe array
task = self.context.create_auto_task(CuNumericOpCode.ZIP)
task.throws_exception(IndexError)
task.add_output(output_arr.base)
task.add_scalar_arg(self.ndim, ty.int64) # N of points in Point<N>
task.add_scalar_arg(key_dim, ty.int64) # key_dim
task.add_scalar_arg(start_index, ty.int64) # start_index
task.add_scalar_arg(self.shape, (ty.int64,))
for a in arrays:
task.add_input(a)
task.add_alignment(output_arr.base, a)
task.execute()
return output_arr
def _copy_store(self, store: Any) -> DeferredArray:
store_to_copy = DeferredArray(
self.runtime,
base=store,
)
store_copy = self.runtime.create_empty_thunk(
store_to_copy.shape,
self.base.type,
inputs=[store_to_copy],
)
store_copy.copy(store_to_copy, deep=True)
return cast(DeferredArray, store_copy)
@staticmethod
def _slice_store(k: slice, store: Store, dim: int) -> tuple[slice, Store]:
start = k.start
end = k.stop
step = k.step
size = store.shape[dim]
if start is not None:
if start < 0:
start += size
start = max(0, min(size, start))
if end is not None:
if end < 0:
end += size
end = max(0, min(size, end))
if (
(start is not None and start == size)
or (end is not None and end == 0)
or (start is not None and end is not None and start >= end)
):
start = 0
end = 0
step = 1
k = slice(start, end, step)
if start == end and start == 0: # empty slice
store = store.project(dim, 0)
store = store.promote(dim, 0)
else:
store = store.slice(dim, k)
return k, store
def _has_single_boolean_array(
self, key: Any, is_set: bool
) -> tuple[bool, DeferredArray, Any]:
if isinstance(key, NumPyThunk) and key.dtype == bool:
return True, self, key
else:
# key is a single array of indices
if isinstance(key, NumPyThunk):
return False, self, key
assert isinstance(key, tuple)
key = self._unpack_ellipsis(key, self.ndim)
# loop through all the keys to check if there
# is a single NumPyThunk entry
num_arrays = 0
transpose_index = 0
for dim, k in enumerate(key):
if isinstance(k, NumPyThunk):
num_arrays += 1
transpose_index = dim
# this is the case when there is a single boolean array passed
# in this case we transpose original array so that the indx
# to which boolean array is passed to goes first
# doing this we can avoid going through Realm Copy which should
# improve performance
if (
num_arrays == 1
and key[transpose_index].dtype == bool
and is_set
):
lhs = self
key_dim = key[transpose_index].ndim
transpose_indices = tuple(
(transpose_index + i) for i in range(0, key_dim)
)
transpose_indices += tuple(
i for i in range(0, transpose_index)
)
transpose_indices += tuple(
i for i in range(transpose_index + key_dim, lhs.ndim)
)
new_key = tuple(key[i] for i in range(0, transpose_index))
new_key += tuple(
key[i] for i in range(transpose_index + 1, len(key))
)
lhs = lhs.transpose(transpose_indices)
# transform original array for all other keys in the tuple
if len(new_key) > 0:
shift = 0
store = lhs.base
for dim, k in enumerate(new_key):
if np.isscalar(k):
if k < 0: # type: ignore [operator]
k += store.shape[dim + key_dim + shift]
store = store.project(dim + key_dim + shift, k)
shift -= 1
elif k is np.newaxis:
store = store.promote(dim + key_dim + shift, 1)
elif isinstance(k, slice):
k, store = self._slice_store(
k, store, dim + key_dim + shift
)
else:
raise TypeError(
"Unsupported entry type passed to advanced ",
"indexing operation",
)
lhs = DeferredArray(self.runtime, store)
return True, lhs, key[transpose_index]
# this is a general advanced indexing case
else:
return False, self, key
def _advanced_indexing_with_boolean_array(
self,
key: Any,
is_set: bool = False,
set_value: Optional[Any] = None,
) -> tuple[bool, Any, Any, Any]:
rhs = self
if not isinstance(key, DeferredArray):
key = self.runtime.to_deferred_array(key)
# in case when boolean array is passed as an index, shape for all
# its dimensions should be the same as the shape of
# corresponding dimensions of the input array
for i in range(key.ndim):
if key.shape[i] != rhs.shape[i]:
raise ValueError(
"shape of the index array for "
f"dimension {i} doesn't match to the shape of the"
f"index array which is {rhs.shape[i]}"
)
# if key or rhs are empty, return an empty array with correct shape
if key.size == 0 or rhs.size == 0:
if rhs.size == 0 and key.size != 0:
# we need to calculate shape of the 0 dim of output region
# even though the size of it is 0
# this can potentially be replaced with COUNT_NONZERO
s = key.nonzero()[0].size
else:
s = 0
out_shape = (s,) + tuple(
rhs.shape[i] for i in range(key.ndim, rhs.ndim)
)
out = cast(
DeferredArray,
self.runtime.create_empty_thunk(
out_shape,
rhs.base.type,
inputs=[rhs],
),
)
out.fill(np.zeros((), dtype=out.dtype))
return False, rhs, out, self
key_store = key.base
# bring key to the same shape as rhs
for i in range(key_store.ndim, rhs.ndim):
key_store = key_store.promote(i, rhs.shape[i])
# has_set_value && set_value.size==1 corresponds to the case
# when a[bool_indices]=scalar
# then we can call "putmask" to modify input array
# and avoid calling Copy
has_set_value = set_value is not None and set_value.size == 1
if has_set_value:
mask = DeferredArray(
self.runtime,
base=key_store,
)
rhs.putmask(mask, set_value)
return False, rhs, rhs, self
else:
out_dtype = rhs.base.type
# in the case this operation is called for the set_item, we
# return Point<N> type field that is later used for
# indirect copy operation
if is_set:
N = rhs.ndim
out_dtype = rhs.runtime.get_point_type(N)
# TODO : current implementation of the ND output regions
# requires out.ndim == rhs.ndim. This will be fixed in the
# future
out = rhs.runtime.create_unbound_thunk(out_dtype, ndim=rhs.ndim)
key_dims = key.ndim # dimension of the original key
task = rhs.context.create_auto_task(
CuNumericOpCode.ADVANCED_INDEXING
)
task.add_output(out.base)
task.add_input(rhs.base)
task.add_input(key_store)
task.add_scalar_arg(is_set, ty.bool_)
task.add_scalar_arg(key_dims, ty.int64)
task.add_alignment(rhs.base, key_store)
task.add_broadcast(
rhs.base, axes=tuple(range(1, len(rhs.base.shape)))
)
task.execute()
# TODO : current implementation of the ND output regions
# requires out.ndim == rhs.ndim.
# The logic below will be removed in the future
out_dim = rhs.ndim - key_dims + 1
if out_dim != rhs.ndim:
out_tmp = out.base
if out.size == 0:
out_shape = tuple(out.shape[i] for i in range(0, out_dim))
out = cast(
DeferredArray,
self.runtime.create_empty_thunk(
out_shape,
out_dtype,
inputs=[out],
),
)
if not is_set:
out.fill(np.array(0, dtype=out_dtype.to_numpy_dtype()))
else:
for dim in range(rhs.ndim - out_dim):
out_tmp = out_tmp.project(rhs.ndim - dim - 1, 0)
out = out._copy_store(out_tmp)
return is_set, rhs, out, self
def _create_indexing_array(
self,
key: Any,
is_set: bool = False,
set_value: Optional[Any] = None,
) -> tuple[bool, Any, Any, Any]:
is_bool_array, lhs, bool_key = self._has_single_boolean_array(
key, is_set
)
# the case when single boolean array is passed to the advanced
# indexing operation
if is_bool_array:
return lhs._advanced_indexing_with_boolean_array(
bool_key, is_set, set_value
)
# general advanced indexing case
store = self.base
rhs = self
computed_key: tuple[Any, ...]
if isinstance(key, NumPyThunk):
computed_key = (key,)
else:
computed_key = key
assert isinstance(computed_key, tuple)
computed_key = self._unpack_ellipsis(computed_key, self.ndim)
# the index where the first index_array is passed to the [] operator
start_index = -1
shift = 0
last_index = self.ndim
# in case when index arrays are passed in the scattered way,
# we need to transpose original array so all index arrays
# are close to each other
transpose_needed = False
transpose_indices: NdShape = tuple()
key_transpose_indices: tuple[int, ...] = tuple()
tuple_of_arrays: tuple[Any, ...] = ()
# First, we need to check if transpose is needed
for dim, k in enumerate(computed_key):
if np.isscalar(k) or isinstance(k, NumPyThunk):
if start_index == -1:
start_index = dim
key_transpose_indices += (dim,)
transpose_needed = transpose_needed or ((dim - last_index) > 1)
if (
isinstance(k, NumPyThunk)
and k.dtype == bool
and k.ndim >= 2
):
for i in range(dim, dim + k.ndim):
transpose_indices += (shift + i,)
shift += k.ndim - 1
else:
transpose_indices += ((dim + shift),)
last_index = dim
if transpose_needed:
start_index = 0
post_indices = tuple(
i for i in range(store.ndim) if i not in transpose_indices
)
transpose_indices += post_indices
post_indices = tuple(
i
for i in range(len(computed_key))
if i not in key_transpose_indices
)
key_transpose_indices += post_indices
store = store.transpose(transpose_indices)
computed_key = tuple(
computed_key[i] for i in key_transpose_indices
)
shift = 0
for dim, k in enumerate(computed_key):
if np.isscalar(k):
if k < 0: # type: ignore [operator]
k += store.shape[dim + shift] # type: ignore [operator]
store = store.project(dim + shift, k)
shift -= 1
elif k is np.newaxis:
store = store.promote(dim + shift, 1)
elif isinstance(k, slice):
k, store = self._slice_store(k, store, dim + shift)
elif isinstance(k, NumPyThunk):
if not isinstance(computed_key, DeferredArray):
k = self.runtime.to_deferred_array(k)
if k.dtype == bool:
for i in range(k.ndim):
if k.shape[i] != store.shape[dim + i + shift]:
raise ValueError(
"shape of boolean index did not match "
"indexed array "
)
# in case of the mixed indices we all nonzero
# for the boolean array
k = k.nonzero()
shift += len(k) - 1
tuple_of_arrays += k
else:
tuple_of_arrays += (k,)
else:
raise TypeError(
"Unsupported entry type passed to advanced ",
"indexing operation",
)
if store.transformed:
# in the case this operation is called for the set_item, we need
# to apply all the transformations done to `store` to `self`
# as well before creating a copy
if is_set:
self = DeferredArray(self.runtime, store)
# after store is transformed we need to to return a copy of
# the store since Copy operation can't be done on
# the store with transformation
rhs = self._copy_store(store)
if len(tuple_of_arrays) <= rhs.ndim:
output_arr = rhs._zip_indices(start_index, tuple_of_arrays)
return True, rhs, output_arr, self
else:
raise ValueError("Advanced indexing dimension mismatch")
@staticmethod
def _unpack_ellipsis(key: Any, ndim: int) -> tuple[Any, ...]:
num_ellipsis = sum(k is Ellipsis for k in key)
num_newaxes = sum(k is np.newaxis for k in key)
if num_ellipsis == 0:
return key
elif num_ellipsis > 1:
raise ValueError("Only a single ellipsis must be present")
free_dims = ndim - (len(key) - num_newaxes - num_ellipsis)
to_replace = (slice(None),) * free_dims
unpacked: tuple[Any, ...] = ()
for k in key:
if k is Ellipsis:
unpacked += to_replace
else:
unpacked += (k,)
return unpacked
def _get_view(self, key: Any) -> DeferredArray:
key = self._unpack_ellipsis(key, self.ndim)
store = self.base
shift = 0
for dim, k in enumerate(key):
if k is np.newaxis:
store = store.promote(dim + shift, 1)
elif isinstance(k, slice):
k, store = self._slice_store(k, store, dim + shift)
elif np.isscalar(k):
if k < 0: # type: ignore [operator]
k += store.shape[dim + shift] # type: ignore [operator]
store = store.project(dim + shift, k)
shift -= 1
else:
assert False
return DeferredArray(
self.runtime,
base=store,
)
def _broadcast(self, shape: NdShape) -> Any:
result = self.base
diff = len(shape) - result.ndim
for dim in range(diff):
result = result.promote(dim, shape[dim])
for dim in range(len(shape)):
if result.shape[dim] != shape[dim]:
if result.shape[dim] != 1:
raise ValueError(
f"Shape did not match along dimension {dim} "
"and the value is not equal to 1"
)
result = result.project(dim, 0).promote(dim, shape[dim])
return result
def _convert_future_to_regionfield(
self, change_shape: bool = False
) -> DeferredArray:
if change_shape and self.shape == ():
shape: NdShape = (1,)
else:
shape = self.shape
store = self.context.create_store(
self.base.type,
shape=shape,
optimize_scalar=False,
)
thunk_copy = DeferredArray(
self.runtime,
base=store,
)
thunk_copy.copy(self, deep=True)
return thunk_copy
def get_item(self, key: Any) -> NumPyThunk:
# Check to see if this is advanced indexing or not
if is_advanced_indexing(key):
# Create the indexing array
(
copy_needed,
rhs,
index_array,
self,
) = self._create_indexing_array(key)
if copy_needed:
if rhs.base.kind == Future:
rhs = rhs._convert_future_to_regionfield()
result: NumPyThunk
if index_array.base.kind == Future:
index_array = index_array._convert_future_to_regionfield()
result_store = self.context.create_store(
self.base.type,
shape=index_array.shape,
optimize_scalar=False,
)
result = DeferredArray(
self.runtime,
base=result_store,
)
else:
result = self.runtime.create_empty_thunk(
index_array.base.shape,
self.base.type,
inputs=[self],
)
copy = self.context.create_copy()
copy.set_source_indirect_out_of_range(False)
copy.add_input(rhs.base)
copy.add_source_indirect(index_array.base)
copy.add_output(result.base) # type: ignore