Repository navigation
Expand file tree
/
Copy pathtest_usm_ndarray_ctor.py
More file actions
2767 lines (2362 loc) · 80.6 KB
/
Copy pathtest_usm_ndarray_ctor.py
File metadata and controls
2767 lines (2362 loc) · 80.6 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.
import ctypes
import numbers
from math import prod
import numpy as np
import pytest
import dpctl
import dpctl.memory as dpm
import dpctl.tensor as dpt
from dpctl.tensor import Device
from .helper import get_queue_or_skip, skip_if_dtype_not_supported
_all_dtypes = [
"b1",
"i1",
"u1",
"i2",
"u2",
"i4",
"u4",
"i8",
"u8",
"f2",
"f4",
"f8",
"c8",
"c16",
]
@pytest.mark.parametrize(
"shape",
[
(),
(4,),
(0,),
(0, 1),
(0, 0),
(4, 5),
(2, 5, 2),
(2, 2, 2, 2, 2, 2, 2, 2),
5,
np.int32(7),
],
)
@pytest.mark.parametrize("usm_type", ["shared", "host", "device"])
def test_allocate_usm_ndarray(shape, usm_type):
q = get_queue_or_skip()
X = dpt.usm_ndarray(
shape, dtype="i8", buffer=usm_type, buffer_ctor_kwargs={"queue": q}
)
Xnp = np.ndarray(shape, dtype="i8")
assert X.usm_type == usm_type
assert X.sycl_context == q.sycl_context
assert X.sycl_device == q.sycl_device
assert X.size == Xnp.size
assert X.shape == Xnp.shape
assert X.shape == X.__sycl_usm_array_interface__["shape"]
def test_usm_ndarray_flags():
get_queue_or_skip()
f = dpt.usm_ndarray((5,), dtype="i4").flags
assert f.fc
assert f.forc
f = dpt.usm_ndarray((5, 2), dtype="i4").flags
assert f.c_contiguous
assert f.forc
f = dpt.usm_ndarray((5, 2), dtype="i4", order="F").flags
assert f.f_contiguous
assert f.forc
assert f.fnc
f = dpt.usm_ndarray((5,), dtype="i4", strides=(1,)).flags
assert f.fc
assert f.forc
f = dpt.usm_ndarray((5, 1, 2), dtype="i4", strides=(2, 0, 1)).flags
assert f.c_contiguous
assert f.forc
f = dpt.usm_ndarray((5, 1, 2), dtype="i4", strides=(1, 0, 5)).flags
assert f.f_contiguous
assert f.forc
assert f.fnc
f = dpt.usm_ndarray((5, 0, 1), dtype="i4", strides=(1, 0, 1)).flags
assert f.fc
assert f.forc
assert not dpt.usm_ndarray(
(5, 1, 1), dtype="i4", strides=(2, 0, 1)
).flags.forc
x = dpt.empty(5, dtype="u2")
assert x.flags.writable is True
x.flags.writable = False
assert x.flags.writable is False
with pytest.raises(ValueError):
x[:] = 0
x.flags["W"] = True
assert x.flags.writable is True
x.flags["WRITABLE"] = True
assert x.flags.writable is True
x[:] = 0
with pytest.raises(TypeError):
x.flags.writable = dict()
with pytest.raises(ValueError):
x.flags["C"] = False
def test_usm_ndarray_flags_bug_gh_1334():
get_queue_or_skip()
a = dpt.ones((2, 3), dtype="u4")
r = dpt.reshape(a, (1, 6, 1))
assert r.flags["C"] and r.flags["F"]
a = dpt.ones((2, 3), dtype="u4", order="F")
r = dpt.reshape(a, (1, 6, 1), order="F")
assert r.flags["C"] and r.flags["F"]
a = dpt.ones((2, 3, 4), dtype="i8")
r = dpt.sum(a, axis=(1, 2), keepdims=True)
assert r.flags["C"] and r.flags["F"]
a = dpt.ones((2, 1), dtype="?")
r = a[:, 1::-1]
assert r.flags["F"] and r.flags["C"]
def test_usm_ndarray_writable_flag_views():
get_queue_or_skip()
a = dpt.arange(10, dtype="f4")
a.flags["W"] = False
a.shape = (5, 2)
assert not a.flags.writable
assert not a.T.flags.writable
assert not a.mT.flags.writable
assert not a.real.flags.writable
assert not a[0:3].flags.writable
a = dpt.arange(10, dtype="c8")
a.flags["W"] = False
assert not a.real.flags.writable
assert not a.imag.flags.writable
@pytest.mark.parametrize("dt1", _all_dtypes)
@pytest.mark.parametrize("dt2", _all_dtypes)
def test_usm_ndarray_from_zero_sized_usm_ndarray(dt1, dt2):
q = get_queue_or_skip()
skip_if_dtype_not_supported(dt1, q)
skip_if_dtype_not_supported(dt2, q)
x1 = dpt.ones((0,), dtype=dt1, sycl_queue=q)
x2 = dpt.usm_ndarray(x1.shape, dtype=dt2, buffer=x1)
assert x2.dtype == dt2
assert x2.sycl_queue == q
assert x2._pointer == x1._pointer
assert x2.shape == x1.shape
def test_usm_ndarray_from_usm_ndarray_readonly():
get_queue_or_skip()
x1 = dpt.arange(10, dtype="f4")
x1.flags["W"] = False
x2 = dpt.usm_ndarray(x1.shape, dtype="f4", buffer=x1)
assert not x2.flags.writable
@pytest.mark.parametrize(
"dtype",
_all_dtypes
+ [
b"float32",
dpt.dtype("d"),
np.half,
],
)
def test_dtypes(dtype):
q = get_queue_or_skip()
skip_if_dtype_not_supported(dtype, q)
Xusm = dpt.usm_ndarray((1,), dtype=dtype)
assert Xusm.itemsize == dpt.dtype(dtype).itemsize
expected_fmt = (dpt.dtype(dtype).str)[1:]
actual_fmt = Xusm.__sycl_usm_array_interface__["typestr"][1:]
assert expected_fmt == actual_fmt
@pytest.mark.parametrize("usm_type", ["device", "shared", "host"])
@pytest.mark.parametrize("buffer_ctor_kwargs", [dict(), {"queue": None}])
def test_default_dtype(usm_type, buffer_ctor_kwargs):
q = get_queue_or_skip()
dev = q.get_sycl_device()
if buffer_ctor_kwargs:
buffer_ctor_kwargs["queue"] = q
Xusm = dpt.usm_ndarray(
(1,), buffer=usm_type, buffer_ctor_kwargs=buffer_ctor_kwargs
)
if dev.has_aspect_fp64:
expected_dtype = "f8"
else:
expected_dtype = "f4"
assert Xusm.itemsize == dpt.dtype(expected_dtype).itemsize
expected_fmt = (dpt.dtype(expected_dtype).str)[1:]
actual_fmt = Xusm.__sycl_usm_array_interface__["typestr"][1:]
assert expected_fmt == actual_fmt
@pytest.mark.parametrize(
"dtype",
[
"",
">f4",
"invalid",
123,
np.dtype(">f4"),
np.dtype([("a", ">f4"), ("b", "i4")]),
],
)
def test_dtypes_invalid(dtype):
with pytest.raises((TypeError, ValueError)):
dpt.usm_ndarray((1,), dtype=dtype)
@pytest.mark.parametrize("dt", ["f", "c8"])
def test_properties(dt):
"""
Test that properties execute
"""
try:
X = dpt.usm_ndarray((3, 4, 5), dtype=dt)
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
assert isinstance(X.sycl_queue, dpctl.SyclQueue)
assert isinstance(X.sycl_device, dpctl.SyclDevice)
assert isinstance(X.sycl_context, dpctl.SyclContext)
assert isinstance(X.dtype, dpt.dtype)
assert isinstance(X.__sycl_usm_array_interface__, dict)
assert isinstance(X.mT, dpt.usm_ndarray)
assert isinstance(X.imag, dpt.usm_ndarray)
assert isinstance(X.real, dpt.usm_ndarray)
assert isinstance(X.shape, tuple)
assert isinstance(X.strides, tuple)
assert X.usm_type in ("shared", "device", "host")
assert isinstance(X.size, numbers.Integral)
assert isinstance(X.nbytes, numbers.Integral)
assert isinstance(X.ndim, numbers.Integral)
assert isinstance(X._pointer, numbers.Integral)
assert isinstance(X.device, Device)
with pytest.raises(ValueError):
# array-API mandates exception for .ndim != 2
X.T
Y = dpt.usm_ndarray((2, 3), dtype=dt)
assert isinstance(Y.mT, dpt.usm_ndarray)
V = dpt.usm_ndarray((3,), dtype=dt)
with pytest.raises(ValueError):
# array-API mandates exception for .ndim != 2
V.mT
@pytest.mark.parametrize("func", [bool, float, int, complex])
@pytest.mark.parametrize("shape", [tuple(), (1,), (1, 1), (1, 1, 1)])
@pytest.mark.parametrize("dtype", ["|b1", "|u2", "|f4", "|i8"])
def test_copy_scalar_with_func(func, shape, dtype):
try:
X = dpt.usm_ndarray(shape, dtype=dtype)
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Y = np.arange(1, X.size + 1, dtype=dtype)
X.usm_data.copy_from_host(Y.view("|u1"))
Y.shape = tuple()
assert func(X) == func(Y)
@pytest.mark.parametrize(
"method", ["__bool__", "__float__", "__int__", "__complex__"]
)
@pytest.mark.parametrize("shape", [tuple(), (1,), (1, 1), (1, 1, 1)])
@pytest.mark.parametrize("dtype", ["|b1", "|u2", "|f4", "|i8"])
def test_copy_scalar_with_method(method, shape, dtype):
try:
X = dpt.usm_ndarray(shape, dtype=dtype)
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Y = np.arange(1, X.size + 1, dtype=dtype)
X.usm_data.copy_from_host(Y.view("|u1"))
Y.shape = tuple()
assert getattr(X, method)() == getattr(Y, method)()
@pytest.mark.parametrize("func", [bool, float, int, complex])
@pytest.mark.parametrize("shape", [(2,), (1, 2), (3, 4, 5), (0,)])
def test_copy_scalar_invalid_shape(func, shape):
try:
X = dpt.usm_ndarray(shape, dtype="i8")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
with pytest.raises(ValueError):
func(X)
def test_index_noninteger():
import operator
try:
X = dpt.usm_ndarray(1, "f4")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
with pytest.raises(IndexError):
operator.index(X)
@pytest.mark.parametrize(
"ind",
[
tuple(),
(None,),
(
None,
Ellipsis,
None,
),
(2, 2, None, 3, 4),
(Ellipsis,),
(None, slice(0, None, 2), Ellipsis, slice(0, None, 3)),
(None, slice(1, None, 2), Ellipsis, slice(1, None, 3)),
(None, slice(None, -1, -2), Ellipsis, slice(2, None, 3)),
(
slice(None, None, -1),
slice(None, None, -1),
slice(0, None, 3),
slice(1, None, 2),
),
],
)
def test_basic_slice(ind):
try:
X = dpt.usm_ndarray((2 * 3, 2 * 4, 3 * 5, 2 * 7), dtype="u1")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Xnp = np.empty(X.shape, dtype=X.dtype)
S = X[ind]
Snp = Xnp[ind]
assert S.shape == Snp.shape
assert S.strides == Snp.strides
assert S.dtype == X.dtype
def test_empty_slice():
# see gh801
try:
X = dpt.empty((1, 0, 1), dtype="u1")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Y = X[:, ::-1, :]
assert Y.shape == X.shape
Z = X[:, ::2, :]
assert Z.shape == X.shape
X = dpt.empty(0)
Y = X[::-1]
assert Y.shape == X.shape
Z = X[::2]
assert Z.shape == X.shape
X = dpt.empty((0, 4), dtype="u1")
assert X[:, 1].shape == (0,)
assert X[:, 1:3].shape == (0, 2)
def test_slice_constructor_1d():
Xh = np.arange(37, dtype="i4")
try:
Xusm = dpt.arange(Xh.size, dtype="i4")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
for ind in [
slice(1, None, 2),
slice(0, None, 3),
slice(1, None, 3),
slice(2, None, 3),
slice(None, None, -1),
slice(-2, 2, -2),
slice(-1, 1, -2),
slice(None, None, -13),
]:
assert np.array_equal(
dpt.asnumpy(Xusm[ind]), Xh[ind]
), "Failed for {}".format(ind)
def test_slice_constructor_3d():
Xh = np.ones((37, 24, 35), dtype="i4")
try:
Xusm = dpt.ones(Xh.shape, dtype=Xh.dtype)
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
for ind in [
slice(1, None, 2),
slice(0, None, 3),
slice(1, None, 3),
slice(2, None, 3),
slice(None, None, -1),
slice(-2, 2, -2),
slice(-1, 1, -2),
slice(None, None, -13),
(slice(None, None, -2), Ellipsis, None, 15),
]:
assert np.array_equal(
dpt.to_numpy(Xusm[ind]), Xh[ind]
), "Failed for {}".format(ind)
@pytest.mark.parametrize("usm_type", ["device", "shared", "host"])
def test_slice_suai(usm_type):
Xh = np.arange(0, 10, dtype="u1")
try:
Xusm = dpt.arange(0, 10, dtype="u1", usm_type=usm_type)
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
for ind in [slice(2, 3, None), slice(5, 7, None), slice(3, 9, None)]:
assert np.array_equal(
dpm.as_usm_memory(Xusm[ind]).copy_to_host(), Xh[ind]
), "Failed for {}".format(ind)
def test_slicing_basic():
try:
Xusm = dpt.usm_ndarray((10, 5), dtype="c8")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Xusm[None]
Xusm[...]
Xusm[8]
Xusm[-3]
with pytest.raises(IndexError):
Xusm[..., ...]
with pytest.raises(IndexError):
Xusm[1, 1, :, 1]
Xusm[:, -4]
with pytest.raises(IndexError):
Xusm[:, -128]
with pytest.raises(IndexError):
Xusm[{1, 2, 3, 4, 5, 6, 7}]
X = dpt.usm_ndarray(10, "u1")
X.usm_data.copy_from_host(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09")
int(
X[X[2]]
) # check that objects with __index__ method can be used as indices
Xh = dpm.as_usm_memory(X[X[2] : X[5]]).copy_to_host()
Xnp = np.arange(0, 10, dtype="u1")
assert np.array_equal(Xh, Xnp[Xnp[2] : Xnp[5]])
def test_slicing_empty():
try:
X = dpt.usm_ndarray((0, 10), dtype="i4")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
x = dpt.moveaxis(X, 1, 0)
# this used to raise ValueError
y = x[1]
assert y.ndim == 1
assert y.shape == (0,)
assert y.dtype == X.dtype
assert y.usm_type == X.usm_type
assert y.sycl_queue == X.sycl_queue
w = x[1:3]
assert w.ndim == 2
assert w.shape == (
2,
0,
)
assert w.dtype == X.dtype
assert w.usm_type == X.usm_type
assert w.sycl_queue == X.sycl_queue
def test_ctor_invalid_shape():
with pytest.raises(TypeError):
dpt.usm_ndarray(dict())
def test_ctor_invalid_order():
get_queue_or_skip()
with pytest.raises(ValueError):
dpt.usm_ndarray((5, 5, 3), order="Z")
with pytest.raises(ValueError):
dpt.usm_ndarray((10), strides=(1,), order="Z")
with pytest.raises(ValueError):
dpt.usm_ndarray((), order="Z")
def test_ctor_buffer_kwarg():
try:
dpt.usm_ndarray(10, dtype="i8", buffer=b"device")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
with pytest.raises(ValueError):
dpt.usm_ndarray(10, buffer="invalid_param")
Xusm = dpt.usm_ndarray((10, 5), dtype="c8")
Xusm[...] = 1
X2 = dpt.usm_ndarray(Xusm.shape, buffer=Xusm, dtype=Xusm.dtype)
Horig_copy = Xusm.usm_data.copy_to_host()
H2_copy = X2.usm_data.copy_to_host()
assert np.array_equal(Horig_copy, H2_copy)
with pytest.raises(ValueError):
dpt.usm_ndarray(10, dtype="i4", buffer=dict())
# use device-specific default fp data type
X3 = dpt.usm_ndarray(Xusm.shape, buffer=Xusm)
assert np.array_equal(Horig_copy, X3.usm_data.copy_to_host())
def test_usm_ndarray_props():
try:
Xusm = dpt.usm_ndarray((10, 5), dtype="c8", order="F")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
Xusm.ndim
repr(Xusm)
Xusm.flags
Xusm.__sycl_usm_array_interface__
Xusm.device
Xusm.strides
Xusm.real
Xusm.imag
try:
dpctl.SyclQueue("cpu")
except dpctl.SyclQueueCreationError:
pytest.skip("Sycl device CPU was not detected")
Xusm.to_device("cpu")
def test_datapi_device():
try:
X = dpt.usm_ndarray(1, dtype="i4")
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
dev_t = type(X.device)
with pytest.raises(TypeError):
dev_t()
dev_t.create_device(X.device)
dev_t.create_device(X.sycl_queue)
d1 = dev_t.create_device(X.sycl_device)
d2 = dev_t.create_device(X.sycl_device.filter_string)
d3 = dev_t.create_device(None)
assert d1.sycl_queue == d2.sycl_queue
assert d1.sycl_queue == d3.sycl_queue
X.device.sycl_context
X.device.sycl_queue
X.device.sycl_device
repr(X.device)
X.device.print_device_info()
def _pyx_capi_fnptr_to_callable(
X,
pyx_capi_name,
caps_name,
fn_restype=ctypes.c_void_p,
fn_argtypes=(ctypes.py_object,),
):
import sys
mod = sys.modules[X.__class__.__module__]
cap = mod.__pyx_capi__.get(pyx_capi_name, None)
if cap is None:
raise ValueError(
"__pyx_capi__ does not export {} capsule".format(pyx_capi_name)
)
# construct Python callable to invoke these functions
cap_ptr_fn = ctypes.pythonapi.PyCapsule_GetPointer
cap_ptr_fn.restype = ctypes.c_void_p
cap_ptr_fn.argtypes = [ctypes.py_object, ctypes.c_char_p]
fn_ptr = cap_ptr_fn(cap, caps_name)
callable_maker_ptr = ctypes.PYFUNCTYPE(fn_restype, *fn_argtypes)
return callable_maker_ptr(fn_ptr)
def test_pyx_capi_get_data():
try:
X = dpt.usm_ndarray(17, dtype="i8")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_data_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetData",
b"char *(struct PyUSMArrayObject *)",
fn_restype=ctypes.c_void_p,
fn_argtypes=(ctypes.py_object,),
)
r1 = get_data_fn(X)
sua_iface = X.__sycl_usm_array_interface__
assert r1 == sua_iface["data"][0] + sua_iface.get("offset") * X.itemsize
def test_pyx_capi_get_shape():
try:
X = dpt.usm_ndarray(17, dtype="u4")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_shape_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetShape",
b"Py_ssize_t *(struct PyUSMArrayObject *)",
fn_restype=ctypes.c_void_p,
fn_argtypes=(ctypes.py_object,),
)
c_longlong_p = ctypes.POINTER(ctypes.c_longlong)
shape0 = ctypes.cast(get_shape_fn(X), c_longlong_p).contents.value
assert shape0 == X.shape[0]
def test_pyx_capi_get_strides():
try:
X = dpt.usm_ndarray(17, dtype="f4")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_strides_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetStrides",
b"Py_ssize_t *(struct PyUSMArrayObject *)",
fn_restype=ctypes.c_void_p,
fn_argtypes=(ctypes.py_object,),
)
c_longlong_p = ctypes.POINTER(ctypes.c_longlong)
strides0_p = get_strides_fn(X)
if strides0_p:
strides0_p = ctypes.cast(strides0_p, c_longlong_p).contents
strides0_p = strides0_p.value
assert strides0_p == 0 or strides0_p == X.strides[0]
def test_pyx_capi_get_ndim():
try:
X = dpt.usm_ndarray(17, dtype="?")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_ndim_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetNDim",
b"int (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_int,
fn_argtypes=(ctypes.py_object,),
)
assert get_ndim_fn(X) == X.ndim
def test_pyx_capi_get_typenum():
try:
X = dpt.usm_ndarray(17, dtype="c8")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_typenum_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetTypenum",
b"int (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_int,
fn_argtypes=(ctypes.py_object,),
)
typenum = get_typenum_fn(X)
assert type(typenum) is int
assert typenum == X.dtype.num
def test_pyx_capi_get_elemsize():
try:
X = dpt.usm_ndarray(17, dtype="u8")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_elemsize_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetElementSize",
b"int (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_int,
fn_argtypes=(ctypes.py_object,),
)
itemsize = get_elemsize_fn(X)
assert type(itemsize) is int
assert itemsize == X.itemsize
def test_pyx_capi_get_flags():
try:
X = dpt.usm_ndarray(17, dtype="i8")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_flags_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetFlags",
b"int (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_int,
fn_argtypes=(ctypes.py_object,),
)
flags = get_flags_fn(X)
assert type(flags) is int and X.flags == flags
def test_pyx_capi_get_offset():
try:
X = dpt.usm_ndarray(17, dtype="u2")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_offset_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetOffset",
b"Py_ssize_t (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_longlong,
fn_argtypes=(ctypes.py_object,),
)
offset = get_offset_fn(X)
assert type(offset) is int
assert offset == X.__sycl_usm_array_interface__["offset"]
def test_pyx_capi_get_usmdata():
try:
X = dpt.usm_ndarray(17, dtype="u2")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_usmdata_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetUSMData",
b"PyObject *(struct PyUSMArrayObject *)",
fn_restype=ctypes.py_object,
fn_argtypes=(ctypes.py_object,),
)
capi_usm_data = get_usmdata_fn(X)
assert isinstance(capi_usm_data, dpm._memory._Memory)
assert capi_usm_data.nbytes == X.usm_data.nbytes
assert capi_usm_data._pointer == X.usm_data._pointer
assert capi_usm_data.sycl_queue == X.usm_data.sycl_queue
def test_pyx_capi_get_queue_ref():
try:
X = dpt.usm_ndarray(17, dtype="i2")[1::2]
except dpctl.SyclDeviceCreationError:
pytest.skip("No SYCL devices available")
get_queue_ref_fn = _pyx_capi_fnptr_to_callable(
X,
"UsmNDArray_GetQueueRef",
b"DPCTLSyclQueueRef (struct PyUSMArrayObject *)",
fn_restype=ctypes.c_void_p,
fn_argtypes=(ctypes.py_object,),
)
queue_ref = get_queue_ref_fn(X) # address of a copy, should be unequal
assert queue_ref != X.sycl_queue.addressof_ref()
def test_pyx_capi_make_from_memory():
q = get_queue_or_skip()
n0, n1 = 4, 6
c_tuple = (ctypes.c_ssize_t * 2)(n0, n1)
mem = dpm.MemoryUSMShared(n0 * n1 * 4, queue=q)
typenum = dpt.dtype("single").num
any_usm_ndarray = dpt.empty(tuple(), dtype="i4", sycl_queue=q)
make_from_memory_fn = _pyx_capi_fnptr_to_callable(
any_usm_ndarray,
"UsmNDArray_MakeSimpleFromMemory",
b"PyObject *(int, Py_ssize_t const *, int, "
b"struct Py_MemoryObject *, Py_ssize_t, char)",
fn_restype=ctypes.py_object,
fn_argtypes=(
ctypes.c_int,
ctypes.POINTER(ctypes.c_ssize_t),
ctypes.c_int,
ctypes.py_object,
ctypes.c_ssize_t,
ctypes.c_char,
),
)
r = make_from_memory_fn(
ctypes.c_int(2),
c_tuple,
ctypes.c_int(typenum),
mem,
ctypes.c_ssize_t(0),
ctypes.c_char(b"C"),
)
assert isinstance(r, dpt.usm_ndarray)
assert r.ndim == 2
assert r.shape == (n0, n1)
assert r._pointer == mem._pointer
assert r.usm_type == "shared"
assert r.sycl_queue == q
assert r.flags["C"]
r2 = make_from_memory_fn(
ctypes.c_int(2),
c_tuple,
ctypes.c_int(typenum),
mem,
ctypes.c_ssize_t(0),
ctypes.c_char(b"F"),
)
ptr = mem._pointer
del mem
del r
assert isinstance(r2, dpt.usm_ndarray)
assert r2._pointer == ptr
assert r2.usm_type == "shared"
assert r2.sycl_queue == q
assert r2.flags["F"]
def test_pyx_capi_set_writable_flag():
q = get_queue_or_skip()
usm_ndarray = dpt.empty((4, 5), dtype="i4", sycl_queue=q)
assert isinstance(usm_ndarray, dpt.usm_ndarray)
assert usm_ndarray.flags["WRITABLE"] is True
set_writable = _pyx_capi_fnptr_to_callable(
usm_ndarray,
"UsmNDArray_SetWritableFlag",
b"void (struct PyUSMArrayObject *, int)",
fn_restype=None,
fn_argtypes=(ctypes.py_object, ctypes.c_int),
)
set_writable(usm_ndarray, ctypes.c_int(0))
assert isinstance(usm_ndarray, dpt.usm_ndarray)
assert usm_ndarray.flags["WRITABLE"] is False
set_writable(usm_ndarray, ctypes.c_int(1))
assert isinstance(usm_ndarray, dpt.usm_ndarray)
assert usm_ndarray.flags["WRITABLE"] is True
def test_pyx_capi_make_from_ptr():
q = get_queue_or_skip()
usm_ndarray = dpt.empty(tuple(), dtype="i4", sycl_queue=q)
make_from_ptr = _pyx_capi_fnptr_to_callable(
usm_ndarray,
"UsmNDArray_MakeSimpleFromPtr",
b"PyObject *(size_t, int, DPCTLSyclUSMRef, "
b"DPCTLSyclQueueRef, PyObject *)",
fn_restype=ctypes.py_object,
fn_argtypes=(
ctypes.c_size_t,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.py_object,
),
)
nelems = 10
dt = dpt.int64
mem = dpm.MemoryUSMDevice(nelems * dt.itemsize, queue=q)
arr = make_from_ptr(
ctypes.c_size_t(nelems),
dt.num,
mem._pointer,
mem.sycl_queue.addressof_ref(),
mem,
)
assert isinstance(arr, dpt.usm_ndarray)
assert arr.shape == (nelems,)
assert arr.dtype == dt
assert arr.sycl_queue == q
assert arr._pointer == mem._pointer
del mem
assert isinstance(arr.__repr__(), str)
def test_pyx_capi_make_general():
q = get_queue_or_skip()
usm_ndarray = dpt.empty(tuple(), dtype="i4", sycl_queue=q)
make_from_ptr = _pyx_capi_fnptr_to_callable(
usm_ndarray,
"UsmNDArray_MakeFromPtr",
b"PyObject *(int, Py_ssize_t const *, int, Py_ssize_t const *, "
b"DPCTLSyclUSMRef, DPCTLSyclQueueRef, Py_ssize_t, PyObject *)",
fn_restype=ctypes.py_object,
fn_argtypes=(
ctypes.c_int,
ctypes.POINTER(ctypes.c_ssize_t),
ctypes.c_int,
ctypes.POINTER(ctypes.c_ssize_t),
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_ssize_t,
ctypes.py_object,
),
)
# Create array to view into diagonal of a matrix
n = 5
mat = dpt.reshape(
dpt.arange(n * n, dtype="i4", sycl_queue=q),
(
n,
n,
),
)
c_shape = (ctypes.c_ssize_t * 1)(
n,
)
c_strides = (ctypes.c_ssize_t * 1)(
n + 1,
)
diag = make_from_ptr(
ctypes.c_int(1),
c_shape,
ctypes.c_int(mat.dtype.num),
c_strides,
mat._pointer,
mat.sycl_queue.addressof_ref(),
ctypes.c_ssize_t(0),
mat,
)
assert isinstance(diag, dpt.usm_ndarray)
assert diag.shape == (n,)
assert diag.strides == (n + 1,)
assert diag.dtype == mat.dtype
assert diag.sycl_queue == q
assert diag._pointer == mat._pointer
del mat
assert isinstance(diag.__repr__(), str)
# create 0d scalar
mat = dpt.reshape(
dpt.arange(n * n, dtype="i4", sycl_queue=q),
(
n,
n,
),
)
sc = make_from_ptr(
ctypes.c_int(0),
None, # NULL pointer
ctypes.c_int(mat.dtype.num),
None, # NULL pointer
mat._pointer,
mat.sycl_queue.addressof_ref(),
ctypes.c_ssize_t(0),
mat,
)
assert isinstance(sc, dpt.usm_ndarray)
assert sc.shape == tuple()
assert sc.dtype == mat.dtype
assert sc.sycl_queue == q
assert sc._pointer == mat._pointer
c_shape = (ctypes.c_ssize_t * 2)(0, n)
c_strides = (ctypes.c_ssize_t * 2)(0, 1)
zd_arr = make_from_ptr(
ctypes.c_int(2),
c_shape,
ctypes.c_int(mat.dtype.num),
c_strides,
mat._pointer,
mat.sycl_queue.addressof_ref(),
ctypes.c_ssize_t(0),
mat,
)
assert isinstance(zd_arr, dpt.usm_ndarray)
assert zd_arr.shape == (
0,
n,
)
assert zd_arr.strides == (
0,
1,
)
assert zd_arr.dtype == mat.dtype
assert zd_arr.sycl_queue == q
assert zd_arr._pointer == mat._pointer
def test_pyx_capi_make_fns_invalid_typenum():
q = get_queue_or_skip()
usm_ndarray = dpt.empty(tuple(), dtype="i4", sycl_queue=q)
make_simple_from_ptr = _pyx_capi_fnptr_to_callable(
usm_ndarray,
"UsmNDArray_MakeSimpleFromPtr",
b"PyObject *(size_t, int, DPCTLSyclUSMRef, "
b"DPCTLSyclQueueRef, PyObject *)",
fn_restype=ctypes.py_object,
fn_argtypes=(
ctypes.c_size_t,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,