/
core.pyx
2820 lines (2282 loc) · 96 KB
/
core.pyx
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
# distutils: language = c++
import contextlib
import functools
import os
import pickle
import re
import sys
import warnings
import numpy
import cupy
from cupy._core._kernel import create_ufunc
from cupy._core._kernel import ElementwiseKernel
from cupy._core._kernel import ufunc # NOQA
from cupy._core._ufuncs import elementwise_copy
from cupy._core import flags
from cupy._core import syncdetect
from cupy import cuda
from cupy.cuda import memory as memory_module
from cupy.cuda import stream as stream_mod
from cupy_backends.cuda.api.runtime import CUDARuntimeError
from cupy import _util
cimport cpython # NOQA
cimport cython # NOQA
from libcpp cimport vector
from libc.stdint cimport int64_t, intptr_t
from cupy._core cimport _carray
from cupy._core cimport _dtype
from cupy._core._dtype cimport get_dtype
from cupy._core._kernel cimport create_ufunc
from cupy._core cimport _routines_binary as _binary
from cupy._core cimport _routines_indexing as _indexing
from cupy._core cimport _routines_linalg as _linalg
from cupy._core cimport _routines_logic as _logic
from cupy._core cimport _routines_manipulation as _manipulation
from cupy._core cimport _routines_math as _math
from cupy._core cimport _routines_sorting as _sorting
from cupy._core cimport _routines_statistics as _statistics
from cupy._core cimport _scalar
from cupy._core cimport dlpack
from cupy._core cimport internal
from cupy.cuda cimport device
from cupy.cuda cimport function
from cupy.cuda cimport pinned_memory
from cupy.cuda cimport memory
from cupy.cuda cimport stream as stream_module
from cupy_backends.cuda cimport stream as _stream_module
from cupy_backends.cuda.api cimport runtime
from cupy_backends.cuda.libs cimport cublas
# If rop of cupy.ndarray is called, cupy's op is the last chance.
# If op of cupy.ndarray is called and the `other` is cupy.ndarray, too,
# it is safe to call cupy's op.
# Otherwise, use this function `_should_use_rop` to choose
# * [True] return NotImplemented to defer rhs, or
# * [False] call NumPy's ufunc to try all `__array_ufunc__`.
# Note that extension types (`cdef class`) in Cython 0.x shares
# implementations of op and rop. (i.e. `__radd__(self, other)` is
# `__add__(other, self)`.)
#
# It follows NEP 13 except that cupy also implements the fallback to
# `__array_priority__`, which seems fair and necessary because of the
# following facts:
# * `numpy` : `scipy.sparse` = `cupy` : `cupyx.scipy.sparse`;
# * NumPy ignores `__array_priority__` attributes of arguments if NumPy finds
# `__array_function__` of `cupy.ndarray`;
# * SciPy sparse classes don't implement `__array_function__` and they even
# don't set `__array_function__ = None` to opt-out the feature; and
# * `__array_priority__` of SciPy sparse classes is respected because
# `numpy.ndarray.__array_function__` does not disable `__array_priority__`.
@cython.profile(False)
cdef inline _should_use_rop(x, y):
try:
y_ufunc = y.__array_ufunc__
except AttributeError:
# NEP 13's recommendation is `return False`.
xp = getattr(x, '__array_priority__', 0)
yp = getattr(y, '__array_priority__', 0)
return xp < yp
return y_ufunc is None
cdef tuple _HANDLED_TYPES
cdef object _null_context = contextlib.nullcontext()
class ndarray(_ndarray_base):
"""
__init__(self, shape, dtype=float, memptr=None, strides=None, order='C')
Multi-dimensional array on a CUDA device.
This class implements a subset of methods of :class:`numpy.ndarray`.
The difference is that this class allocates the array content on the
current GPU device.
Args:
shape (tuple of ints): Length of axes.
dtype: Data type. It must be an argument of :class:`numpy.dtype`.
memptr (cupy.cuda.MemoryPointer): Pointer to the array content head.
strides (tuple of ints or None): Strides of data in memory.
order ({'C', 'F'}): Row-major (C-style) or column-major
(Fortran-style) order.
Attributes:
base (None or cupy.ndarray): Base array from which this array is
created as a view.
data (cupy.cuda.MemoryPointer): Pointer to the array content head.
~ndarray.dtype(numpy.dtype): Dtype object of element type.
.. seealso::
`Data type objects (dtype) \
<https://numpy.org/doc/stable/reference/arrays.dtypes.html>`_
~ndarray.size (int): Number of elements this array holds.
This is equivalent to product over the shape tuple.
.. seealso:: :attr:`numpy.ndarray.size`
"""
__module__ = 'cupy'
def __new__(cls, *args, _obj=None, _no_init=False, **kwargs):
x = super().__new__(cls, *args, **kwargs)
if _no_init:
return x
x._init(*args, **kwargs)
if cls is not ndarray:
x.__array_finalize__(_obj)
return x
def __init__(self, *args, **kwargs):
# Prevent from calling the super class `_ndarray_base.__init__()` as
# it is used to check accidental direct instantiation of underlaying
# `_ndarray_base` extention.
pass
def __array_finalize__(self, obj):
pass
# We provide the Python-level wrapper of `view` method to follow NumPy's
# API signature, as it seems that Cython's `cpdef`d methods does not take
# an argument named `type`. Cython also does not take starargs
# (`*args` and `**kwargs`) for `cpdef`d methods so we can not interpret the
# arguments `dtype` and `type` from them.
def view(self, dtype=None, type=None):
"""Returns a view of the array.
Args:
dtype: If this is different from the data type of the array, the
returned view reinterpret the memory sequence as an array of
this type.
Returns:
cupy.ndarray: A view of the array. A reference to the original
array is stored at the :attr:`~ndarray.base` attribute.
.. seealso:: :meth:`numpy.ndarray.view`
"""
return super(ndarray, self).view(dtype=dtype, array_class=type)
cdef class _ndarray_base:
def __init__(self, *args, **kwargs):
# Raise an error if underlaying `_ndarray_base` extension type is
# directly instantiated. We must instantiate `ndarray` class instead
# for our ndarray subclassing mechanism.
raise RuntimeError('Must not be directly instantiated')
def _init(self, shape, dtype=float, memptr=None, strides=None,
order='C'):
cdef Py_ssize_t x, itemsize
cdef tuple s = internal.get_size(shape)
del shape
cdef int order_char = (
b'C' if order is None else internal._normalize_order(order))
# `strides` is prioritized over `order`, but invalid `order` should be
# checked even if `strides` is given.
if order_char != b'C' and order_char != b'F':
raise ValueError('order not understood. order=%s' % order)
# Check for erroneous shape
if len(s) > _carray.MAX_NDIM:
msg = f'maximum supported dimension for an ndarray is '
msg += f'{_carray.MAX_NDIM}, found {len(s)}'
raise ValueError(msg)
self._shape.reserve(len(s))
for x in s:
if x < 0:
raise ValueError('Negative dimensions are not allowed')
self._shape.push_back(x)
del s
# dtype
self.dtype, itemsize = _dtype.get_dtype_with_itemsize(dtype)
# Store shape and strides
if strides is not None:
if memptr is None:
raise ValueError('memptr is required if strides is given.')
self._set_shape_and_strides(self._shape, strides, True, True)
elif order_char == b'C':
self._set_contiguous_strides(itemsize, True)
elif order_char == b'F':
self._set_contiguous_strides(itemsize, False)
else:
assert False
# data
if memptr is None:
self.data = memory.alloc(self.size * itemsize)
self._index_32_bits = (self.size * itemsize) <= (1 << 31)
else:
self.data = memptr
bound = cupy._core._memory_range.get_bound(self)
self._index_32_bits = bound[1] - bound[0] <= (1 << 31)
cdef _init_fast(self, const shape_t& shape, dtype, bint c_order):
""" For internal ndarray creation. """
cdef Py_ssize_t itemsize
if shape.size() > _carray.MAX_NDIM:
msg = f'maximum supported dimension for an ndarray is '
msg += f'{_carray.MAX_NDIM}, found {shape.size()}'
raise ValueError(msg)
self._shape = shape
self.dtype, itemsize = _dtype.get_dtype_with_itemsize(dtype)
self._set_contiguous_strides(itemsize, c_order)
self.data = memory.alloc(self.size * itemsize)
self._index_32_bits = (self.size * itemsize) <= (1 << 31)
@property
def __cuda_array_interface__(self):
if runtime._is_hip_environment:
raise AttributeError(
'HIP/ROCm does not support cuda array interface')
cdef dict desc = {
'shape': self.shape,
'typestr': self.dtype.str,
'descr': self.dtype.descr,
}
cdef int ver = _util.CUDA_ARRAY_INTERFACE_EXPORT_VERSION
cdef intptr_t stream_ptr
if ver == 3:
stream_ptr = stream_module.get_current_stream_ptr()
# CAI v3 says setting the stream field to 0 is disallowed
if stream_ptr == 0:
stream_ptr = _stream_module.get_default_stream_ptr()
desc['stream'] = stream_ptr
elif ver == 2:
# Old behavior (prior to CAI v3): stream sync is explicitly handled
# by users. To restore this behavior, we do not export any stream
# if CUPY_CUDA_ARRAY_INTERFACE_EXPORT_VERSION is set to 2 (so that
# other participating libraries lacking a finer control over sync
# behavior can avoid syncing).
pass
else:
raise ValueError('CUPY_CUDA_ARRAY_INTERFACE_EXPORT_VERSION can '
'only be set to 3 (default) or 2')
desc['version'] = ver
if self._c_contiguous:
desc['strides'] = None
else:
desc['strides'] = self.strides
if self.size > 0:
desc['data'] = (self.data.ptr, False)
else:
desc['data'] = (0, False)
return desc
def __dlpack__(self, stream=None):
# Note: the stream argument is supplied by the consumer, not by CuPy
curr_stream = stream_module.get_current_stream()
curr_stream_ptr = curr_stream.ptr
# stream must be an int for CUDA/ROCm
if not runtime._is_hip_environment: # CUDA
if stream is None:
stream = runtime.streamLegacy
elif not isinstance(stream, int) or stream < -1:
# DLPack does not accept 0 as a valid stream, but there is a
# bug in PyTorch that exports the default stream as 0, which
# renders the protocol unusable, we will accept a 0 value
# meanwhile.
raise ValueError(
f'On CUDA, the valid stream for the DLPack protocol is -1,'
f' 1, 2, or any larger value, but {stream} was provided')
if stream == 0:
warnings.warn(
'Stream 0 is passed from a library that you are'
' converting to; CuPy assumes 0 as a legacy default '
'stream. Please report this problem to the library as this'
' violates the DLPack protocol.')
stream = runtime.streamLegacy
if curr_stream_ptr == 0:
curr_stream_ptr = runtime.streamLegacy
else: # ROCm/HIP
if stream is None:
stream = 0
elif (not isinstance(stream, int) or stream < -1
or stream in (1, 2)):
raise ValueError(
f'On ROCm/HIP, the valid stream for the DLPack protocol is'
f' -1, 0, or any value > 2, but {stream} was provided')
# if -1, no stream order should be established; otherwise, the consumer
# stream should wait for the work on CuPy's current stream to finish
if stream >= 0 and stream != curr_stream_ptr:
next_stream = stream_mod.ExternalStream(stream)
event = curr_stream.record()
next_stream.wait_event(event)
return dlpack.toDlpack(self)
def __dlpack_device__(self):
if not runtime._is_hip_environment:
attrs = runtime.pointerGetAttributes(self.data.ptr)
is_managed = (
attrs.type == runtime.memoryTypeManaged
and _util.DLPACK_EXPORT_VERSION >= (0, 6))
if is_managed:
device_type = dlpack.managed_CUDA
else:
device_type = dlpack.device_CUDA
else:
device_type = dlpack.device_ROCM
return (device_type, self.device.id)
# The definition order of attributes and methods are borrowed from the
# order of documentation at the following NumPy document.
# https://numpy.org/doc/stable/reference/arrays.ndarray.html
# -------------------------------------------------------------------------
# Memory layout
# -------------------------------------------------------------------------
@property
def flags(self):
"""Object containing memory-layout information.
It only contains ``c_contiguous``, ``f_contiguous``, and ``owndata``
attributes. All of these are read-only. Accessing by indexes is also
supported.
.. seealso:: :attr:`numpy.ndarray.flags`
"""
return flags.Flags(self._c_contiguous, self._f_contiguous,
self.base is None)
property shape:
"""Lengths of axes.
Setter of this property involves reshaping without copy. If the array
cannot be reshaped without copy, it raises an exception.
.. seealso: :attr:`numpy.ndarray.shape`
"""
def __get__(self):
return tuple(self._shape)
def __set__(self, newshape):
_manipulation._ndarray_shape_setter(self, newshape)
@property
def strides(self):
"""Strides of axes in bytes.
.. seealso:: :attr:`numpy.ndarray.strides`
"""
return tuple(self._strides)
@property
def ndim(self):
"""Number of dimensions.
``a.ndim`` is equivalent to ``len(a.shape)``.
.. seealso:: :attr:`numpy.ndarray.ndim`
"""
return self._shape.size()
@property
def itemsize(self):
"""Size of each element in bytes.
.. seealso:: :attr:`numpy.ndarray.itemsize`
"""
return self.dtype.itemsize
@property
def nbytes(self):
"""Total size of all elements in bytes.
It does not count skips between elements.
.. seealso:: :attr:`numpy.ndarray.nbytes`
"""
return self.size * self.dtype.itemsize
# -------------------------------------------------------------------------
# Other attributes
# -------------------------------------------------------------------------
@property
def T(self):
"""Shape-reversed view of the array.
If ndim < 2, then this is just a reference to the array itself.
"""
if self.ndim < 2:
return self
else:
return _manipulation._T(self)
@property
def flat(self):
return cupy.flatiter(self)
__array_priority__ = 100
# -------------------------------------------------------------------------
# Array interface
# -------------------------------------------------------------------------
# TODO(beam2d): Implement __array_interface__
# -------------------------------------------------------------------------
# foreign function interface
# -------------------------------------------------------------------------
@property
def cstruct(self):
"""C representation of the array.
This property is used for sending an array to CUDA kernels. The type of
returned C structure is different for different dtypes and ndims. The
definition of C type is written in ``cupy/carray.cuh``.
"""
return _CArray_from_ndarray(self)
# -------------------------------------------------------------------------
# Array conversion
# -------------------------------------------------------------------------
cpdef item(self):
"""Converts the array with one element to a Python scalar
Returns:
int or float or complex: The element of the array.
.. seealso:: :meth:`numpy.ndarray.item`
"""
if self.size != 1:
raise ValueError(
'can only convert an array of size 1 to a Python scalar')
return self.get().item()
cpdef tolist(self):
"""Converts the array to a (possibly nested) Python list.
Returns:
list: The possibly nested Python list of array elements.
.. seealso:: :meth:`numpy.ndarray.tolist`
"""
return self.get().tolist()
# TODO(okuta): Implement itemset
# TODO(okuta): Implement tostring
cpdef bytes tobytes(self, order='C'):
"""Turns the array into a Python bytes object."""
return self.get().tobytes(order)
cpdef tofile(self, fid, sep='', format='%s'):
"""Writes the array to a file.
.. seealso:: :meth:`numpy.ndarray.tofile`
"""
self.get().tofile(fid, sep, format)
cpdef dump(self, file):
"""Dumps a pickle of the array to a file.
Dumped file can be read back to :class:`cupy.ndarray` by
:func:`cupy.load`.
"""
pickle.dump(self, file, -1)
cpdef bytes dumps(self):
"""Dumps a pickle of the array to a string."""
return pickle.dumps(self, -1)
cpdef _ndarray_base astype(
self, dtype, order='K', casting=None, subok=None, copy=True):
"""Casts the array to given data type.
Args:
dtype: Type specifier.
order ({'C', 'F', 'A', 'K'}): Row-major (C-style) or column-major
(Fortran-style) order.
When ``order`` is 'A', it uses 'F' if ``a`` is column-major and
uses 'C' otherwise.
And when ``order`` is 'K', it keeps strides as closely as
possible.
copy (bool): If it is False and no cast happens, then this method
returns the array itself. Otherwise, a copy is returned.
Returns:
If ``copy`` is False and no cast is required, then the array itself
is returned. Otherwise, it returns a (possibly casted) copy of the
array.
.. note::
This method currently does not support ``casting``, and ``subok``
arguments.
.. seealso:: :meth:`numpy.ndarray.astype`
"""
cdef strides_t strides
cdef Py_ssize_t stride
# TODO(beam2d): Support casting and subok option
if casting is not None:
raise TypeError('casting is not supported yet')
if subok is not None:
raise TypeError('subok is not supported yet')
if order is None:
order = 'K'
cdef int order_char = internal._normalize_order(order)
dtype = get_dtype(dtype)
if dtype == self.dtype:
if not copy and (
order_char == b'K' or
order_char == b'A' and (self._c_contiguous or
self._f_contiguous) or
order_char == b'C' and self._c_contiguous or
order_char == b'F' and self._f_contiguous):
return self
order_char = internal._update_order_char(
self._c_contiguous, self._f_contiguous, order_char)
if order_char == b'K':
strides = internal._get_strides_for_order_K(self, dtype)
newarray = _ndarray_init(ndarray, self._shape, dtype, None)
# TODO(niboshi): Confirm update_x_contiguity flags
newarray._set_shape_and_strides(self._shape, strides, True, True)
else:
newarray = ndarray(self.shape, dtype=dtype, order=chr(order_char))
if self.size == 0:
# skip copy
if self.dtype.kind == 'c' and newarray.dtype.kind not in 'bc':
warnings.warn(
'Casting complex values to real discards the imaginary '
'part',
numpy.ComplexWarning)
else:
elementwise_copy(self, newarray)
return newarray
# TODO(okuta): Implement byteswap
cpdef _ndarray_base copy(self, order='C'):
"""Returns a copy of the array.
This method makes a copy of a given array in the current device.
Even when a given array is located in another device, you can copy it
to the current device.
Args:
order ({'C', 'F', 'A', 'K'}): Row-major (C-style) or column-major
(Fortran-style) order.
When ``order`` is 'A', it uses 'F' if ``a`` is column-major and
uses 'C' otherwise.
And when `order` is 'K', it keeps strides as closely as
possible.
.. seealso::
:func:`cupy.copy` for full documentation,
:meth:`numpy.ndarray.copy`
"""
cdef _ndarray_base x
if self.size == 0:
return self.astype(self.dtype, order=order)
dev_id = device.get_device_id()
if self.data.device_id == dev_id:
return self.astype(self.dtype, order=order)
# It need to make a contiguous copy for copying from another device
prev_device = runtime.getDevice()
try:
runtime.setDevice(self.device.id)
x = self.astype(self.dtype, order=order, copy=False)
finally:
runtime.setDevice(prev_device)
newarray = _ndarray_init(ndarray, x._shape, x.dtype, None)
if not x._c_contiguous and not x._f_contiguous:
raise NotImplementedError(
'CuPy cannot copy non-contiguous array between devices.')
# TODO(niboshi): Confirm update_x_contiguity flags
newarray._strides = x._strides
newarray._c_contiguous = x._c_contiguous
newarray._f_contiguous = x._f_contiguous
copy_context = _null_context
if runtime._is_hip_environment:
# HIP requires changing the active device to the one where
# src data is before the copy. From the docs:
# it is recommended to set the current device to the device
# where the src data is physically located.
copy_context = self.device
with copy_context:
newarray.data.copy_from_device_async(x.data, x.nbytes)
return newarray
cpdef _ndarray_base view(self, dtype=None, array_class=None):
cdef Py_ssize_t ndim, axis, tmp_size
cdef int self_is, v_is
if dtype is not None:
if type(dtype) is type and issubclass(dtype, ndarray):
if array_class is not None:
raise ValueError('Cannot specify output type twice.')
array_class = dtype
dtype = None
if (
array_class is not None and (
type(array_class) is not type or
not issubclass(array_class, ndarray)
)
):
raise ValueError('Type must be a sub-type of ndarray type')
if array_class is None:
array_class = type(self)
v = self._view(
array_class, self._shape, self._strides, False, False, self)
if dtype is None:
return v
v.dtype, v_is = _dtype.get_dtype_with_itemsize(dtype)
self_is = self.dtype.itemsize
if v_is == self_is:
return v
ndim = self._shape.size()
if ndim == 0:
raise ValueError(
'Changing the dtype of a 0d array is only supported if '
'the itemsize is unchanged')
axis = ndim - 1
if (
self._shape[axis] != 1
and self.size != 0
and self._strides[axis] != self.dtype.itemsize
):
raise ValueError(
'To change to a dtype of a different size, the last axis '
'must be contiguous')
# Normalize `_strides[axis]` whenever itemsize changes
v._strides[axis] = v_is
tmp_size = v._shape[axis] * self_is
if tmp_size % v_is != 0:
raise ValueError(
'When changing to a larger dtype, its size must be a '
'divisor of the total size in bytes of the last axis '
'of the array.')
# itemsize of dtype in CuPy is one of 1, 2, 4, 8, 16.
# Thus, CuPy does not raise the following:
# raise ValueError(
# 'When changing to a smaller dtype, its size must be a '
# 'divisor of the size of original dtype')
v._shape[axis] = tmp_size // v_is
v.size = v.size * self_is // v_is # divisible because shape[axis] is.
if axis != ndim - 1:
v._update_c_contiguity()
if axis != 0:
v._update_f_contiguity()
return v
# TODO(okuta): Implement getfield
# TODO(okuta): Implement setflags
cpdef fill(self, value):
"""Fills the array with a scalar value.
Args:
value: A scalar value to fill the array content.
.. seealso:: :meth:`numpy.ndarray.fill`
"""
if isinstance(value, cupy.ndarray):
if value.shape != ():
raise ValueError(
'non-scalar cupy.ndarray cannot be used for fill')
value = value.astype(self.dtype, copy=False)
fill_kernel(value, self)
return
if isinstance(value, numpy.ndarray):
if value.shape != ():
raise ValueError(
'non-scalar numpy.ndarray cannot be used for fill')
value = value.astype(self.dtype, copy=False).item()
if value == 0 and self._c_contiguous:
self.data.memset_async(0, self.nbytes)
else:
fill_kernel(value, self)
# -------------------------------------------------------------------------
# Shape manipulation
# -------------------------------------------------------------------------
def reshape(self, *shape, order='C'):
"""Returns an array of a different shape and the same content.
.. seealso::
:func:`cupy.reshape` for full documentation,
:meth:`numpy.ndarray.reshape`
"""
return _manipulation._ndarray_reshape(self, shape, order)
# TODO(okuta): Implement resize
def transpose(self, *axes):
"""Returns a view of the array with axes permuted.
.. seealso::
:func:`cupy.transpose` for full documentation,
:meth:`numpy.ndarray.reshape`
"""
return _manipulation._ndarray_transpose(self, axes)
cpdef _ndarray_base swapaxes(self, Py_ssize_t axis1, Py_ssize_t axis2):
"""Returns a view of the array with two axes swapped.
.. seealso::
:func:`cupy.swapaxes` for full documentation,
:meth:`numpy.ndarray.swapaxes`
"""
return _manipulation._ndarray_swapaxes(self, axis1, axis2)
cpdef _ndarray_base flatten(self, order='C'):
"""Returns a copy of the array flatten into one dimension.
Args:
order ({'C', 'F', 'A', 'K'}):
'C' means to flatten in row-major (C-style) order.
'F' means to flatten in column-major (Fortran-
style) order. 'A' means to flatten in column-major
order if `self` is Fortran *contiguous* in memory,
row-major order otherwise. 'K' means to flatten
`self` in the order the elements occur in memory.
The default is 'C'.
Returns:
cupy.ndarray: A copy of the array with one dimension.
.. seealso:: :meth:`numpy.ndarray.flatten`
"""
return _manipulation._ndarray_flatten(self, order)
cpdef _ndarray_base ravel(self, order='C'):
"""Returns an array flattened into one dimension.
.. seealso::
:func:`cupy.ravel` for full documentation,
:meth:`numpy.ndarray.ravel`
"""
return _internal_ascontiguousarray(
_manipulation._ndarray_ravel(self, order))
cpdef _ndarray_base squeeze(self, axis=None):
"""Returns a view with size-one axes removed.
.. seealso::
:func:`cupy.squeeze` for full documentation,
:meth:`numpy.ndarray.squeeze`
"""
return _manipulation._ndarray_squeeze(self, axis)
# -------------------------------------------------------------------------
# Item selection and manipulation
# -------------------------------------------------------------------------
cpdef _ndarray_base take(self, indices, axis=None, out=None):
"""Returns an array of elements at given indices along the axis.
.. seealso::
:func:`cupy.take` for full documentation,
:meth:`numpy.ndarray.take`
"""
return _indexing._ndarray_take(self, indices, axis, out)
cpdef put(self, indices, values, mode='wrap'):
"""Replaces specified elements of an array with given values.
.. seealso::
:func:`cupy.put` for full documentation,
:meth:`numpy.ndarray.put`
"""
return _indexing._ndarray_put(self, indices, values, mode)
cpdef repeat(self, repeats, axis=None):
"""Returns an array with repeated arrays along an axis.
.. seealso::
:func:`cupy.repeat` for full documentation,
:meth:`numpy.ndarray.repeat`
"""
return _manipulation._ndarray_repeat(self, repeats, axis)
cpdef choose(self, choices, out=None, mode='raise'):
# TODO(niboshi): Write docstring
return _indexing._ndarray_choose(self, choices, out, mode)
cpdef sort(self, int axis=-1):
"""Sort an array, in-place with a stable sorting algorithm.
Args:
axis (int): Axis along which to sort. Default is -1, which means
sort along the last axis.
.. note::
For its implementation reason, ``ndarray.sort`` currently supports
only arrays with their own data, and does not support ``kind`` and
``order`` parameters that ``numpy.ndarray.sort`` does support.
.. seealso::
:func:`cupy.sort` for full documentation,
:meth:`numpy.ndarray.sort`
"""
# TODO(takagi): Support kind argument.
_sorting._ndarray_sort(self, axis)
cpdef _ndarray_base argsort(self, axis=-1):
"""Returns the indices that would sort an array with stable sorting
Args:
axis (int or None): Axis along which to sort. Default is -1, which
means sort along the last axis. If None is supplied, the array
is flattened before sorting.
Returns:
cupy.ndarray: Array of indices that sort the array.
.. seealso::
:func:`cupy.argsort` for full documentation,
:meth:`numpy.ndarray.argsort`
"""
# TODO(takagi): Support kind argument.
return _sorting._ndarray_argsort(self, axis)
cpdef partition(self, kth, int axis=-1):
"""Partitions an array.
Args:
kth (int or sequence of ints): Element index to partition by. If
supplied with a sequence of k-th it will partition all elements
indexed by k-th of them into their sorted position at once.
axis (int): Axis along which to sort. Default is -1, which means
sort along the last axis.
.. seealso::
:func:`cupy.partition` for full documentation,
:meth:`numpy.ndarray.partition`
"""
_sorting._ndarray_partition(self, kth, axis)
cpdef _ndarray_base argpartition(self, kth, axis=-1):
"""Returns the indices that would partially sort an array.
Args:
kth (int or sequence of ints): Element index to partition by. If
supplied with a sequence of k-th it will partition all elements
indexed by k-th of them into their sorted position at once.
axis (int or None): Axis along which to sort. Default is -1, which
means sort along the last axis. If None is supplied, the array
is flattened before sorting.
Returns:
cupy.ndarray: Array of the same type and shape as ``a``.
.. seealso::
:func:`cupy.argpartition` for full documentation,
:meth:`numpy.ndarray.argpartition`
"""
return _sorting._ndarray_argpartition(self, kth, axis)
def searchsorted(self, v, side='left', sorter=None):
"""Finds indices where elements of v should be inserted to maintain order.
For full documentation, see :func:`cupy.searchsorted`
Returns:
.. seealso:: :func:`numpy.searchsorted`
"""
return cupy.searchsorted(self, v, side, sorter)
cpdef tuple nonzero(self):
"""Return the indices of the elements that are non-zero.
Returned Array is containing the indices of the non-zero elements
in that dimension.
Returns:
tuple of arrays: Indices of elements that are non-zero.
.. warning::
This function may synchronize the device.
.. seealso::
:func:`numpy.nonzero`
"""
return _indexing._ndarray_nonzero(self)
cpdef _ndarray_base compress(self, condition, axis=None, out=None):
"""Returns selected slices of this array along given axis.
.. warning::
This function may synchronize the device.
.. seealso::
:func:`cupy.compress` for full documentation,
:meth:`numpy.ndarray.compress`
"""
return _indexing._ndarray_compress(self, condition, axis, out)
cpdef _ndarray_base diagonal(self, offset=0, axis1=0, axis2=1):
"""Returns a view of the specified diagonals.
.. seealso::
:func:`cupy.diagonal` for full documentation,
:meth:`numpy.ndarray.diagonal`
"""
return _indexing._ndarray_diagonal(self, offset, axis1, axis2)
# -------------------------------------------------------------------------
# Calculation
# -------------------------------------------------------------------------
cpdef _ndarray_base max(self, axis=None, out=None, keepdims=False):
"""Returns the maximum along a given axis.
.. seealso::
:func:`cupy.amax` for full documentation,
:meth:`numpy.ndarray.max`