Repository navigation
Expand file tree
/
Copy path_sycl_queue.pyx
More file actions
2487 lines (2176 loc) · 83.8 KB
/
Copy path_sycl_queue.pyx
File metadata and controls
2487 lines (2176 loc) · 83.8 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 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
# cython: freethreading_compatible = True
""" Implements SyclQueue Cython extension type.
"""
from ._backend cimport ( # noqa: E211
DPCTLContext_Create,
DPCTLContext_Delete,
DPCTLDefaultSelector_Create,
DPCTLDevice_Copy,
DPCTLDevice_CreateFromSelector,
DPCTLDevice_Delete,
DPCTLDeviceMgr_GetCachedContext,
DPCTLDeviceSelector_Delete,
DPCTLEvent_Delete,
DPCTLEvent_Wait,
DPCTLFilterSelector_Create,
DPCTLQueue_AreEq,
DPCTLQueue_Copy,
DPCTLQueue_CopyData,
DPCTLQueue_CopyDataWithEvents,
DPCTLQueue_Create,
DPCTLQueue_Delete,
DPCTLQueue_Fill8,
DPCTLQueue_Fill8WithEvents,
DPCTLQueue_Fill16,
DPCTLQueue_Fill16WithEvents,
DPCTLQueue_Fill32,
DPCTLQueue_Fill32WithEvents,
DPCTLQueue_Fill64,
DPCTLQueue_Fill64WithEvents,
DPCTLQueue_Fill128,
DPCTLQueue_Fill128WithEvents,
DPCTLQueue_GetBackend,
DPCTLQueue_GetContext,
DPCTLQueue_GetDevice,
DPCTLQueue_HasEnableProfiling,
DPCTLQueue_Hash,
DPCTLQueue_IsInOrder,
DPCTLQueue_MemAdvise,
DPCTLQueue_Memcpy,
DPCTLQueue_MemcpyWithEvents,
DPCTLQueue_Memset,
DPCTLQueue_MemsetWithEvents,
DPCTLQueue_Prefetch,
DPCTLQueue_SubmitBarrierForEvents,
DPCTLQueue_SubmitNDRange,
DPCTLQueue_SubmitRange,
DPCTLQueue_Wait,
DPCTLRawKernelArg_Available,
DPCTLRawKernelArg_Create,
DPCTLRawKernelArg_Delete,
DPCTLSyclContextRef,
DPCTLSyclDeviceSelectorRef,
DPCTLSyclEventRef,
DPCTLWorkGroupMemory_Available,
DPCTLWorkGroupMemory_Create,
DPCTLWorkGroupMemory_Delete,
_arg_data_type,
_backend_type,
_md_local_accessor,
_queue_property_type,
)
from .memory._memory cimport _Memory
import ctypes
import numbers
from .enum_types import backend_type
from cpython cimport pycapsule
from cpython.buffer cimport (
Py_buffer,
PyBUF_ANY_CONTIGUOUS,
PyBUF_SIMPLE,
PyBUF_WRITABLE,
PyBuffer_Release,
PyObject_CheckBuffer,
PyObject_GetBuffer,
)
from cpython.ref cimport Py_INCREF, PyObject
from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t
from libc.stdlib cimport free, malloc
import collections.abc
import logging
import struct
import sys
cdef extern from "_host_task_util.hpp":
DPCTLSyclEventRef async_dec_ref(
DPCTLSyclQueueRef, PyObject **,
size_t, DPCTLSyclEventRef *, size_t, int *
) nogil
__all__ = [
"SyclQueue",
"SyclKernelInvalidRangeError",
"SyclKernelSubmitError",
"SyclQueueCreationError",
]
_logger = logging.getLogger(__name__)
cdef class kernel_arg_type_attribute:
cdef str parent_name
cdef str attr_name
cdef int attr_value
def __cinit__(self, str parent, str name, int value):
self.parent_name = parent
self.attr_name = name
self.attr_value = value
def __repr__(self):
return f"<{self.parent_name}.{self.attr_name}: {self.attr_value}>"
def __str__(self):
return f"<{self.parent_name}.{self.attr_name}: {self.attr_value}>"
@property
def name(self):
return self.attr_name
@property
def value(self):
return self.attr_value
cdef class LocalAccessor:
"""
LocalAccessor(dtype, shape)
Python class for specifying the dimensionality and type of a
``sycl::local_accessor``, to be used as a kernel argument type.
Args:
dtype (str):
the data type of the local memory.
The permitted values are
`'i1'`, `'i2'`, `'i4'`, `'i8'`:
signed integral types int8_t, int16_t, int32_t, int64_t
`'u1'`, `'u2'`, `'u4'`, `'u8'`
unsigned integral types uint8_t, uint16_t, uint32_t,
uint64_t
`'f4'`, `'f8'`,
single- and double-precision floating-point types float and
double
shape (tuple, list):
Size of LocalAccessor dimensions. Dimension of the LocalAccessor is
determined by the length of the tuple. Must be of length 1, 2, or 3,
and contain only non-negative integers.
Raises:
TypeError:
If the given shape is not a tuple or list.
ValueError:
If the given shape sequence is not between one and
three elements long.
TypeError:
If the shape is not a sequence of integers.
ValueError:
If the shape contains a negative integer.
ValueError:
If the dtype string is unrecognized.
"""
cdef _md_local_accessor lacc
def __cinit__(self, str dtype, shape):
if not isinstance(shape, (list, tuple)):
raise TypeError(
f"`shape` must be a list or tuple, got {type(shape)}"
)
ndim = len(shape)
if ndim < 1 or ndim > 3:
raise ValueError(
"LocalAccessor must have dimension between one and three"
)
for s in shape:
if not isinstance(s, numbers.Integral):
raise TypeError(
"LocalAccessor shape must be a sequence of integers"
)
if s < 0:
raise ValueError(
"LocalAccessor dimensions must be non-negative"
)
self.lacc.ndim = ndim
self.lacc.dim0 = <size_t> shape[0]
self.lacc.dim1 = <size_t> shape[1] if ndim > 1 else 1
self.lacc.dim2 = <size_t> shape[2] if ndim > 2 else 1
if dtype == "i1":
self.lacc.dpctl_type_id = _arg_data_type._INT8_T
elif dtype == "u1":
self.lacc.dpctl_type_id = _arg_data_type._UINT8_T
elif dtype == "i2":
self.lacc.dpctl_type_id = _arg_data_type._INT16_T
elif dtype == "u2":
self.lacc.dpctl_type_id = _arg_data_type._UINT16_T
elif dtype == "i4":
self.lacc.dpctl_type_id = _arg_data_type._INT32_T
elif dtype == "u4":
self.lacc.dpctl_type_id = _arg_data_type._UINT32_T
elif dtype == "i8":
self.lacc.dpctl_type_id = _arg_data_type._INT64_T
elif dtype == "u8":
self.lacc.dpctl_type_id = _arg_data_type._UINT64_T
elif dtype == "f4":
self.lacc.dpctl_type_id = _arg_data_type._FLOAT
elif dtype == "f8":
self.lacc.dpctl_type_id = _arg_data_type._DOUBLE
else:
raise ValueError(f"Unrecognized type value: '{dtype}'")
def __repr__(self):
return f"LocalAccessor({self.lacc.ndim})"
cdef size_t addressof(self):
"""
Returns the address of the _md_local_accessor for this LocalAccessor
cast to ``size_t``.
"""
return <size_t>&self.lacc
cdef class _kernel_arg_type:
"""
An enumeration of supported kernel argument types in
:func:`dpctl.SyclQueue.submit`
"""
cdef str _name
def __cinit__(self):
self._name = "kernel_arg_type"
@property
def __name__(self):
return self._name
def __repr__(self):
return "<enum 'kernel_arg_type'>"
def __str__(self):
return "<enum 'kernel_arg_type'>"
@property
def dpctl_int8(self):
cdef str p_name = "dpctl_int8"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._INT8_T
)
@property
def dpctl_uint8(self):
cdef str p_name = "dpctl_uint8"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._UINT8_T
)
@property
def dpctl_int16(self):
cdef str p_name = "dpctl_int16"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._INT16_T
)
@property
def dpctl_uint16(self):
cdef str p_name = "dpctl_uint16"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._UINT16_T
)
@property
def dpctl_int32(self):
cdef str p_name = "dpctl_int32"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._INT32_T
)
@property
def dpctl_uint32(self):
cdef str p_name = "dpctl_uint32"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._UINT32_T
)
@property
def dpctl_int64(self):
cdef str p_name = "dpctl_int64"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._INT64_T
)
@property
def dpctl_uint64(self):
cdef str p_name = "dpctl_uint64"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._UINT64_T
)
@property
def dpctl_float32(self):
cdef str p_name = "dpctl_float32"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._FLOAT
)
@property
def dpctl_float64(self):
cdef str p_name = "dpctl_float64"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._DOUBLE
)
@property
def dpctl_void_ptr(self):
cdef str p_name = "dpctl_void_ptr"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._VOID_PTR
)
@property
def dpctl_local_accessor(self):
cdef str p_name = "dpctl_local_accessor"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._LOCAL_ACCESSOR
)
@property
def dpctl_work_group_memory(self):
cdef str p_name = "dpctl_work_group_memory"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._WORK_GROUP_MEMORY
)
@property
def dpctl_raw_kernel_arg(self):
cdef str p_name = "dpctl_raw_kernel_arg"
return kernel_arg_type_attribute(
self._name,
p_name,
_arg_data_type._RAW_KERNEL_ARG
)
kernel_arg_type = _kernel_arg_type()
cdef class SyclKernelSubmitError(Exception):
"""
A ``SyclKernelSubmitError`` exception is raised when
the provided :class:`.compiler.SyclKernel` could not be
submitted to the :class:`.SyclQueue`.
"""
pass
cdef class SyclKernelInvalidRangeError(Exception):
"""
A ``SyclKernelInvalidRangeError`` is raised when the provided
range has less than one or more than three dimensions.
"""
pass
cdef class SyclQueueCreationError(Exception):
"""
A ``SyclQueueCreationError`` exception is raised when a
:class:`.SyclQueue` could not be created.
:class:`.SyclQueue` creation can fail if the filter
string is invalid, or the backend or device type values are not supported.
"""
pass
cdef int _parse_queue_properties(object prop) except *:
cdef int res = 0
cdef object props
if isinstance(prop, int):
return <int>prop
if not isinstance(prop, (tuple, list)):
props = (prop, )
else:
props = prop
for p in props:
if isinstance(p, int):
res = res | <int> p
elif isinstance(p, str):
if (p == "in_order"):
res = res | _queue_property_type._IN_ORDER
elif (p == "enable_profiling"):
res = res | _queue_property_type._ENABLE_PROFILING
elif (p == "default"):
res = res | _queue_property_type._DEFAULT_PROPERTY
else:
raise ValueError(
f"queue property '{prop}' is not understood, expecting "
"'in_order', 'enable_profiling', or 'default'"
)
else:
raise ValueError(
f"queue property '{prop}' is not understood."
)
return res
cdef void _queue_capsule_deleter(object o) noexcept:
cdef DPCTLSyclQueueRef QRef = NULL
if pycapsule.PyCapsule_IsValid(o, "SyclQueueRef"):
QRef = <DPCTLSyclQueueRef> pycapsule.PyCapsule_GetPointer(
o, "SyclQueueRef"
)
DPCTLQueue_Delete(QRef)
elif pycapsule.PyCapsule_IsValid(o, "used_SyclQueueRef"):
QRef = <DPCTLSyclQueueRef> pycapsule.PyCapsule_GetPointer(
o, "used_SyclQueueRef"
)
DPCTLQueue_Delete(QRef)
cdef bint _is_buffer(object o):
return PyObject_CheckBuffer(o)
# Function pointer typedefs for the C API queue copy functions
ctypedef DPCTLSyclEventRef (*queue_copy_fn)(
const DPCTLSyclQueueRef, void*, const void*, size_t
)
ctypedef DPCTLSyclEventRef (*queue_copy_with_events_fn)(
const DPCTLSyclQueueRef, void*, const void*, size_t,
const DPCTLSyclEventRef*, size_t
)
cdef size_t _get_dtype_size(str dtype) except *:
"""
Parse numpy-style dtype string and return element size in bytes.
Supports: i1, u1, i2, u2, i4, u4, i8, u8, f4, f8
"""
if dtype == "i1" or dtype == "u1":
return 1
elif dtype == "i2" or dtype == "u2":
return 2
elif dtype == "i4" or dtype == "u4" or dtype == "f4":
return 4
elif dtype == "i8" or dtype == "u8" or dtype == "f8":
return 8
else:
raise ValueError(
f"Unrecognized dtype '{dtype}'. "
"Expected one of: i1, u1, i2, u2, i4, u4, i8, u8, f4, f8"
)
cdef DPCTLSyclEventRef _copy_memcpy_impl(
SyclQueue q,
object dst,
object src,
size_t byte_count,
DPCTLSyclEventRef *dep_events,
size_t dep_events_count,
queue_copy_fn copy_fn,
queue_copy_with_events_fn copy_with_events_fn
) except *:
cdef void *c_dst_ptr = NULL
cdef void *c_src_ptr = NULL
cdef DPCTLSyclEventRef ERef = NULL
cdef Py_buffer src_buf_view
cdef Py_buffer dst_buf_view
cdef bint src_is_buf = False
cdef bint dst_is_buf = False
cdef int ret_code = 0
if isinstance(src, _Memory):
c_src_ptr = <void*>(<_Memory>src).get_data_ptr()
elif _is_buffer(src):
ret_code = PyObject_GetBuffer(
src, &src_buf_view, PyBUF_SIMPLE | PyBUF_ANY_CONTIGUOUS
)
if ret_code != 0: # pragma: no cover
raise RuntimeError("Could not access buffer")
c_src_ptr = src_buf_view.buf
src_is_buf = True
else:
raise TypeError(
"Parameter `src` should have either type `dpctl.memory._Memory` "
"or a type that supports Python buffer protocol"
)
if isinstance(dst, _Memory):
c_dst_ptr = <void*>(<_Memory>dst).get_data_ptr()
elif _is_buffer(dst):
ret_code = PyObject_GetBuffer(
dst, &dst_buf_view,
PyBUF_SIMPLE | PyBUF_ANY_CONTIGUOUS | PyBUF_WRITABLE
)
if ret_code != 0: # pragma: no cover
if src_is_buf:
PyBuffer_Release(&src_buf_view)
raise RuntimeError("Could not access buffer")
c_dst_ptr = dst_buf_view.buf
dst_is_buf = True
else:
if src_is_buf:
PyBuffer_Release(&src_buf_view)
raise TypeError(
"Parameter `dst` should have either type `dpctl.memory._Memory` "
"or a type that supports Python buffer protocol"
)
if dep_events_count == 0 or dep_events is NULL:
ERef = copy_fn(q._queue_ref, c_dst_ptr, c_src_ptr, byte_count)
else:
ERef = copy_with_events_fn(
q._queue_ref,
c_dst_ptr,
c_src_ptr,
byte_count,
dep_events,
dep_events_count
)
if src_is_buf:
PyBuffer_Release(&src_buf_view)
if dst_is_buf:
PyBuffer_Release(&dst_buf_view)
return ERef
# struct format per dtype used to pack the fill value into its byte pattern.
# The pattern's length is the element size.
# Complex types are packed as (real, imag).
_fill_dtype_formats = {
"i1": "b",
"u1": "B",
"i2": "h",
"u2": "H",
"i4": "i",
"u4": "I",
"f4": "f",
"i8": "q",
"u8": "Q",
"f8": "d",
"c8": "ff",
"c16": "dd",
}
cdef bytes _pack_fill_pattern(object value, str dtype):
"""
Return the native-byte-order byte pattern of ``value`` interpreted as a
single element of ``dtype``. ``sycl::queue::fill`` replicates this pattern
across the destination allocation.
"""
cdef str fmt
if dtype not in _fill_dtype_formats:
raise ValueError(
f"Unrecognized dtype '{dtype}'. Expected one of: "
"i1, u1, i2, u2, i4, u4, i8, u8, f4, f8, c8, c16"
)
fmt = _fill_dtype_formats[dtype]
try:
if dtype == "c8" or dtype == "c16":
# complex: pack real then imag
cval = complex(value)
return struct.pack("=" + fmt, cval.real, cval.imag)
return struct.pack("=" + fmt, value)
except (struct.error, OverflowError, TypeError, ValueError) as e:
raise ValueError(
f"Value {value!r} cannot be represented as dtype '{dtype}': {e}"
)
cdef DPCTLSyclEventRef _fill_impl(
SyclQueue q,
object dst,
object value,
size_t count,
str dtype,
DPCTLSyclEventRef *dep_events,
size_t dep_events_count
) except *:
cdef void *c_dst_ptr = NULL
cdef DPCTLSyclEventRef ERef = NULL
cdef _Memory m_dst
cdef uint64_t val128[2]
cdef bytes pattern = _pack_fill_pattern(value, dtype)
cdef size_t element_size = len(pattern)
cdef bint with_events = dep_events is not NULL and dep_events_count > 0
cdef uint8_t v8
cdef uint16_t v16
cdef uint32_t v32
cdef uint64_t v64
if not isinstance(dst, _Memory):
raise TypeError(
"Parameter `dest` should have type `dpctl.memory._Memory`"
)
m_dst = <_Memory>dst
c_dst_ptr = <void*>m_dst.get_data_ptr()
# check count fits within the allocation
if count > (<size_t>m_dst.nbytes) // element_size:
raise ValueError(
f"Fill of {count} elements of dtype '{dtype}' is too large "
f"to be accommodated in {m_dst.nbytes} bytes allocation"
)
if element_size == 1:
v8 = <uint8_t> int.from_bytes(pattern, sys.byteorder)
if with_events:
ERef = DPCTLQueue_Fill8WithEvents(
q._queue_ref, c_dst_ptr, v8, count,
dep_events, dep_events_count
)
else:
ERef = DPCTLQueue_Fill8(q._queue_ref, c_dst_ptr, v8, count)
elif element_size == 2:
v16 = <uint16_t> int.from_bytes(pattern, sys.byteorder)
if with_events:
ERef = DPCTLQueue_Fill16WithEvents(
q._queue_ref, c_dst_ptr, v16, count,
dep_events, dep_events_count
)
else:
ERef = DPCTLQueue_Fill16(q._queue_ref, c_dst_ptr, v16, count)
elif element_size == 4:
v32 = <uint32_t> int.from_bytes(pattern, sys.byteorder)
if with_events:
ERef = DPCTLQueue_Fill32WithEvents(
q._queue_ref, c_dst_ptr, v32, count,
dep_events, dep_events_count
)
else:
ERef = DPCTLQueue_Fill32(q._queue_ref, c_dst_ptr, v32, count)
elif element_size == 8:
v64 = <uint64_t> int.from_bytes(pattern, sys.byteorder)
if with_events:
ERef = DPCTLQueue_Fill64WithEvents(
q._queue_ref, c_dst_ptr, v64, count,
dep_events, dep_events_count
)
else:
ERef = DPCTLQueue_Fill64(q._queue_ref, c_dst_ptr, v64, count)
else:
# 128-bit pattern is passed as two uint64
val128[0] = <uint64_t> int.from_bytes(pattern[:8], sys.byteorder)
val128[1] = <uint64_t> int.from_bytes(pattern[8:], sys.byteorder)
if with_events:
ERef = DPCTLQueue_Fill128WithEvents(
q._queue_ref, c_dst_ptr, val128, count,
dep_events, dep_events_count
)
else:
ERef = DPCTLQueue_Fill128(q._queue_ref, c_dst_ptr, val128, count)
return ERef
cdef DPCTLSyclEventRef _memcpy_impl(
SyclQueue q,
object dst,
object src,
size_t byte_count,
DPCTLSyclEventRef *dep_events,
size_t dep_events_count
) except *:
return _copy_memcpy_impl(
q, dst, src, byte_count, dep_events, dep_events_count,
DPCTLQueue_Memcpy, DPCTLQueue_MemcpyWithEvents
)
cdef DPCTLSyclEventRef _copy_impl(
SyclQueue q,
object dst,
object src,
size_t count,
DPCTLSyclEventRef *dep_events,
size_t dep_events_count,
str dtype="u1"
) except *:
# ``count`` is in elements of ``dtype`` (default "u1" => bytes).
cdef size_t element_size = _get_dtype_size(dtype)
cdef size_t byte_count = count * element_size
return _copy_memcpy_impl(
q, dst, src, byte_count, dep_events, dep_events_count,
DPCTLQueue_CopyData, DPCTLQueue_CopyDataWithEvents
)
cdef DPCTLSyclEventRef _memset_impl(
SyclQueue q,
object mem,
uint8_t val,
size_t count,
DPCTLSyclEventRef *dep_events,
size_t dep_events_count,
) except *:
cdef void *ptr = NULL
cdef DPCTLSyclEventRef ERef = NULL
if isinstance(mem, _Memory):
ptr = <void*>(<_Memory>mem).get_data_ptr()
else:
raise TypeError("Parameter `mem` should have type _Memory")
if count <= 0 or count > mem.nbytes:
count = mem.nbytes
if dep_events_count == 0 or dep_events is NULL:
ERef = DPCTLQueue_Memset(q._queue_ref, ptr, val, count)
else:
ERef = DPCTLQueue_MemsetWithEvents(
q._queue_ref, ptr, val, count, dep_events, dep_events_count
)
return ERef
cdef class _SyclQueue:
""" Barebone data owner class used by SyclQueue.
"""
def __dealloc__(self):
if (self._queue_ref):
DPCTLQueue_Delete(self._queue_ref)
# self._context is a Python object and will be GC-ed
# self._device is a Python object
cdef class SyclQueue(_SyclQueue):
"""
SyclQueue(*args, **kwargs)
Python class representing ``sycl::queue``.
There are multiple ways to create a :class:`dpctl.SyclQueue` object:
- Invoking the constructor with no arguments creates a context using
the default selector.
:Example:
.. code-block:: python
import dpctl
# Create a default SyclQueue
q = dpctl.SyclQueue()
print(q.sycl_device)
- Invoking the constructor with specific filter selector string that
creates a queue for the device corresponding to the filter string.
:Example:
.. code-block:: python
import dpctl
# Create in-order SyclQueue for either gpu, or cpu device
q = dpctl.SyclQueue("gpu,cpu", property="in_order")
print([q.sycl_device.is_gpu, q.sycl_device.is_cpu])
- Invoking the constructor with a :class:`dpctl.SyclDevice` object
creates a queue for that device, automatically finding/creating
a :class:`dpctl.SyclContext` for the given device.
:Example:
.. code-block:: python
import dpctl
d = dpctl.SyclDevice("gpu")
q = dpctl.SyclQueue(d)
ctx = q.sycl_context
print(q.sycl_device == d)
print(any([ d == ctx_d for ctx_d in ctx.get_devices()]))
- Invoking the constructor with a :class:`dpctl.SyclContext` and a
:class:`dpctl.SyclDevice` creates a queue for given context and
device.
:Example:
.. code-block:: python
import dpctl
# Create a CPU device using the opencl driver
cpu_d = dpctl.SyclDevice("opencl:cpu")
# Partition the CPU device into sub-devices with two cores each.
sub_devices = cpu_d.create_sub_devices(partition=2)
# Create a context common to all the sub-devices.
ctx = dpctl.SyclContext(sub_devices)
# create a queue for each sub-device using the common context
queues = [dpctl.SyclQueue(ctx, sub_d) for sub_d in sub_devices]
- Invoking the constructor with a named ``PyCapsule`` with the name
**"SyclQueueRef"** that carries a pointer to a ``sycl::queue``
object. The capsule will be renamed upon successful consumption
to ensure one-time use. A new named capsule can be constructed by
using :func:`dpctl.SyclQueue._get_capsule` method.
Args:
ctx (:class:`dpctl.SyclContext`, optional): Sycl context to create
:class:`dpctl.SyclQueue` from. If not specified, a single-device
context will be created from the specified device.
dev (str, :class:`dpctl.SyclDevice`, capsule, optional): Sycl device
to create :class:`dpctl.SyclQueue` from. If not specified, sycl
device selected by ``sycl::default_selector`` is used.
The argument must be explicitly specified if `ctxt` argument is
provided.
If `dev` is a named ``PyCapsule`` called **"SyclQueueRef"** and
`ctxt` is not specified, :class:`dpctl.SyclQueue` instance is
created from foreign `sycl::queue` object referenced by the
capsule.
property (str, tuple(str), list(str), optional): Defaults to None.
The argument can be either "default", "in_order",
"enable_profiling", or a tuple containing these.
Raises:
SyclQueueCreationError: If the :class:`dpctl.SyclQueue` object
creation failed.
TypeError: In case of incorrect arguments given to constructors,
unexpected types of input arguments, or in the case the input
capsule contained a null pointer or could not be renamed.
"""
def __cinit__(self, *args, **kwargs):
cdef int len_args
cdef int status = 0
cdef const char *filter_c_str = NULL
if len(args) > 2:
raise TypeError(
"SyclQueue constructor takes 0, 1, or 2 positinal arguments, "
f"but {len(args)} were given."
)
props = _parse_queue_properties(
kwargs.pop("property", _queue_property_type._DEFAULT_PROPERTY)
)
if (kwargs):
raise TypeError(
f"Unsupported keyword arguments {kwargs} to "
"SyclQueue constructor encountered."
)
len_args = len(args)
if len_args == 0:
status = self._init_queue_default(props)
elif len_args == 1:
arg = args[0]
if type(arg) is str:
string = bytes(<str>arg, "utf-8")
filter_c_str = string
status = self._init_queue_from_filter_string(
filter_c_str, props)
elif type(arg) is _SyclQueue:
status = self._init_queue_from__SyclQueue(<_SyclQueue>arg)
elif isinstance(arg, SyclDevice):
status = self._init_queue_from_device(<SyclDevice>arg, props)
elif pycapsule.PyCapsule_IsValid(arg, "SyclQueueRef"):
status = self._init_queue_from_capsule(arg)
else:
raise TypeError(
f"Positional argument {arg} is not a filter string or a "
"SyclDevice"
)
else:
ctx, dev = args
if not isinstance(ctx, SyclContext):
raise TypeError(
"SyclQueue constructor with two positional arguments "
"expected SyclContext as its first argument, but got "
f"{type(ctx)}."
)
if not isinstance(dev, SyclDevice):
raise TypeError(
"SyclQueue constructor with two positional arguments "
"expected SyclDevice as its second argument, but got "
f"{type(dev)}."
)
status = self._init_queue_from_context_and_device(
<SyclContext>ctx, <SyclDevice>dev, props
)
if status < 0:
if status == -1:
raise SyclQueueCreationError(
f"Device filter selector string '{arg}' is not understood."
)
elif status == -2 or status == -8:
default_dev_error = (
"Default SYCL Device could not be created."
)
raise SyclQueueCreationError(
default_dev_error if (len_args == 0) else
f"SYCL Device '{arg}' could not be created."
)
elif status == -3 or status == -7:
raise SyclQueueCreationError(
"SYCL Context could not be created " +
"by default constructor" if len_args == 0 else
f"from '{arg}'."
)
elif status == -4 or status == -6:
if len_args == 2:
arg = args
raise SyclQueueCreationError(
f"SYCL Queue failed to be created from '{arg}'."
)
elif status == -5:
raise TypeError(
f"Input capsule {arg} contains a null pointer or could not "
"be renamed"
)
cdef int _init_queue_from__SyclQueue(self, _SyclQueue other):
""" Copy data container _SyclQueue fields over.
"""
cdef DPCTLSyclQueueRef QRef = DPCTLQueue_Copy(other._queue_ref)
if (QRef is NULL):
return -4
self._queue_ref = QRef
self._context = other._context
self._device = other._device
cdef int _init_queue_from_DPCTLSyclDeviceRef(
self, DPCTLSyclDeviceRef DRef, int props
):
"""
Initializes self by creating SyclQueue with specified error handler and
specified properties from the given device instance. SyclContext is
looked-up by DPCTL from a cache to avoid repeated construction of new
context for performance reasons.
Returns: 0 : normal execution
-3 : Context creation/look-up failed
-4 : queue could not be created from context,device, error
handler and properties
"""
cdef DPCTLSyclContextRef CRef
cdef DPCTLSyclQueueRef QRef
CRef = DPCTLDeviceMgr_GetCachedContext(DRef)
if (CRef is NULL):
# look-up failed (was not a root device?)
# create a new context