-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy patharray.py
2301 lines (2112 loc) · 78.1 KB
/
array.py
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 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.
#
import warnings
from collections.abc import Iterable
from functools import reduce
from inspect import signature
from typing import Optional, Set, Tuple
import numpy as np
import pyarrow
from legate.core import Array
from .config import (
BinaryOpCode,
CuNumericOpCode,
FusedOpCode,
UnaryOpCode,
UnaryRedCode,
)
from .deferred import DeferredArray
from .doc_utils import copy_docstring
from .runtime import runtime
from .utils import unimplemented
def add_boilerplate(*array_params: str, mutates_self: bool = False):
"""
Adds required boilerplate to the wrapped cuNumeric ndarray member function.
Every time the wrapped function is called, this wrapper will:
* Convert all specified array-like parameters, plus the special "out"
parameter (if present), to cuNumeric ndarrays.
* Convert the special "where" parameter (if present) to a valid predicate.
* Handle the case of scalar cuNumeric ndarrays, by forwarding the operation
to the equivalent `()`-shape numpy array.
NOTE: Assumes that no parameters are mutated besides `out`, and `self` if
`mutates_self` is True.
"""
keys: Set[str] = set(array_params)
def decorator(func):
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.
indices: Set[int] = set()
all_formals: Set[str] = set()
where_idx: Optional[int] = None
out_idx: Optional[int] = None
for (idx, param) in enumerate(signature(func).parameters):
all_formals.add(param)
if param == "where":
where_idx = idx
elif param == "out":
out_idx = idx
elif param in keys:
indices.add(idx)
assert len(keys - all_formals) == 0, "unkonwn parameter(s)"
def wrapper(*args, **kwargs):
self = args[0]
assert (where_idx is None or len(args) <= where_idx) and (
out_idx is None or len(args) <= out_idx
), "'where' and 'out' should be passed as keyword arguments"
stacklevel = kwargs.get("stacklevel", 0) + 1
kwargs["stacklevel"] = stacklevel
# Convert relevant arguments to cuNumeric ndarrays
args = tuple(
ndarray.convert_to_cunumeric_ndarray(
arg, stacklevel=stacklevel
)
if idx in indices and arg is not None
else arg
for (idx, arg) in enumerate(args)
)
for (k, v) in kwargs.items():
if v is None:
continue
elif k == "where":
kwargs[k] = ndarray.convert_to_predicate_ndarray(
v, stacklevel=stacklevel
)
elif k == "out":
kwargs[k] = ndarray.convert_to_cunumeric_ndarray(
v, stacklevel=stacklevel, share=True
)
elif k in keys:
kwargs[k] = ndarray.convert_to_cunumeric_ndarray(
v, stacklevel=stacklevel
)
# Handle the case where all array-like parameters are scalar, by
# performing the operation on the equivalent scalar numpy arrays.
# NOTE: This mplicitly blocks on the contents of the scalar arrays.
if all(
arg._thunk.scalar
for (idx, arg) in enumerate(args)
if (idx in indices or idx == 0) and isinstance(arg, ndarray)
) and all(
v._thunk.scalar
for (k, v) in kwargs.items()
if (k in keys or k == "where") and isinstance(v, ndarray)
):
out = None
if "out" in kwargs:
out = kwargs["out"]
del kwargs["out"]
del kwargs["stacklevel"]
args = tuple(
arg._thunk.__numpy_array__(stacklevel=stacklevel)
if (idx in indices or idx == 0)
and isinstance(arg, ndarray)
else arg
for (idx, arg) in enumerate(args)
)
for (k, v) in kwargs.items():
if (k in keys or k == "where") and isinstance(v, ndarray):
kwargs[k] = v._thunk.__numpy_array__(
stacklevel=stacklevel
)
self_scalar = args[0]
args = args[1:]
result = ndarray.convert_to_cunumeric_ndarray(
getattr(self_scalar, func.__name__)(*args, **kwargs)
)
if mutates_self:
self._thunk = runtime.create_scalar(
self_scalar.data,
self_scalar.dtype,
shape=self_scalar.shape,
wrap=True,
)
if out is not None:
out._thunk.copy(result._thunk, stacklevel=stacklevel)
result = out
return result
return func(*args, **kwargs)
return wrapper
return decorator
def broadcast_shapes(*args):
arrays = [np.empty(x, dtype=[]) for x in args]
return np.broadcast(*arrays).shape
@copy_docstring(np.ndarray)
class ndarray(object):
def __init__(
self,
shape,
dtype=np.float64,
buffer=None,
offset=0,
strides=None,
order=None,
thunk=None,
stacklevel=2,
inputs=None,
):
if thunk is None:
if not isinstance(dtype, np.dtype):
dtype = np.dtype(dtype)
if buffer is not None:
# Make a normal numpy array for this buffer
np_array = np.ndarray(
shape=shape,
dtype=dtype,
buffer=buffer,
offset=offset,
strides=strides,
order=order,
)
self._thunk = runtime.find_or_create_array_thunk(
np_array, stacklevel=(stacklevel + 1), share=False
)
else:
# Filter the inputs if necessary
if inputs is not None:
inputs = [
inp._thunk
for inp in inputs
if isinstance(inp, ndarray)
]
self._thunk = runtime.create_empty_thunk(shape, dtype, inputs)
else:
self._thunk = thunk
self._thunk.wrap(self)
self._legate_data = None
# Support for the Legate data interface
@property
def __legate_data_interface__(self):
if self._legate_data is None:
# All of our thunks implement the Legate Store interface
# so we just need to convert our type and stick it in
# a Legate Array
arrow_type = pyarrow.from_numpy_dtype(self.dtype)
# We don't have nullable data for the moment
# until we support masked arrays
array = Array(arrow_type, [None, self._thunk])
self._legate_data = dict()
self._legate_data["version"] = 1
data = dict()
field = pyarrow.field(
"cuNumeric Array", arrow_type, nullable=False
)
data[field] = array
self._legate_data["data"] = data
return self._legate_data
# A class method for sanitizing inputs by converting them to
# cuNumeric ndarray types
@staticmethod
def convert_to_cunumeric_ndarray(obj, stacklevel=2, share=False):
# If this is an instance of one of our ndarrays then we're done
if isinstance(obj, ndarray):
return obj
# Ask the runtime to make a numpy thunk for this object
thunk = runtime.get_numpy_thunk(
obj, stacklevel=(stacklevel + 1), share=share
)
return ndarray(shape=None, stacklevel=(stacklevel + 1), thunk=thunk)
@staticmethod
def convert_to_predicate_ndarray(obj, stacklevel):
# Keep all boolean types as they are
if obj is True or obj is False:
return obj
if isinstance(obj, ndarray):
thunk = obj._thunk
else:
thunk = runtime.get_numpy_thunk(obj, stacklevel=(stacklevel + 1))
if thunk.scalar:
# Convert this into a bool for now, in the future we may want to
# defer this anyway to avoid blocking deferred execution
return bool(thunk.__numpy_array__(stacklevel=(stacklevel + 1)))
result = ndarray(shape=None, stacklevel=(stacklevel + 1), thunk=thunk)
# If the type of the thunk is not bool then we need to convert it
if result.dtype != np.bool_:
temp = ndarray(
result.shape,
dtype=np.dtype(np.bool_),
stacklevel=(stacklevel + 1),
inputs=(result,),
)
temp._thunk.convert(
result._thunk, warn=True, stacklevel=(stacklevel + 1)
)
result = temp
return result
# Properties for ndarray
# Disable these since they seem to cause problems
# when our arrays do not last long enough, instead
# users will go through the __array__ method
# @property
# def __array_interface__(self):
# return self.__array__(stacklevel=2).__array_interface__
# @property
# def __array_priority__(self):
# return self.__array__(stacklevel=2).__array_priority__
# @property
# def __array_struct__(self):
# return self.__array__(stacklevel=2).__array_struct__
@property
def T(self):
return self.transpose(stacklevel=2)
@property
def base(self):
return self.__array__(stacklevel=2).base
@property
def data(self):
return self.__array__(stacklevel=2).data
@property
def dtype(self):
return self._thunk.dtype
@property
def flags(self):
return self.__array__(stacklevel=2).flags
@property
def flat(self):
return self.__array__(stacklevel=2).flat
@property
def imag(self):
if self.dtype.kind == "c":
return ndarray(
shape=self.shape, thunk=self._thunk.imag(stacklevel=2)
)
else:
result = ndarray(self.shape, self.dtype)
result.fill(0, stacklevel=2)
return result
@property
def ndim(self):
return self._thunk.ndim
@property
def real(self):
if self.dtype.kind == "c":
return ndarray(
shape=self.shape, thunk=self._thunk.real(stacklevel=2)
)
else:
return self
@property
def shape(self):
return self._thunk.shape
@property
def size(self):
s = 1
if self.ndim == 0:
return s
for p in self.shape:
s *= p
return s
@property
def itemsize(self):
return self._thunk.dtype.itemsize
@property
def nbytes(self):
return self.itemsize * self.size
@property
def strides(self):
return self.__array__(stacklevel=2).strides
@property
def ctypes(self):
return self.__array__(stacklevel=2).ctypes
# Methods for ndarray
def __abs__(self):
# Handle the nice case of it being unsigned
if (
self.dtype.type == np.uint16
or self.dtype.type == np.uint32
or self.dtype.type == np.uint64
or self.dtype.type == np.bool_
):
return self
return self.perform_unary_op(UnaryOpCode.ABSOLUTE, self)
def __add__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.ADD, self, rhs_array)
def __and__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.LOGICAL_AND, self, rhs_array
)
def __array__(self, dtype=None, stacklevel=1):
if dtype is None:
return self._thunk.__numpy_array__(stacklevel=(stacklevel + 1))
else:
return self._thunk.__numpy_array__(
stacklevel=(stacklevel + 1)
).__array__(dtype)
# def __array_prepare__(self, *args, **kwargs):
# return self.__array__(stacklevel=2).__array_prepare__(*args, **kwargs)
# def __array_wrap__(self, *args, **kwargs):
# return self.__array__(stacklevel=2).__array_wrap__(*args, **kwargs)
def __bool__(self):
return bool(self.__array__(stacklevel=2))
def __complex__(self):
return complex(self.__array__(stacklevel=2))
def __contains__(self, item):
if isinstance(item, np.ndarray):
args = (item.astype(self.dtype),)
else: # Otherwise convert it to a scalar numpy array of our type
args = (np.array(item, dtype=self.dtype),)
if args[0].size != 1:
raise ValueError("contains needs scalar item")
return self.perform_unary_reduction(
UnaryRedCode.CONTAINS,
self,
axis=None,
dtype=np.dtype(np.bool_),
args=args,
check_types=False,
stacklevel=2,
)
def __copy__(self):
result = ndarray(self.shape, self.dtype, inputs=(self,))
result._thunk.copy(self._thunk, deep=False, stacklevel=2)
return result
def __deepcopy__(self, memo=None):
result = ndarray(self.shape, self.dtype, inputs=(self,))
result._thunk.copy(self._thunk, deep=True, stacklevel=2)
return result
def __div__(self, rhs):
return self.internal_truediv(rhs, inplace=False, stacklevel=2)
def __divmod__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.DIVMOD, self, rhs_array)
def __eq__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.EQUAL, self, rhs_array, out_dtype=np.dtype(np.bool_)
)
def __float__(self):
return float(self.__array__(stacklevel=2))
def __floordiv__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.FLOOR_DIVIDE, self, rhs_array
)
def __format__(self, *args, **kwargs):
return self.__array__(stacklevel=2).__format__(*args, **kwargs)
def __ge__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.GREATER_EQUAL,
self,
rhs_array,
out_dtype=np.dtype(np.bool_),
)
# __getattribute__
def _convert_key(self, key, stacklevel=2, first=True):
# Convert any arrays stored in a key to a cuNumeric array
if (
key is np.newaxis
or key is Ellipsis
or np.isscalar(key)
or isinstance(key, slice)
):
return (key,) if first else key
elif isinstance(key, tuple) and first:
return tuple(
self._convert_key(k, stacklevel=(stacklevel + 1), first=False)
for k in key
)
else:
# Otherwise convert it to a cuNumeric array and get the thunk
return self.convert_to_cunumeric_ndarray(
key, stacklevel=(stacklevel + 1)
)._thunk
@add_boilerplate()
def __getitem__(self, key, stacklevel=1):
key = self._convert_key(key)
return ndarray(
shape=None, thunk=self._thunk.get_item(key, stacklevel=2)
)
def __gt__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.GREATER, self, rhs_array, out_dtype=np.dtype(np.bool_)
)
def __hash__(self, *args, **kwargs):
raise TypeError("unhashable type: cunumeric.ndarray")
def __iadd__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(BinaryOpCode.ADD, self, rhs_array, out=self)
return self
def __iand__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.LOGICAL_AND, self, rhs_array, out=self
)
return self
def __idiv__(self, rhs):
return self.internal_truediv(rhs, inplace=True, stacklevel=2)
def __idivmod__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(BinaryOpCode.DIVMOD, self, rhs_array, out=self)
return self
def __ifloordiv__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.FLOOR_DIVIDE, self, rhs_array, out=self
)
return self
def __ilshift__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.SHIFT_LEFT, self, rhs_array, out=self
)
return self
def __imod__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(BinaryOpCode.MODULUS, self, rhs_array, out=self)
return self
def __imul__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.MULTIPLY, self, rhs_array, out=self
)
return self
def __int__(self):
return int(self.__array__(stacklevel=2))
def __invert__(self):
if self.dtype == np.bool_:
# Boolean values are special, just do logical NOT
return self.perform_unary_op(
UnaryOpCode.LOGICAL_NOT, self, out_dtype=np.dtype(np.bool_)
)
else:
return self.perform_unary_op(UnaryOpCode.INVERT, self)
def __ior__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.LOGICAL_OR, self, rhs_array, out=self
)
return self
def __ipow__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(BinaryOpCode.POWER, self, rhs_array, out=self)
return self
def __irshift__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.SHIFT_RIGHT, self, rhs_array, out=self
)
return self
def __iter__(self):
return self.__array__(stacklevel=2).__iter__()
def __isub__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.SUBTRACT, self, rhs_array, out=self
)
return self
def internal_truediv(self, rhs, inplace, stacklevel):
rhs_array = self.convert_to_cunumeric_ndarray(
rhs, stacklevel=(stacklevel + 1)
)
self_array = self
# Convert any non-floats to floating point arrays
if self_array.dtype.kind != "f" and self_array.dtype.kind != "c":
self_type = np.dtype(np.float64)
else:
self_type = self_array.dtype
if rhs_array.dtype.kind != "f" and rhs_array.dtype.kind != "c":
if inplace:
rhs_type = self_type
else:
rhs_type = np.dtype(np.float64)
else:
rhs_type = rhs_array.dtype
# If the types don't match then align them
if self_type != rhs_type:
common_type = self.find_common_type(self_array, rhs_array)
else:
common_type = self_type
if self_array.dtype != common_type:
temp = ndarray(
self_array.shape,
dtype=common_type,
stacklevel=(stacklevel + 1),
inputs=(self_array,),
)
temp._thunk.convert(
self_array._thunk, warn=False, stacklevel=(stacklevel + 1)
)
self_array = temp
if rhs_array.dtype != common_type:
temp = ndarray(
rhs_array.shape,
dtype=common_type,
stacklevel=(stacklevel + 1),
inputs=(rhs_array,),
)
temp._thunk.convert(
rhs_array._thunk, warn=False, stacklevel=(stacklevel + 1)
)
rhs_array = temp
return self.perform_binary_op(
BinaryOpCode.DIVIDE,
self_array,
rhs_array,
out=self if inplace else None,
stacklevel=(stacklevel + 1),
)
def __itruediv__(self, rhs):
return self.internal_truediv(rhs, inplace=True, stacklevel=2)
def __ixor__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
self.perform_binary_op(
BinaryOpCode.LOGICAL_XOR, self, rhs_array, out=self
)
return self
def __le__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.LESS_EQUAL,
self,
rhs_array,
out_dtype=np.dtype(np.bool_),
)
def __len__(self):
return self.shape[0]
def __lshift__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.SHIFT_LEFT, self, rhs_array)
def __lt__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.LESS, self, rhs_array, out_dtype=np.dtype(np.bool_)
)
def __matmul__(self, value):
return self.dot(value, stacklevel=2)
def __mod__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.MOD, self, rhs_array)
def __mul__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.MULTIPLY, self, rhs_array)
def __ne__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.NOT_EQUAL,
self,
rhs_array,
out_dtype=np.dtype(np.bool_),
)
def __neg__(self):
if (
self.dtype.type == np.uint16
or self.dtype.type == np.uint32
or self.dtype.type == np.uint64
):
raise TypeError("cannot negate unsigned type " + str(self.dtype))
return self.perform_unary_op(UnaryOpCode.NEGATIVE, self)
# __new__
@add_boilerplate()
def nonzero(self, stacklevel=1):
thunks = self._thunk.nonzero(stacklevel=stacklevel + 1)
return tuple(
ndarray(shape=thunk.shape, thunk=thunk) for thunk in thunks
)
def __nonzero__(self):
return self.__array__(stacklevel=2).__nonzero__()
def __or__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.LOGICAL_OR, self, rhs_array)
def __pos__(self):
# We know these types are already positive
if (
self.dtype.type == np.uint16
or self.dtype.type == np.uint32
or self.dtype.type == np.uint64
or self.dtype.type == np.bool_
):
return self
return self.perform_unary_op(UnaryOpCode.POSITIVE, self)
def __pow__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.POWER, self, rhs_array)
def __radd__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.ADD, lhs_array, self)
def __rand__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(
BinaryOpCode.LOGICAL_AND, lhs_array, self
)
def __rdiv__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return lhs_array.internal_truediv(self, inplace=False, stacklevel=2)
def __rdivmod__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.DIVMOD, lhs_array, self)
def __reduce__(self, *args, **kwargs):
return self.__array__(stacklevel=2).__reduce__(*args, **kwargs)
def __reduce_ex__(self, *args, **kwargs):
return self.__array__(stacklevel=2).__reduce_ex__(*args, **kwargs)
def __repr__(self):
return repr(self.__array__(stacklevel=2))
def __rfloordiv__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(
BinaryOpCode.FLOOR_DIVIDE, lhs_array, self
)
def __rmod__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.MOD, lhs_array, self)
def __rmul__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.MULTIPLY, lhs_array, self)
def __ror__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.LOGICAL_OR, lhs_array, self)
def __rpow__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.POWER, lhs_array, self)
def __rshift__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.SHIFT_RIGHT, self, rhs_array
)
def __rsub__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(BinaryOpCode.SUBTRACT, lhs_array, self)
def __rtruediv__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return lhs_array.internal_truediv(self, inplace=False, stacklevel=2)
def __rxor__(self, lhs):
lhs_array = self.convert_to_cunumeric_ndarray(lhs)
return self.perform_binary_op(
BinaryOpCode.LOGICAL_XOR, lhs_array, self
)
# __setattr__
@add_boilerplate("value", mutates_self=True)
def __setitem__(self, key, value, stacklevel=1):
if key is None:
raise KeyError("invalid key passed to cunumeric.ndarray")
if value.dtype != self.dtype:
temp = ndarray(value.shape, dtype=self.dtype, inputs=(value,))
temp._thunk.convert(value._thunk, stacklevel=2)
value = temp
key = self._convert_key(key)
self._thunk.set_item(key, value._thunk, stacklevel=2)
def __setstate__(self, state):
self.__array__(stacklevel=2).__setstate__(state)
def __sizeof__(self, *args, **kwargs):
return self.__array__(stacklevel=2).__sizeof__(*args, **kwargs)
def __sub__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(BinaryOpCode.SUBTRACT, self, rhs_array)
def __str__(self):
return str(self.__array__(stacklevel=2))
def __truediv__(self, rhs, stacklevel=1):
return self.internal_truediv(
rhs, inplace=False, stacklevel=(stacklevel + 1)
)
def __xor__(self, rhs):
rhs_array = self.convert_to_cunumeric_ndarray(rhs)
return self.perform_binary_op(
BinaryOpCode.LOGICAL_XOR, rhs_array, self
)
@add_boilerplate()
def all(
self,
axis=None,
out=None,
keepdims=False,
initial=None,
where=True,
stacklevel=1,
):
return self.perform_unary_reduction(
UnaryRedCode.ALL,
self,
axis=axis,
dst=out,
keepdims=keepdims,
dtype=np.dtype(np.bool_),
check_types=False,
initial=initial,
where=where,
stacklevel=(stacklevel + 1),
)
@add_boilerplate()
def any(
self,
axis=None,
out=None,
keepdims=False,
initial=None,
where=True,
stacklevel=1,
):
return self.perform_unary_reduction(
UnaryRedCode.ANY,
self,
axis=axis,
dst=out,
keepdims=keepdims,
dtype=np.dtype(np.bool_),
check_types=False,
initial=initial,
where=where,
stacklevel=(stacklevel + 1),
)
def argmax(self, axis=None, out=None, stacklevel=1):
if self.size == 1:
return 0
if axis is None:
axis = self.ndim - 1
elif type(axis) != int:
raise TypeError("'axis' argument for argmax must be an 'int'")
elif axis < 0 or axis >= self.ndim:
raise TypeError("invalid 'axis' argument for argmax " + str(axis))
return self.perform_unary_reduction(
UnaryRedCode.ARGMAX,
self,
axis=axis,
dtype=np.dtype(np.int64),
dst=out,
check_types=False,
stacklevel=(stacklevel + 1),
)
def argmin(self, axis=None, out=None, stacklevel=1):
if self.size == 1:
return 0
if axis is None:
axis = self.ndim - 1
elif type(axis) != int:
raise TypeError("'axis' argument for argmin must be an 'int'")
elif axis < 0 or axis >= self.ndim:
raise TypeError("invalid 'axis' argument for argmin " + str(axis))
return self.perform_unary_reduction(
UnaryRedCode.ARGMIN,
self,
axis=axis,
dtype=np.dtype(np.int64),
dst=out,
check_types=False,
stacklevel=(stacklevel + 1),
)
@unimplemented
def argpartition(self, kth, axis=-1, kind="introselect", order=None):
numpy_array = self.__array__(stacklevel=3).argpartition(
kth=kth, axis=axis, kind=kind, order=order
)
return self.convert_to_cunumeric_ndarray(numpy_array, stacklevel=3)
@unimplemented
def argsort(self, axis=-1, kind=None, order=None):
numpy_array = self.__array__(stacklevel=3).argsort(
axis=axis, kind=kind, order=order
)
return self.convert_to_cunumeric_ndarray(numpy_array, stacklevel=3)
def astype(
self, dtype, order="C", casting="unsafe", subok=True, copy=True
):
dtype = np.dtype(dtype)
if self.dtype == dtype:
return self
result = ndarray(self.shape, dtype=dtype, inputs=(self,))
result._thunk.convert(self._thunk, warn=False, stacklevel=2)
return result
@unimplemented
def byteswap(self, inplace=False):
if inplace:
self.__array__(stacklevel=3).byteswap(inplace=True)
return self
else:
numpy_array = self.__array__(stacklevel=3).byteswap(inplace=False)
return self.convert_to_cunumeric_ndarray(numpy_array, stacklevel=3)
@unimplemented
def choose(self, choices, out, mode="raise"):
numpy_array = self.__array__(stacklevel=3).choose(
choices=choices, out=out, mode=mode
)
return self.convert_to_cunumeric_ndarray(numpy_array, stacklevel=3)
def clip(self, min=None, max=None, out=None):
args = (
np.array(min, dtype=self.dtype),
np.array(max, dtype=self.dtype),
)
if args[0].size != 1 or args[1].size != 1:
warnings.warn(
"cuNumeric has not implemented clip with array-like "
"arguments and is falling back to canonical numpy. You "
"may notice significantly decreased performance for this "
"function call.",
stacklevel=2,
category=RuntimeWarning,
)
if out is not None:
self.__array__(stacklevel=2).clip(min, max, out=out)
return self.convert_to_cunumeric_ndarray(
out, stacklevel=2, share=True
)
else:
return self.convert_to_cunumeric_ndarray(
self.__array__.clip(min, max)
)
return self.perform_unary_op(
UnaryOpCode.CLIP, self, dst=out, args=args
)
@unimplemented
def compress(self, condition, axis=None, out=None):
numpy_array = self.__array__(stacklevel=3).compress(