-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy path_ctors.py
More file actions
1977 lines (1838 loc) · 69.4 KB
/
_ctors.py
File metadata and controls
1977 lines (1838 loc) · 69.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# *****************************************************************************
# Copyright (c) 2026, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# *****************************************************************************
import operator
from numbers import Number
import dpctl
import dpctl.memory as dpm
import dpctl.tensor as dpt
import dpctl.utils
import numpy as np
from dpctl.tensor._data_types import _get_dtype
from dpctl.tensor._device import normalize_queue_device
from dpctl.tensor._usmarray import _is_object_with_buffer_protocol
# TODO: revert to `import dpctl.tensor...`
# when dpnp fully migrates dpctl/tensor
import dpctl_ext.tensor as dpt_ext
import dpctl_ext.tensor._tensor_impl as ti
from ._copy_utils import (
_empty_like_orderK,
_from_numpy_empty_like_orderK,
)
__doc__ = "Implementation of creation functions in :module:`dpctl.tensor`"
_empty_tuple = ()
_host_set = frozenset([None])
def _array_info_dispatch(obj):
if isinstance(obj, dpt.usm_ndarray):
return obj.shape, obj.dtype, frozenset([obj.sycl_queue])
if isinstance(obj, np.ndarray):
return obj.shape, obj.dtype, _host_set
if isinstance(obj, range):
return (len(obj),), int, _host_set
if isinstance(obj, bool):
return _empty_tuple, bool, _host_set
if isinstance(obj, float):
return _empty_tuple, float, _host_set
if isinstance(obj, int):
return _empty_tuple, int, _host_set
if isinstance(obj, complex):
return _empty_tuple, complex, _host_set
if isinstance(
obj,
(
list,
tuple,
),
):
return _array_info_sequence(obj)
if _is_object_with_buffer_protocol(obj):
np_obj = np.array(obj)
return np_obj.shape, np_obj.dtype, _host_set
if hasattr(obj, "__usm_ndarray__"):
usm_ar = obj.__usm_ndarray__
if isinstance(usm_ar, dpt.usm_ndarray):
return usm_ar.shape, usm_ar.dtype, frozenset([usm_ar.sycl_queue])
if hasattr(obj, "__sycl_usm_array_interface__"):
usm_ar = _usm_ndarray_from_suai(obj)
return usm_ar.shape, usm_ar.dtype, frozenset([usm_ar.sycl_queue])
def _array_info_sequence(li):
if not isinstance(li, (list, tuple, range)):
raise TypeError(f"Expected list, tuple, or range, got {type(li)}")
n = len(li)
dim = None
dt = None
device = frozenset()
for el in li:
el_dim, el_dt, el_dev = _array_info_dispatch(el)
if dim is None:
dim = el_dim
dt = np.promote_types(el_dt, el_dt)
device = device.union(el_dev)
elif el_dim == dim:
dt = np.promote_types(dt, el_dt)
device = device.union(el_dev)
else:
raise ValueError(f"Inconsistent dimensions, {dim} and {el_dim}")
if dim is None:
dim = ()
dt = float
device = _host_set
return (n,) + dim, dt, device
def _asarray_from_numpy_ndarray(
ary, dtype=None, usm_type=None, sycl_queue=None, order="K"
):
if not isinstance(ary, np.ndarray):
raise TypeError(f"Expected numpy.ndarray, got {type(ary)}")
if usm_type is None:
usm_type = "device"
copy_q = normalize_queue_device(sycl_queue=None, device=sycl_queue)
if ary.dtype.char not in "?bBhHiIlLqQefdFD":
raise TypeError(
f"Numpy array of data type {ary.dtype} is not supported. "
"Please convert the input to an array with numeric data type."
)
if dtype is None:
# deduce device-representable output data type
dtype = _map_to_device_dtype(ary.dtype, copy_q)
_ensure_native_dtype_device_support(dtype, copy_q.sycl_device)
f_contig = ary.flags["F"]
c_contig = ary.flags["C"]
fc_contig = f_contig or c_contig
if order == "A":
order = "F" if f_contig and not c_contig else "C"
if order == "K" and fc_contig:
order = "C" if c_contig else "F"
if order == "K":
# new USM allocation
res = _from_numpy_empty_like_orderK(ary, dtype, usm_type, copy_q)
else:
res = dpt.usm_ndarray(
ary.shape,
dtype=dtype,
buffer=usm_type,
order=order,
buffer_ctor_kwargs={"queue": copy_q},
)
res[...] = ary
return res
def _asarray_from_seq(
seq_obj,
seq_shape,
seq_dt,
alloc_q,
exec_q,
dtype=None,
usm_type=None,
order="C",
):
"""`seq_obj` is a sequence"""
if usm_type is None:
usm_types_in_seq = []
_usm_types_walker(seq_obj, usm_types_in_seq)
usm_type = dpctl.utils.get_coerced_usm_type(usm_types_in_seq)
dpctl.utils.validate_usm_type(usm_type)
if dtype is None:
dtype = _map_to_device_dtype(seq_dt, alloc_q)
else:
_mapped_dt = _map_to_device_dtype(dtype, alloc_q)
if _mapped_dt != dtype:
raise ValueError(
f"Device {alloc_q.sycl_device} "
f"does not support {dtype} natively."
)
dtype = _mapped_dt
if order in "KA":
order = "C"
if isinstance(exec_q, dpctl.SyclQueue):
res = dpt_ext.empty(
seq_shape,
dtype=dtype,
usm_type=usm_type,
sycl_queue=alloc_q,
order=order,
)
_manager = dpctl.utils.SequentialOrderManager[exec_q]
_device_copy_walker(seq_obj, res, _manager)
return res
else:
res = dpt_ext.empty(
seq_shape,
dtype=dtype,
usm_type=usm_type,
sycl_queue=alloc_q,
order=order,
)
_copy_through_host_walker(seq_obj, res)
return res
def _asarray_from_seq_single_device(
obj,
seq_shape,
seq_dt,
seq_dev,
dtype=None,
usm_type=None,
sycl_queue=None,
order="C",
):
if sycl_queue is None:
exec_q = seq_dev
alloc_q = seq_dev
else:
exec_q = dpctl.utils.get_execution_queue(
(
sycl_queue,
seq_dev,
)
)
alloc_q = sycl_queue
return _asarray_from_seq(
obj,
seq_shape,
seq_dt,
alloc_q,
exec_q,
dtype=dtype,
usm_type=usm_type,
order=order,
)
def _asarray_from_usm_ndarray(
usm_ndary,
dtype=None,
copy=None,
usm_type=None,
sycl_queue=None,
order="K",
):
if not isinstance(usm_ndary, dpt.usm_ndarray):
raise TypeError(
f"Expected dpctl.tensor.usm_ndarray, got {type(usm_ndary)}"
)
if usm_type is None:
usm_type = usm_ndary.usm_type
if sycl_queue is not None:
exec_q = dpctl.utils.get_execution_queue(
[usm_ndary.sycl_queue, sycl_queue]
)
copy_q = normalize_queue_device(sycl_queue=sycl_queue, device=exec_q)
else:
copy_q = usm_ndary.sycl_queue
if dtype is None:
dtype = _map_to_device_dtype(usm_ndary.dtype, copy_q)
# Conditions for zero copy:
can_zero_copy = copy is not True
# dtype is unchanged
can_zero_copy = can_zero_copy and dtype == usm_ndary.dtype
# USM allocation type is unchanged
can_zero_copy = can_zero_copy and usm_type == usm_ndary.usm_type
# sycl_queue is unchanged
can_zero_copy = can_zero_copy and copy_q is usm_ndary.sycl_queue
# order is unchanged
c_contig = usm_ndary.flags.c_contiguous
f_contig = usm_ndary.flags.f_contiguous
fc_contig = usm_ndary.flags.forc
if can_zero_copy:
if order == "C" and c_contig:
pass
elif order == "F" and f_contig:
pass
elif order == "A" and fc_contig:
pass
elif order == "K":
pass
else:
can_zero_copy = False
if copy is False and can_zero_copy is False:
raise ValueError("asarray(..., copy=False) is not possible")
if can_zero_copy:
return usm_ndary
if order == "A":
order = "F" if f_contig and not c_contig else "C"
if order == "K" and fc_contig:
order = "C" if c_contig else "F"
if order == "K":
_ensure_native_dtype_device_support(dtype, copy_q.sycl_device)
res = _empty_like_orderK(usm_ndary, dtype, usm_type, copy_q)
else:
_ensure_native_dtype_device_support(dtype, copy_q.sycl_device)
res = dpt.usm_ndarray(
usm_ndary.shape,
dtype=dtype,
buffer=usm_type,
order=order,
buffer_ctor_kwargs={"queue": copy_q},
)
eq = dpctl.utils.get_execution_queue([usm_ndary.sycl_queue, copy_q])
if eq is not None:
_manager = dpctl.utils.SequentialOrderManager[eq]
dep_evs = _manager.submitted_events
hev, cpy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=usm_ndary, dst=res, sycl_queue=eq, depends=dep_evs
)
_manager.add_event_pair(hev, cpy_ev)
else:
tmp = dpt_ext.asnumpy(usm_ndary)
res[...] = tmp
return res
def _cast_fill_val(fill_val, dt):
"""
Casts the Python scalar `fill_val` to another Python type coercible to the
requested data type `dt`, if necessary.
"""
val_type = type(fill_val)
if val_type in [float, complex] and np.issubdtype(dt, np.integer):
return int(fill_val.real)
elif val_type is complex and np.issubdtype(dt, np.floating):
return fill_val.real
elif val_type is int and np.issubdtype(dt, np.integer):
return _to_scalar(fill_val, dt)
else:
return fill_val
def _coerce_and_infer_dt(*args, dt, sycl_queue, err_msg, allow_bool=False):
"""Deduce arange type from sequence spec"""
nd, seq_dt, d = _array_info_sequence(args)
if d != _host_set or nd != (len(args),):
raise ValueError(err_msg)
dt = _get_dtype(dt, sycl_queue, ref_type=seq_dt)
if np.issubdtype(dt, np.integer):
return tuple(int(v) for v in args), dt
if np.issubdtype(dt, np.floating):
return tuple(float(v) for v in args), dt
if np.issubdtype(dt, np.complexfloating):
return tuple(complex(v) for v in args), dt
if allow_bool and dt.char == "?":
return tuple(bool(v) for v in args), dt
raise ValueError(f"Data type {dt} is not supported")
def _copy_through_host_walker(seq_o, usm_res):
if isinstance(seq_o, dpt.usm_ndarray):
if (
dpctl.utils.get_execution_queue(
(
usm_res.sycl_queue,
seq_o.sycl_queue,
)
)
is None
):
usm_res[...] = dpt_ext.asnumpy(seq_o).copy()
return
else:
usm_res[...] = seq_o
if hasattr(seq_o, "__usm_ndarray__"):
usm_arr = seq_o.__usm_ndarray__
if isinstance(usm_arr, dpt.usm_ndarray):
_copy_through_host_walker(usm_arr, usm_res)
return
if hasattr(seq_o, "__sycl_usm_array_interface__"):
usm_ar = _usm_ndarray_from_suai(seq_o)
if (
dpctl.utils.get_execution_queue(
(
usm_res.sycl_queue,
usm_ar.sycl_queue,
)
)
is None
):
usm_res[...] = dpt_ext.asnumpy(usm_ar).copy()
else:
usm_res[...] = usm_ar
return
if _is_object_with_buffer_protocol(seq_o):
np_ar = np.asarray(seq_o)
usm_res[...] = np_ar
return
if isinstance(seq_o, (list, tuple)):
for i, el in enumerate(seq_o):
_copy_through_host_walker(el, usm_res[i])
return
usm_res[...] = np.asarray(seq_o)
def _device_copy_walker(seq_o, res, _manager):
if isinstance(seq_o, dpt.usm_ndarray):
exec_q = res.sycl_queue
deps = _manager.submitted_events
ht_ev, cpy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=seq_o, dst=res, sycl_queue=exec_q, depends=deps
)
_manager.add_event_pair(ht_ev, cpy_ev)
return
if hasattr(seq_o, "__usm_ndarray__"):
usm_arr = seq_o.__usm_ndarray__
if isinstance(usm_arr, dpt.usm_ndarray):
_device_copy_walker(usm_arr, res, _manager)
return
if hasattr(seq_o, "__sycl_usm_array_interface__"):
usm_ar = _usm_ndarray_from_suai(seq_o)
exec_q = res.sycl_queue
deps = _manager.submitted_events
ht_ev, cpy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=usm_ar, dst=res, sycl_queue=exec_q, depends=deps
)
_manager.add_event_pair(ht_ev, cpy_ev)
return
if isinstance(seq_o, (list, tuple)):
for i, el in enumerate(seq_o):
_device_copy_walker(el, res[i], _manager)
return
raise TypeError
def _ensure_native_dtype_device_support(dtype, dev) -> None:
"""Check that dtype is natively supported by device.
Arg:
dtype:
Elemental data-type
dev (:class:`dpctl.SyclDevice`):
The device about which the query is being made.
Returns:
None
Raise:
ValueError:
if device does not natively support this `dtype`.
"""
if dtype in [dpt.float64, dpt.complex128] and not dev.has_aspect_fp64:
raise ValueError(
f"Device {dev.name} does not provide native support "
"for double-precision floating point type."
)
if (
dtype
in [
dpt.float16,
]
and not dev.has_aspect_fp16
):
raise ValueError(
f"Device {dev.name} does not provide native support "
"for half-precision floating point type."
)
def _get_arange_length(start, stop, step):
"""Compute length of arange sequence"""
span = stop - start
if hasattr(step, "__float__") and hasattr(span, "__float__"):
return _round_for_arange(span / step)
tmp = span / step
if hasattr(tmp, "__complex__"):
tmp = complex(tmp)
tmp = tmp.real
else:
tmp = float(tmp)
return _round_for_arange(tmp)
def _map_to_device_dtype(dt, q):
dtc = dt.char
if dtc == "?" or np.issubdtype(dt, np.integer):
return dt
d = q.sycl_device
if np.issubdtype(dt, np.floating):
if dtc == "f":
return dt
if dtc == "d" and d.has_aspect_fp64:
return dt
if dtc == "e" and d.has_aspect_fp16:
return dt
return dpt.dtype("f4")
if np.issubdtype(dt, np.complexfloating):
if dtc == "F":
return dt
if dtc == "D" and d.has_aspect_fp64:
return dt
return dpt.dtype("c8")
raise RuntimeError(f"Unrecognized data type '{dt}' encountered.")
def _normalize_order(order, arr):
"""
Utility function for processing the `order` keyword of array-like
constructors, which support `"K"` and `"A"` orders.
"""
arr_flags = arr.flags
f_contig = arr_flags["F"]
c_contig = arr_flags["C"]
if order == "A":
order = "F" if f_contig and not c_contig else "C"
if order == "K" and (f_contig or c_contig):
order = "C" if c_contig else "F"
return order
def _round_for_arange(tmp):
k = int(tmp)
if k >= 0 and float(k) < tmp:
tmp = tmp + 1
return tmp
def _to_scalar(obj, sc_ty):
"""A way to convert object to NumPy scalar type.
Raises OverflowError if obj can not be represented
using the requested scalar type.
"""
zd_arr = np.asarray(obj, dtype=sc_ty)
return zd_arr[()]
def _usm_ndarray_from_suai(obj):
sua_iface = obj.__sycl_usm_array_interface__
membuf = dpm.as_usm_memory(obj)
ary = dpt.usm_ndarray(
sua_iface["shape"],
dtype=sua_iface["typestr"],
buffer=membuf,
strides=sua_iface.get("strides", None),
)
_data_field = sua_iface["data"]
if isinstance(_data_field, tuple) and len(_data_field) > 1:
ro_field = _data_field[1]
else:
ro_field = False
if ro_field:
ary.flags["W"] = False
return ary
def _usm_types_walker(o, usm_types_list):
if isinstance(o, dpt.usm_ndarray):
usm_types_list.append(o.usm_type)
return
if hasattr(o, "__usm_ndarray__"):
usm_arr = o.__usm_ndarray__
if isinstance(usm_arr, dpt.usm_ndarray):
usm_types_list.append(usm_arr.usm_type)
return
if hasattr(o, "__sycl_usm_array_interface__"):
usm_ar = _usm_ndarray_from_suai(o)
usm_types_list.append(usm_ar.usm_type)
return
if _is_object_with_buffer_protocol(o):
return
if isinstance(o, (int, bool, float, complex)):
return
if isinstance(o, (list, tuple, range)):
for el in o:
_usm_types_walker(el, usm_types_list)
return
raise TypeError
def arange(
start,
/,
stop=None,
step=1,
*,
dtype=None,
device=None,
usm_type="device",
sycl_queue=None,
):
"""
Returns evenly spaced values within the half-open interval [start, stop)
as a one-dimensional array.
Args:
start:
Starting point of the interval
stop:
Ending point of the interval. Default: ``None``
step: Increment of the returned sequence. Default: ``1``
dtype: Output array data type. Default: ``None``
device (optional): array API concept of device where the output array
is created. ``device`` can be ``None``, a oneAPI filter selector
string, an instance of :class:`dpctl.SyclDevice` corresponding to
a non-partitioned SYCL device, an instance of
:class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object
returned by :attr:`dpctl.tensor.usm_ndarray.device`.
Default: ``None``
usm_type (``"device"``, ``"shared"``, ``"host"``, optional):
The type of SYCL USM allocation for the output array.
Default: ``"device"``
sycl_queue (:class:`dpctl.SyclQueue`, optional):
The SYCL queue to use
for output array allocation and copying. ``sycl_queue`` and
``device`` are complementary arguments, i.e. use one or another.
If both are specified, a :exc:`TypeError` is raised unless both
imply the same underlying SYCL queue to be used. If both are
``None``, a cached queue targeting default-selected device is
used for allocation and population. Default: ``None``
Returns:
usm_ndarray:
Array populated with evenly spaced values.
"""
if stop is None:
stop = start
start = 0
if step is None:
step = 1
dpctl.utils.validate_usm_type(usm_type, allow_none=False)
sycl_queue = normalize_queue_device(sycl_queue=sycl_queue, device=device)
is_bool = False
if dtype:
is_bool = (dtype is bool) or (dpt.dtype(dtype) == dpt.bool)
_, dt = _coerce_and_infer_dt(
start,
stop,
step,
dt=dpt.int8 if is_bool else dtype,
sycl_queue=sycl_queue,
err_msg="start, stop, and step must be Python scalars",
allow_bool=False,
)
try:
tmp = _get_arange_length(start, stop, step)
sh = max(int(tmp), 0)
except TypeError:
sh = 0
if is_bool and sh > 2:
raise ValueError("no fill-function for boolean data type")
res = dpt.usm_ndarray(
(sh,),
dtype=dt,
buffer=usm_type,
order="C",
buffer_ctor_kwargs={"queue": sycl_queue},
)
sc_ty = dt.type
_first = _to_scalar(start, sc_ty)
if sh > 1:
_second = _to_scalar(start + step, sc_ty)
if dt in [dpt.uint8, dpt.uint16, dpt.uint32, dpt.uint64]:
int64_ty = dpt.int64.type
_step = int64_ty(_second) - int64_ty(_first)
else:
_step = _second - _first
_step = sc_ty(_step)
else:
_step = sc_ty(1)
_start = _first
_manager = dpctl.utils.SequentialOrderManager[sycl_queue]
# populating newly allocated array, no task dependencies
hev, lin_ev = ti._linspace_step(_start, _step, res, sycl_queue)
_manager.add_event_pair(hev, lin_ev)
if is_bool:
res_out = dpt.usm_ndarray(
(sh,),
dtype=dpt.bool,
buffer=usm_type,
order="C",
buffer_ctor_kwargs={"queue": sycl_queue},
)
hev_cpy, cpy_ev = ti._copy_usm_ndarray_into_usm_ndarray(
src=res, dst=res_out, sycl_queue=sycl_queue, depends=[lin_ev]
)
_manager.add_event_pair(hev_cpy, cpy_ev)
return res_out
return res
def asarray(
obj,
/,
*,
dtype=None,
device=None,
copy=None,
usm_type=None,
sycl_queue=None,
order="K",
):
"""
Converts input object to :class:`dpctl.tensor.usm_ndarray`.
Args:
obj: Python object to convert. Can be an instance of
:class:`dpctl.tensor.usm_ndarray`,
an object representing SYCL USM allocation and implementing
``__sycl_usm_array_interface__`` protocol, an instance
of :class:`numpy.ndarray`, an object supporting Python buffer
protocol, a Python scalar, or a (possibly nested) sequence of
Python scalars.
dtype (data type, optional):
output array data type. If ``dtype`` is
``None``, the output array data type is inferred from data types in
``obj``. Default: ``None``
copy (`bool`, optional):
boolean indicating whether or not to copy the
input. If ``True``, always creates a copy. If ``False``, the
need to copy raises :exc:`ValueError`. If ``None``, tries to reuse
existing memory allocations if possible, but allows to perform
a copy otherwise. Default: ``None``
order (``"C"``, ``"F"``, ``"A"``, ``"K"``, optional):
memory layout of the output array. Default: ``"K"``
device (optional): array API concept of device where the output array
is created. ``device`` can be ``None``, a oneAPI filter selector
string, an instance of :class:`dpctl.SyclDevice` corresponding to
a non-partitioned SYCL device, an instance of
:class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object
returned by :attr:`dpctl.tensor.usm_ndarray.device`.
Default: ``None``
usm_type (``"device"``, ``"shared"``, ``"host"``, optional):
The type of SYCL USM allocation for the output array.
Default: ``"device"``
sycl_queue (:class:`dpctl.SyclQueue`, optional):
The SYCL queue to use
for output array allocation and copying. ``sycl_queue`` and
``device`` are complementary arguments, i.e. use one or another.
If both are specified, a :exc:`TypeError` is raised unless both
imply the same underlying SYCL queue to be used. If both are
``None``, a cached queue targeting default-selected device is
used for allocation and population. Default: ``None``
Returns:
usm_ndarray:
Array created from input object.
"""
# 1. Check that copy is a valid keyword
if copy not in [None, True, False]:
raise TypeError(
"Recognized copy keyword values should be True, False, or None"
)
# 2. Check that dtype is None, or a valid dtype
if dtype is not None:
dtype = dpt.dtype(dtype)
# 3. Validate order
if not isinstance(order, str):
raise TypeError(
f"Expected order keyword to be of type str, got {type(order)}"
)
if len(order) == 0 or order[0] not in "KkAaCcFf":
raise ValueError(
"Unrecognized order keyword value, expecting 'K', 'A', 'F', or 'C'."
)
order = order[0].upper()
# 4. Check that usm_type is None, or a valid value
dpctl.utils.validate_usm_type(usm_type, allow_none=True)
# 5. Normalize device/sycl_queue [keep it None if was None]
if device is not None or sycl_queue is not None:
sycl_queue = normalize_queue_device(
sycl_queue=sycl_queue, device=device
)
# handle instance(obj, usm_ndarray)
if isinstance(obj, dpt.usm_ndarray):
return _asarray_from_usm_ndarray(
obj,
dtype=dtype,
copy=copy,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
if hasattr(obj, "__usm_ndarray__"):
usm_arr = obj.__usm_ndarray__
if isinstance(usm_arr, dpt.usm_ndarray):
return _asarray_from_usm_ndarray(
usm_arr,
dtype=dtype,
copy=copy,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
if hasattr(obj, "__sycl_usm_array_interface__"):
ary = _usm_ndarray_from_suai(obj)
return _asarray_from_usm_ndarray(
ary,
dtype=dtype,
copy=copy,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
if isinstance(obj, np.ndarray):
if copy is False:
raise ValueError(
"Converting numpy.ndarray to usm_ndarray requires a copy"
)
return _asarray_from_numpy_ndarray(
obj,
dtype=dtype,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
if _is_object_with_buffer_protocol(obj):
if copy is False:
raise ValueError(
f"Converting {type(obj)} to usm_ndarray requires a copy"
)
return _asarray_from_numpy_ndarray(
np.array(obj),
dtype=dtype,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
if isinstance(obj, (list, tuple, range)):
if copy is False:
raise ValueError(
"Converting Python sequence to usm_ndarray requires a copy"
)
seq_shape, seq_dt, devs = _array_info_sequence(obj)
if devs == _host_set:
return _asarray_from_numpy_ndarray(
np.asarray(obj, dtype=dtype, order=order),
dtype=dtype,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
elif len(devs) == 1:
seq_dev = list(devs)[0]
return _asarray_from_seq_single_device(
obj,
seq_shape,
seq_dt,
seq_dev,
dtype=dtype,
usm_type=usm_type,
sycl_queue=sycl_queue,
order=order,
)
elif len(devs) > 1:
devs = [dev for dev in devs if dev is not None]
if sycl_queue is None:
if len(devs) == 1:
alloc_q = devs[0]
else:
raise dpctl.utils.ExecutionPlacementError(
"Please specify `device` or `sycl_queue` keyword "
"argument to determine where to allocate the "
"resulting array."
)
else:
alloc_q = sycl_queue
return _asarray_from_seq(
obj,
seq_shape,
seq_dt,
alloc_q,
# force copying via host
None,
dtype=dtype,
usm_type=usm_type,
order=order,
)
if copy is False:
raise ValueError(
f"Converting {type(obj)} to usm_ndarray requires a copy"
)
# obj is a scalar, create 0d array
return _asarray_from_numpy_ndarray(
np.asarray(obj, dtype=dtype),
dtype=dtype,
usm_type=usm_type,
sycl_queue=sycl_queue,
order="C",
)
def empty(
shape,
*,
dtype=None,
order="C",
device=None,
usm_type="device",
sycl_queue=None,
):
"""
Creates :class:`dpctl.tensor.usm_ndarray` from uninitialized
USM allocation.
Args:
shape (Tuple[int], int):
Dimensions of the array to be created.
dtype (optional):
data type of the array. Can be typestring,
a :class:`numpy.dtype` object, :mod:`numpy` char string,
or a NumPy scalar type. The ``None`` value creates an
array of floating point data type. Default: ``None``
order (``"C"``, or ``F"``):
memory layout for the array. Default: ``"C"``
device (optional): array API concept of device where the output array
is created. ``device`` can be ``None``, a oneAPI filter selector
string, an instance of :class:`dpctl.SyclDevice` corresponding to
a non-partitioned SYCL device, an instance of
:class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object
returned by :attr:`dpctl.tensor.usm_ndarray.device`.
Default: ``None``
usm_type (``"device"``, ``"shared"``, ``"host"``, optional):
The type of SYCL USM allocation for the output array.
Default: ``"device"``
sycl_queue (:class:`dpctl.SyclQueue`, optional):
The SYCL queue to use
for output array allocation and copying. ``sycl_queue`` and
``device`` are complementary arguments, i.e. use one or another.
If both are specified, a :exc:`TypeError` is raised unless both
imply the same underlying SYCL queue to be used. If both are
``None``, a cached queue targeting default-selected device is
used for allocation and population. Default: ``None``
Returns:
usm_ndarray:
Created empty array.
"""
if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf":
raise ValueError(
"Unrecognized order keyword value, expecting 'F' or 'C'."
)
order = order[0].upper()
dpctl.utils.validate_usm_type(usm_type, allow_none=False)
sycl_queue = normalize_queue_device(sycl_queue=sycl_queue, device=device)
dtype = _get_dtype(dtype, sycl_queue)
_ensure_native_dtype_device_support(dtype, sycl_queue.sycl_device)
res = dpt.usm_ndarray(
shape,
dtype=dtype,
buffer=usm_type,
order=order,
buffer_ctor_kwargs={"queue": sycl_queue},
)
return res
def empty_like(
x, /, *, dtype=None, order="K", device=None, usm_type=None, sycl_queue=None
):
"""
Returns an uninitialized :class:`dpctl.tensor.usm_ndarray` with the
same `shape` as the input array `x`.
Args:
x (usm_ndarray):
Input array from which to derive the output array shape.
dtype (optional):
data type of the array. Can be a typestring,
a :class:`numpy.dtype` object, NumPy char string,
or a NumPy scalar type. Default: ``None``
order ("C", "F", "A", or "K"):
memory layout for the array. Default: ``"K"``
device (optional): array API concept of device where the output array
is created. ``device`` can be ``None``, a oneAPI filter selector
string, an instance of :class:`dpctl.SyclDevice` corresponding to
a non-partitioned SYCL device, an instance of
:class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object
returned by :attr:`dpctl.tensor.usm_ndarray.device`.
Default: ``None``
usm_type (``"device"``, ``"shared"``, ``"host"``, optional):
The type of SYCL USM allocation for the output array.
Default: ``"device"``
sycl_queue (:class:`dpctl.SyclQueue`, optional):
The SYCL queue to use
for output array allocation and copying. ``sycl_queue`` and
``device`` are complementary arguments, i.e. use one or another.
If both are specified, a :exc:`TypeError` is raised unless both
imply the same underlying SYCL queue to be used. If both are
``None``, a cached queue targeting default-selected device is
used for allocation. Default: ``None``
Returns:
usm_ndarray:
Created empty array with uninitialized memory.
"""
if not isinstance(x, dpt.usm_ndarray):
raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.")
if (
not isinstance(order, str)
or len(order) == 0
or order[0] not in "CcFfAaKk"
):
raise ValueError(
"Unrecognized order keyword value, expecting 'C', 'F', 'A', or 'K'."
)
order = order[0].upper()
if dtype is None:
dtype = x.dtype