-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy path_usmarray.pyx
More file actions
1967 lines (1692 loc) · 66.3 KB
/
_usmarray.pyx
File metadata and controls
1967 lines (1692 loc) · 66.3 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
# Data Parallel Control (dpctl)
#
# Copyright 2020-2025 Intel 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.
# distutils: language = c++
# cython: language_level=3
# cython: linetrace=True
import numpy as np
import dpctl
import dpctl.memory as dpmem
from .._backend cimport DPCTLSyclUSMRef
from .._sycl_device_factory cimport _cached_default_device
from ._data_types import bool as dpt_bool
from ._device import Device
from ._print import usm_ndarray_repr, usm_ndarray_str
from cpython.mem cimport PyMem_Free
from cpython.tuple cimport PyTuple_New, PyTuple_SetItem
cimport dpctl as c_dpctl
cimport dpctl.memory as c_dpmem
cimport dpctl.tensor._dlpack as c_dlpack
from ._dlpack import get_build_dlpack_version
from .._sycl_device_factory cimport _cached_default_device
from enum import IntEnum
import dpctl.tensor._flags as _flags
from dpctl.tensor._tensor_impl import default_device_fp_type
include "_stride_utils.pxi"
include "_types.pxi"
include "_slicing.pxi"
class DLDeviceType(IntEnum):
"""
An :class:`enum.IntEnum` for the types of DLDevices supported by the DLPack
protocol.
``kDLCPU``:
CPU (host) device
``kDLCUDA``:
CUDA GPU device
``kDLCUDAHost``:
Pinned CUDA CPU memory by cudaMallocHost
``kDLOpenCL``:
OpenCL device
``kDLVulkan``:
Vulkan buffer
``kDLMetal``:
Metal for Apple GPU
``kDLVPI``:
Verilog simulator buffer
``kDLROCM``:
ROCm GPU device
``kDLROCMHost``:
Pinned ROCm CPU memory allocated by hipMallocHost
``kDLExtDev``:
Reserved extension device type used to test new devices
``kDLCUDAManaged``:
CUDA managed/unified memory allocated by cudaMallocManaged
``kDLOneAPI``:
Unified shared memory allocated on a oneAPI non-partitioned device
``kDLWebGPU``:
Device support for WebGPU standard
``kDLHexagon``:
Qualcomm Hexagon DSP
``kDLMAIA``:
Microsoft MAIA device
``kDLTrn``:
AWS Trainium device
"""
kDLCPU = c_dlpack.device_CPU
kDLCUDA = c_dlpack.device_CUDA
kDLCUDAHost = c_dlpack.device_CUDAHost
kDLCUDAManaged = c_dlpack.device_CUDAManaged
kDLROCM = c_dlpack.device_DLROCM
kDLROCMHost = c_dlpack.device_ROCMHost
kDLOpenCL = c_dlpack.device_OpenCL
kDLVulkan = c_dlpack.device_Vulkan
kDLMetal = c_dlpack.device_Metal
kDLVPI = c_dlpack.device_VPI
kDLOneAPI = c_dlpack.device_OneAPI
kDLWebGPU = c_dlpack.device_WebGPU
kDLHexagon = c_dlpack.device_Hexagon
kDLMAIA = c_dlpack.device_MAIA
kDLTrn = c_dlpack.device_Trn
cdef class InternalUSMArrayError(Exception):
"""
An InternalUSMArrayError exception is raised when internal
inconsistency has been detected in :class:`.usm_ndarray`.
"""
pass
cdef object _as_zero_dim_ndarray(object usm_ary):
"Convert size-1 array to NumPy 0d array"
mem_view = dpmem.as_usm_memory(usm_ary)
usm_ary.sycl_queue.wait()
host_buf = mem_view.copy_to_host()
view = host_buf.view(usm_ary.dtype)
view.shape = tuple()
return view
cdef inline void _check_0d_scalar_conversion(object usm_ary) except *:
"Raise TypeError if array cannot be converted to a Python scalar"
if (usm_ary.ndim != 0):
raise TypeError(
"only 0-dimensional arrays can be converted to Python scalars"
)
cdef int _copy_writable(int lhs_flags, int rhs_flags):
"Copy the WRITABLE flag to lhs_flags from rhs_flags"
return (lhs_flags & ~USM_ARRAY_WRITABLE) | (rhs_flags & USM_ARRAY_WRITABLE)
cdef bint _is_host_cpu(object dl_device):
"Check if dl_device denotes (kDLCPU, 0)"
cdef object dl_type
cdef object dl_id
cdef Py_ssize_t n_elems = -1
try:
n_elems = len(dl_device)
except TypeError:
pass
if n_elems != 2:
return False
dl_type = dl_device[0]
dl_id = dl_device[1]
if isinstance(dl_type, str):
return (dl_type == "kDLCPU" and dl_id == 0)
return (dl_type == DLDeviceType.kDLCPU) and (dl_id == 0)
cdef void _validate_and_use_stream(
object stream, c_dpctl.SyclQueue self_queue
) except *:
if (stream is None or stream == self_queue):
pass
else:
if not isinstance(stream, dpctl.SyclQueue):
raise TypeError(
"stream argument type was expected to be dpctl.SyclQueue,"
f" got {type(stream)} instead"
)
ev = self_queue.submit_barrier()
stream.submit_barrier(dependent_events=[ev])
cdef class usm_ndarray:
""" usm_ndarray(shape, dtype=None, strides=None, buffer="device", \
offset=0, order="C", buffer_ctor_kwargs=dict(), \
array_namespace=None)
An array object represents a multidimensional tensor of numeric
elements stored in a USM allocation on a SYCL device.
Arg:
shape (int, tuple):
Shape of the array to be created.
dtype (str, dtype):
Array data type, i.e. the type of array elements.
If ``dtype`` has the value ``None``, it is determined by default
floating point type supported by target device.
The supported types are
``bool``:
boolean type
``int8``, ``int16``, ``int32``, ``int64``:
signed integer types
``uint8``, ``uint16``, ``uint32``, ``uint64``:
unsigned integer types
``float16``:
half-precision floating type,
supported if target device's property
``has_aspect_fp16`` is ``True``
``float32``, ``complex64``:
single-precision real and complex floating types
``float64``, ``complex128``:
double-precision real and complex floating
types, supported if target device's property
``has_aspect_fp64`` is ``True``.
Default: ``None``.
strides (tuple, optional):
Strides of the array to be created in elements.
If ``strides`` has the value ``None``, it is determined by the
``shape`` of the array and the requested ``order``.
Default: ``None``.
buffer (str, object, optional):
A string corresponding to the type of USM allocation to make,
or a Python object representing a USM memory allocation, i.e.
:class:`dpctl.memory.MemoryUSMDevice`,
:class:`dpctl.memory.MemoryUSMShared`, or
:class:`dpctl.memory.MemoryUSMHost`. Recognized strings are
``"device"``, ``"shared"``, or ``"host"``. Additional arguments to
the USM memory allocators can be passed in a dictionary specified
via ``buffer_ctor_kwrds`` keyword parameter.
Default: ``"device"``.
offset (int, optional):
Offset of the array element with all zero indexes relative to the
start of the provided `buffer` in elements. The argument is ignored
if the ``buffer`` value is a string and the memory is allocated by
the constructor. Default: ``0``.
order ({"C", "F"}, optional):
The memory layout of the array when constructing using a new
allocation. Value ``"C"`` corresponds to C-contiguous, or row-major
memory layout, while value ``"F"`` corresponds to F-contiguous, or
column-major layout. Default: ``"C"``.
buffer_ctor_kwargs (dict, optional):
Dictionary with keyword parameters to use when creating a new USM
memory allocation. See :class:`dpctl.memory.MemoryUSMShared` for
supported keyword arguments.
array_namespace (module, optional):
Array namespace module associated with this array.
Default: ``None``.
``buffer`` can be ``"shared"``, ``"host"``, ``"device"`` to allocate
new device memory by calling respective constructor with
the specified ``buffer_ctor_kwrds``; ``buffer`` can be an
instance of :class:`dpctl.memory.MemoryUSMShared`,
:class:`dpctl.memory.MemoryUSMDevice`, or
:class:`dpctl.memory.MemoryUSMHost`; ``buffer`` can also be
another :class:`dpctl.tensor.usm_ndarray` instance, in which case its
underlying ``MemoryUSM*`` buffer is used.
"""
cdef void _reset(usm_ndarray self):
"""
Initializes member fields
"""
self.base_ = None
self.array_namespace_ = None
self.nd_ = -1
self.data_ = <char *>0
self.shape_ = <Py_ssize_t *>0
self.strides_ = <Py_ssize_t *>0
self.flags_ = 0
cdef void _cleanup(usm_ndarray self):
if (self.shape_):
PyMem_Free(self.shape_)
if (self.strides_):
PyMem_Free(self.strides_)
self._reset()
def __cinit__(self, shape, dtype=None, strides=None, buffer="device",
Py_ssize_t offset=0, order="C",
buffer_ctor_kwargs=dict(),
array_namespace=None):
"""
strides and offset must be given in units of array elements.
buffer can be strings ('device'|'shared'|'host' to allocate new memory)
or ``dpctl.memory.MemoryUSM*`` buffers, or ``usm_ndarray`` instances.
"""
cdef int nd = 0
cdef int typenum = 0
cdef int itemsize = 0
cdef int err = 0
cdef int contig_flag = 0
cdef int writable_flag = USM_ARRAY_WRITABLE
cdef Py_ssize_t *shape_ptr = NULL
cdef Py_ssize_t ary_nelems = 0
cdef Py_ssize_t ary_nbytes = 0
cdef Py_ssize_t *strides_ptr = NULL
cdef Py_ssize_t _offset = offset
cdef Py_ssize_t ary_min_displacement = 0
cdef Py_ssize_t ary_max_displacement = 0
cdef bint is_fp64 = False
cdef bint is_fp16 = False
self._reset()
if not isinstance(shape, (list, tuple)):
if hasattr(shape, "tolist"):
fn = getattr(shape, "tolist")
if callable(fn):
shape = shape.tolist()
if not isinstance(shape, (list, tuple)):
try:
<Py_ssize_t> shape
shape = [shape, ]
except Exception as e:
raise TypeError(
"Argument shape must a non-negative integer, "
"or a list/tuple of such integers."
) from e
nd = len(shape)
if dtype is None:
if isinstance(buffer, (dpmem._memory._Memory, usm_ndarray)):
q = buffer.sycl_queue
else:
q = buffer_ctor_kwargs.get("queue")
if q is not None:
dtype = default_device_fp_type(q)
else:
dev = _cached_default_device()
dtype = "f8" if dev.has_aspect_fp64 else "f4"
typenum = dtype_to_typenum(dtype)
if (typenum < 0):
if typenum == -2:
raise ValueError(
"Data type '" + str(dtype) +
"' can only have native byteorder."
)
elif typenum == -1:
raise ValueError(
"Data type '" + str(dtype) + "' is not understood."
)
raise TypeError(
f"Expected string or a dtype object, got {type(dtype)}"
)
itemsize = type_bytesize(typenum)
if (itemsize < 1):
raise TypeError(
"dtype=" + np.dtype(dtype).name + " is not supported."
)
# allocate host C-arrays for shape, strides
err = _from_input_shape_strides(
nd, shape, strides, itemsize, <char> ord(order),
&shape_ptr, &strides_ptr, &ary_nelems,
&ary_min_displacement, &ary_max_displacement, &contig_flag
)
if (err):
self._cleanup()
if err == ERROR_MALLOC:
raise MemoryError("Memory allocation for shape/strides "
"array failed.")
elif err == ERROR_INCORRECT_ORDER:
raise ValueError(
"Unsupported order='{}' given. "
"Supported values are 'C' or 'F'.".format(order))
elif err == ERROR_UNEXPECTED_STRIDES:
raise ValueError(
"strides={} is not understood".format(strides))
else:
raise InternalUSMArrayError(
" .. while processing shape and strides.")
ary_nbytes = (ary_max_displacement -
ary_min_displacement + 1) * itemsize
if isinstance(buffer, dpmem._memory._Memory):
_buffer = buffer
elif isinstance(buffer, (str, bytes)):
if isinstance(buffer, bytes):
buffer = buffer.decode("UTF-8")
_offset = -ary_min_displacement
if (buffer == "shared"):
_buffer = dpmem.MemoryUSMShared(ary_nbytes,
**buffer_ctor_kwargs)
elif (buffer == "device"):
_buffer = dpmem.MemoryUSMDevice(ary_nbytes,
**buffer_ctor_kwargs)
elif (buffer == "host"):
_buffer = dpmem.MemoryUSMHost(ary_nbytes,
**buffer_ctor_kwargs)
else:
self._cleanup()
raise ValueError(
"buffer='{}' is not understood. "
"Recognized values are 'device', 'shared', 'host', "
"an instance of `MemoryUSM*` object, or a usm_ndarray"
"".format(buffer)
)
elif isinstance(buffer, usm_ndarray):
if not buffer.flags.writable:
writable_flag = 0
_buffer = buffer.usm_data
else:
self._cleanup()
raise ValueError("buffer='{}' was not understood.".format(buffer))
if (shape_to_elem_count(nd, shape_ptr) > 0 and
(_offset + ary_min_displacement < 0 or
(_offset + ary_max_displacement + 1) * itemsize > _buffer.nbytes)):
self._cleanup()
raise ValueError(("buffer='{}' can not accommodate "
"the requested array.").format(buffer))
is_fp64 = (typenum == UAR_DOUBLE or typenum == UAR_CDOUBLE)
is_fp16 = (typenum == UAR_HALF)
if (is_fp64 or is_fp16):
if (
(is_fp64 and not _buffer.sycl_device.has_aspect_fp64) or
(is_fp16 and not _buffer.sycl_device.has_aspect_fp16)
):
raise ValueError(
f"Device {_buffer.sycl_device.name} does"
f" not support {dtype} natively."
)
self.base_ = _buffer
self.data_ = (<char *> (<size_t> _buffer._pointer)) + itemsize * _offset
self.shape_ = shape_ptr
self.strides_ = strides_ptr
self.typenum_ = typenum
self.flags_ = (contig_flag | writable_flag)
self.nd_ = nd
self.array_namespace_ = array_namespace
def __dealloc__(self):
self._cleanup()
@property
def _pointer(self):
"""
Returns USM pointer to the start of array (element with zero
multi-index) encoded as integer.
"""
return <size_t> self.get_data()
cdef Py_ssize_t get_offset(self) except *:
cdef char *mem_ptr = NULL
cdef char *ary_ptr = self.get_data()
mem_ptr = <char *>(<size_t> self.base_._pointer)
byte_offset = ary_ptr - mem_ptr
item_size = self.get_itemsize()
if (byte_offset % item_size):
raise InternalUSMArrayError(
"byte_offset is not a multiple of item_size.")
return byte_offset // item_size
@property
def _element_offset(self):
"""Returns the offset of the zero-index element of the array, in
elements, relative to the start of memory allocation"""
return self.get_offset()
@property
def _byte_bounds(self):
"""Returns a 2-tuple with pointers to the end-points of the array
:Example:
.. code-block:: python
from dpctl import tensor
x = tensor.ones((3, 10, 7))
y = tensor.flip(x[:, 1::2], axis=1)
beg_p, end_p = y._byte_bounds
# Bytes taken to store this array
bytes_extent = end_p - beg_p
# C-contiguous copy is more compact
yc = tensor.copy(y, order="C")
beg_pc, end_pc = yc._byte_bounds
assert bytes_extent < end_pc - beg_pc
"""
cdef Py_ssize_t min_disp = 0
cdef Py_ssize_t max_disp = 0
cdef Py_ssize_t step_ = 0
cdef Py_ssize_t dim_ = 0
cdef int it = 0
cdef Py_ssize_t _itemsize = self.get_itemsize()
if (
(self.flags_ & USM_ARRAY_C_CONTIGUOUS)
or (self.flags_ & USM_ARRAY_F_CONTIGUOUS)
):
return (
self._pointer,
self._pointer + shape_to_elem_count(
self.nd_, self.shape_
) * _itemsize
)
for it in range(self.nd_):
dim_ = self.shape[it]
if dim_ > 0:
step_ = self.strides[it]
if step_ > 0:
max_disp += step_ * (dim_ - 1)
else:
min_disp += step_ * (dim_ - 1)
return (
self._pointer + min_disp * _itemsize,
self._pointer + (max_disp + 1) * _itemsize
)
cdef char* get_data(self):
"""Returns the USM pointer for this array."""
return self.data_
cdef int get_ndim(self):
"""
Returns the number of indices needed to address
an element of this array.
"""
return self.nd_
cdef Py_ssize_t* get_shape(self):
"""
Returns pointer to shape C-array for this array.
C-array has at least ``ndim`` non-negative elements,
which determine the range of permissible indices
addressing individual elements of this array.
"""
return self.shape_
cdef Py_ssize_t* get_strides(self):
"""
Returns pointer to strides C-array for this array.
The pointer can be NULL (contiguous array), or the
array size is at least ``ndim`` elements
"""
return self.strides_
cdef int get_typenum(self):
"""Returns typenum corresponding to values of this array"""
return self.typenum_
cdef int get_itemsize(self):
"""
Returns itemsize of this arrays in bytes
"""
return type_bytesize(self.typenum_)
cdef int get_flags(self):
"""Returns flags of this array"""
return self.flags_
cdef object get_base(self):
"""Returns the object owning the USM data addressed by this array"""
return self.base_
cdef c_dpctl.SyclQueue get_sycl_queue(self):
cdef c_dpmem._Memory mem
if not isinstance(self.base_, dpctl.memory._Memory):
raise InternalUSMArrayError(
"This array has unexpected memory owner"
)
mem = <c_dpmem._Memory> self.base_
return mem.queue
cdef c_dpctl.DPCTLSyclQueueRef get_queue_ref(self) except *:
"""
Returns a copy of DPCTLSyclQueueRef associated with array
"""
cdef c_dpctl.SyclQueue q = self.get_sycl_queue()
cdef c_dpctl.DPCTLSyclQueueRef QRef = q.get_queue_ref()
cdef c_dpctl.DPCTLSyclQueueRef QRefCopy = NULL
if QRef is not NULL:
QRefCopy = c_dpctl.DPCTLQueue_Copy(QRef)
return QRefCopy
else:
raise InternalUSMArrayError(
"Memory owner of this array is corrupted"
)
@property
def __sycl_usm_array_interface__(self):
"""
Gives ``__sycl_usm_array_interface__`` dictionary describing
the array.
"""
cdef Py_ssize_t byte_offset = -1
cdef int item_size = -1
cdef Py_ssize_t elem_offset = -1
cdef char *mem_ptr = NULL
cdef char *ary_ptr = NULL
if (not isinstance(self.base_, dpmem._memory._Memory)):
raise InternalUSMArrayError(
"Invalid instance of usm_ndarray encountered. "
"Private field base_ has an unexpected type {}.".format(
type(self.base_)
)
)
ary_iface = self.base_.__sycl_usm_array_interface__
mem_ptr = <char *>(<size_t> ary_iface["data"][0])
ary_ptr = <char *>(<size_t> self.data_)
ro_flag = False if (self.flags_ & USM_ARRAY_WRITABLE) else True
ary_iface["data"] = (<size_t> mem_ptr, ro_flag)
ary_iface["shape"] = self.shape
if (self.strides_):
ary_iface["strides"] = _make_int_tuple(self.nd_, self.strides_)
else:
if (self.flags_ & USM_ARRAY_C_CONTIGUOUS):
ary_iface["strides"] = None
elif (self.flags_ & USM_ARRAY_F_CONTIGUOUS):
ary_iface["strides"] = _f_contig_strides(self.nd_, self.shape_)
else:
raise InternalUSMArrayError(
"USM Array is not contiguous and has empty strides"
)
ary_iface["typestr"] = _make_typestr(self.typenum_)
byte_offset = ary_ptr - mem_ptr
item_size = self.get_itemsize()
if (byte_offset % item_size):
raise InternalUSMArrayError(
"byte_offset is not a multiple of item_size.")
elem_offset = byte_offset // item_size
ary_iface["offset"] = elem_offset
# must wait for content of the memory to finalize
self.sycl_queue.wait()
return ary_iface
@property
def ndim(self):
"""
Gives the number of indices needed to address elements of this array.
"""
return self.nd_
@property
def usm_data(self):
"""
Gives USM memory object underlying :class:`.usm_ndarray` instance.
"""
return self.get_base()
@property
def shape(self):
"""
Elements of the shape tuple give the lengths of the
respective array dimensions.
Setting shape is allowed only when reshaping to the requested
dimensions can be returned as view, otherwise :exc:`AttributeError`
is raised. Use :func:`dpctl.tensor.reshape` to reshape the array
in all cases.
:Example:
.. code-block:: python
from dpctl import tensor
x = tensor.arange(899)
x.shape = (29, 31)
"""
if self.nd_ > 0:
return _make_int_tuple(self.nd_, self.shape_)
else:
return tuple()
@shape.setter
def shape(self, new_shape):
"""
Modifies usm_ndarray instance in-place by changing its metadata
about the shape and the strides of the array, or raises
`AttributeError` exception if in-place change is not possible.
Args:
new_shape: (tuple, int)
New shape. Only non-negative values are supported.
The new shape may not lead to the change in the
number of elements in the array.
Whether the array can be reshape in-place depends on its
strides. Use :func:`dpctl.tensor.reshape` function which
always succeeds to reshape the array by performing a copy
if necessary.
"""
cdef int new_nd = -1
cdef Py_ssize_t nelems = -1
cdef int err = 0
cdef Py_ssize_t min_disp = 0
cdef Py_ssize_t max_disp = 0
cdef int contig_flag = 0
cdef Py_ssize_t *shape_ptr = NULL
cdef Py_ssize_t *strides_ptr = NULL
cdef Py_ssize_t size = -1
import operator
from ._reshape import reshaped_strides
try:
new_nd = len(new_shape)
except TypeError:
new_nd = 1
new_shape = (new_shape,)
try:
new_shape = tuple(operator.index(dim) for dim in new_shape)
except TypeError:
raise TypeError(
"Target shape must be a finite iterable of integers"
)
size = shape_to_elem_count(self.nd_, self.shape_)
if not np.prod(new_shape) == size:
raise TypeError(
f"Can not reshape array of size {self.size} into {new_shape}"
)
if size > 0:
new_strides = reshaped_strides(
self.shape,
self.strides,
new_shape
)
else:
new_strides = (1,) * len(new_shape)
if new_strides is None:
raise AttributeError(
"Incompatible shape for in-place modification. "
"Use `reshape()` to make a copy with the desired shape."
)
err = _from_input_shape_strides(
new_nd, new_shape, new_strides,
self.get_itemsize(),
b"C",
&shape_ptr, &strides_ptr,
&nelems, &min_disp, &max_disp, &contig_flag
)
if (err == 0):
if (self.shape_):
PyMem_Free(self.shape_)
if (self.strides_):
PyMem_Free(self.strides_)
self.flags_ = (contig_flag | (self.flags_ & USM_ARRAY_WRITABLE))
self.nd_ = new_nd
self.shape_ = shape_ptr
self.strides_ = strides_ptr
else:
raise InternalUSMArrayError(
"Encountered in shape setter, error code {err}".format(err)
)
@property
def strides(self):
"""
Returns memory displacement in array elements, upon unit
change of respective index.
For example, for strides ``(s1, s2, s3)`` and multi-index
``(i1, i2, i3)`` position of the respective element relative
to zero multi-index element is ``s1*s1 + s2*i2 + s3*i3``.
:Example:
.. code-block:: python
from dpctl import tensor
x = tensor.zeros((20, 30))
xv = x[10:, :15]
multi_id = (3, 5)
byte_displacement = xv[multi_id]._pointer - xv[0, 0]._pointer
element_displacement = sum(
i * s for i, s in zip(multi_id, xv.strides)
)
assert byte_displacement == element_displacement * xv.itemsize
"""
if (self.strides_):
return _make_int_tuple(self.nd_, self.strides_)
else:
if (self.flags_ & USM_ARRAY_C_CONTIGUOUS):
return _c_contig_strides(self.nd_, self.shape_)
elif (self.flags_ & USM_ARRAY_F_CONTIGUOUS):
return _f_contig_strides(self.nd_, self.shape_)
else:
raise ValueError("Inconsistent usm_ndarray data")
@property
def flags(self):
"""
Returns :class:`dpctl.tensor._flags.Flags` object.
"""
return _flags.Flags(self, self.flags_)
cdef _set_writable_flag(self, int flag):
cdef int mask = (USM_ARRAY_WRITABLE if flag else 0)
self.flags_ = _copy_writable(self.flags_, mask)
@property
def usm_type(self):
"""
USM type of underlying memory. Possible values are:
* ``"device"``
USM-device allocation in device memory, only accessible
to kernels executed on the device
* ``"shared"``
USM-shared allocation in device memory, accessible both
from the device and from host
* ``"host"``
USM-host allocation in host memory, accessible both
from the device and from host
See: https://docs.oneapi.com/versions/latest/dpcpp/iface/usm.html
"""
return self.base_.get_usm_type()
@property
def itemsize(self):
"""
Size of array element in bytes.
"""
return self.get_itemsize()
@property
def nbytes(self):
"""
Total bytes consumed by the elements of the array.
"""
return (
shape_to_elem_count(self.nd_, self.shape_) *
self.get_itemsize())
@property
def size(self):
"""
Number of elements in the array.
"""
return shape_to_elem_count(self.nd_, self.shape_)
@property
def dtype(self):
"""
Returns NumPy's dtype corresponding to the type of the array elements.
"""
return np.dtype(_make_typestr(self.typenum_))
@property
def sycl_queue(self):
"""
Returns :class:`dpctl.SyclQueue` object associated with USM data.
"""
return self.get_sycl_queue()
@property
def sycl_device(self):
"""
Returns :class:`dpctl.SyclDevice` object on which USM data
was allocated.
"""
q = self.sycl_queue
return q.sycl_device
@property
def device(self):
"""
Returns :class:`dpctl.tensor.Device` object representing
residence of the array data.
The ``Device`` object represents Array API notion of the
device, and contains :class:`dpctl.SyclQueue` associated
with this array. Hence, ``.device`` property provides
information distinct from ``.sycl_device`` property.
:Example:
.. code-block:: python
>>> from dpctl import tensor
>>> x = tensor.ones(10)
>>> x.device
Device(level_zero:gpu:0)
"""
return Device.create_device(self.sycl_queue)
@property
def sycl_context(self):
"""
Returns :class:`dpctl.SyclContext` object to which USM data is bound.
"""
q = self.sycl_queue
return q.sycl_context
@property
def T(self):
"""Returns transposed array for 2D array, raises ``ValueError``
otherwise.
"""
if self.nd_ == 2:
return _transpose(self)
else:
raise ValueError(
"array.T requires array to have 2 dimensions. "
"Use array.mT to transpose stacks of matrices and "
"dpctl.tensor.permute_dims() to permute dimensions."
)
@property
def mT(self):
""" Returns array (a view) where the last two dimensions are
transposed.
"""
if self.nd_ < 2:
raise ValueError(
"array.mT requires array to have at least 2 dimensions."
)
return _m_transpose(self)
@property
def real(self):
"""
Returns view into real component for arrays with
complex data-types and returns itself for all other
data-types.
:Example:
.. code-block:: python
from dpctl import tensor
# Create complex array from
# arrays of real and imaginary parts
re = tensor.linspace(-1, 1, num=100, dtype="f4")
im = tensor.full_like(re, fill_value=tensor.pi)
z = tensor.empty_like(re, dtype="c8")
z.real[:] = re
z.imag[:] = im
"""
# explicitly check for UAR_HALF, which is greater than UAR_CFLOAT
if (self.typenum_ < UAR_CFLOAT or self.typenum_ == UAR_HALF):
# elements are real
return self
if (self.typenum_ < UAR_TYPE_SENTINEL):
return _real_view(self)
@property
def imag(self):
""" Returns view into imaginary component for arrays with
complex data-types and returns new zero array for all other
data-types.
:Example:
.. code-block:: python
from dpctl import tensor
# Reset imaginary part of complex array
z = tensor.ones(100, dtype="c8")
z.imag[:] = dpt.pi/2
"""
# explicitly check for UAR_HALF, which is greater than UAR_CFLOAT
if (self.typenum_ < UAR_CFLOAT or self.typenum_ == UAR_HALF):
# elements are real
return _zero_like(self)
if (self.typenum_ < UAR_TYPE_SENTINEL):
return _imag_view(self)
def __getitem__(self, ind):
cdef tuple _meta = _basic_slice_meta(
ind, (<object>self).shape, (<object> self).strides,
self.get_offset())
cdef usm_ndarray res
cdef int i = 0
cdef bint matching = 1
if len(_meta) < 5:
raise RuntimeError
res = usm_ndarray.__new__(
usm_ndarray,
_meta[0],
dtype=_make_typestr(self.typenum_),
strides=_meta[1],
buffer=self.base_,
offset=_meta[2]
)
res.array_namespace_ = self.array_namespace_
adv_ind = _meta[3]
adv_ind_start_p = _meta[4]
if adv_ind_start_p < 0:
res.flags_ = _copy_writable(res.flags_, self.flags_)
return res
from ._copy_utils import _extract_impl, _nonzero_impl, _take_multi_index
# if len(adv_ind == 1), the (only) element is always an array
if len(adv_ind) == 1 and adv_ind[0].dtype == dpt_bool:
key_ = adv_ind[0]
adv_ind_end_p = key_.ndim + adv_ind_start_p
if adv_ind_end_p > res.ndim:
raise IndexError("too many indices for the array")
key_shape = key_.shape