Repository navigation
Expand file tree
/
Copy path_compiler.pyx
More file actions
836 lines (717 loc) · 30 KB
/
Copy path_compiler.pyx
File metadata and controls
836 lines (717 loc) · 30 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
# 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 a Python interface for SYCL's kernel bundle and kernel runtime
classes.
The module also provides functions to create a SYCL kernel bundle from either
an OpenCL source string or a SPIR-V binary file.
"""
from cpython.buffer cimport (
Py_buffer,
PyBUF_ANY_CONTIGUOUS,
PyBUF_SIMPLE,
PyBuffer_Release,
PyObject_CheckBuffer,
PyObject_GetBuffer,
)
from cpython.bytes cimport PyBytes_FromStringAndSize
from libc.stdint cimport UINT32_MAX, uint32_t
from libc.stdlib cimport free, malloc
from libc.string cimport memcmp, memcpy
from dpctl._backend cimport ( # noqa: E211, E402;
DPCTLBuildOptionList_Append,
DPCTLBuildOptionList_Create,
DPCTLBuildOptionList_Delete,
DPCTLBuildOptionListRef,
DPCTLKernel_Copy,
DPCTLKernel_Delete,
DPCTLKernel_GetCompileNumSubGroups,
DPCTLKernel_GetCompileSubGroupSize,
DPCTLKernel_GetMaxNumSubGroups,
DPCTLKernel_GetMaxSubGroupSize,
DPCTLKernel_GetNumArgs,
DPCTLKernel_GetPreferredWorkGroupSizeMultiple,
DPCTLKernel_GetPrivateMemSize,
DPCTLKernel_GetWorkGroupSize,
DPCTLKernelBuildLog_Create,
DPCTLKernelBuildLog_Delete,
DPCTLKernelBuildLog_Get,
DPCTLKernelBuildLogRef,
DPCTLKernelBundle_Copy,
DPCTLKernelBundle_CreateFromOCLSource,
DPCTLKernelBundle_CreateFromSpirv,
DPCTLKernelBundle_CreateFromSYCLSource,
DPCTLKernelBundle_CreateFromSYCLSource_Available,
DPCTLKernelBundle_Delete,
DPCTLKernelBundle_GetKernel,
DPCTLKernelBundle_GetSyclKernel,
DPCTLKernelBundle_HasKernel,
DPCTLKernelBundle_HasSyclKernel,
DPCTLKernelNameList_Append,
DPCTLKernelNameList_Create,
DPCTLKernelNameList_Delete,
DPCTLKernelNameListRef,
DPCTLSyclContextRef,
DPCTLSyclDeviceRef,
DPCTLSyclKernelBundleRef,
DPCTLSyclKernelRef,
DPCTLVirtualHeaderList_Append,
DPCTLVirtualHeaderList_Create,
DPCTLVirtualHeaderList_Delete,
DPCTLVirtualHeaderListRef,
_spec_const,
)
import numbers
import numpy as np
__all__ = [
"create_kernel_bundle_from_source",
"create_kernel_bundle_from_spirv",
"create_kernel_bundle_from_sycl_source",
"is_sycl_source_compilation_available",
"SyclKernel",
"SyclKernelBundle",
"SyclKernelBundleCompilationError",
"SpecializationConstant",
]
cdef class SyclKernelBundleCompilationError(Exception):
"""This exception is raised when a ``sycl::kernel_bundle`` could not be
built from either a SPIR-V binary file or a string source.
"""
pass
cpdef bint is_sycl_source_compilation_available():
"""Returns True if dpctl was built with compiler that supports the DPC++
`kernel_compiler` extension API used by
:func:`create_kernel_bundle_from_sycl_source`.
Device support is separate; callers should also check
``q.sycl_device.can_compile('sycl')`` (or similar) for specific devices.
"""
return DPCTLKernelBundle_CreateFromSYCLSource_Available()
cdef class SyclKernel:
"""
"""
@staticmethod
cdef SyclKernel _create(DPCTLSyclKernelRef kref, str name):
cdef SyclKernel ret = SyclKernel.__new__(SyclKernel)
ret._kernel_ref = kref
ret._function_name = name
return ret
def __dealloc__(self):
DPCTLKernel_Delete(self._kernel_ref)
def get_function_name(self):
""" Returns the name of the ``sycl::kernel`` function.
"""
return self._function_name
def get_num_args(self):
""" Returns the number of arguments for this kernel function.
For a kernel compiled from SYCL source, this is the number of
arguments of the backend kernel, in which a ``sycl::local_accessor``
parameter is four arguments.
Raises:
RuntimeError:
If the number of arguments can not be queried.
"""
cdef size_t n = DPCTLKernel_GetNumArgs(self._kernel_ref)
if n == <size_t>-1:
raise RuntimeError(
"The number of arguments of kernel "
f"'{self._function_name}' can not be queried."
)
return n
cdef DPCTLSyclKernelRef get_kernel_ref(self):
""" Returns the ``DPCTLSyclKernelRef`` pointer for this SyclKernel.
"""
return self._kernel_ref
def addressof_ref(self):
""" Returns the address of the C API ``DPCTLSyclKernelRef`` pointer
as a ``size_t``.
Returns:
The address of the ``DPCTLSyclKernelRef`` pointer used to create
this :class:`dpctl.SyclKernel` object cast to a ``size_t``.
"""
return int(<size_t>self._kernel_ref)
@property
def num_args(self):
""" Property equivalent to method call `SyclKernel.get_num_args()`
"""
return self.get_num_args()
@property
def work_group_size(self):
""" Returns the maximum number of work-items in a work-group that can
be used to execute the kernel on device it was built for.
"""
cdef size_t v = DPCTLKernel_GetWorkGroupSize(self._kernel_ref)
return v
@property
def preferred_work_group_size_multiple(self):
""" Returns a value, of which work-group size is preferred to be
a multiple, for executing the kernel on the device it was built for.
"""
cdef size_t v = DPCTLKernel_GetPreferredWorkGroupSizeMultiple(
self._kernel_ref
)
return v
@property
def private_mem_size(self):
""" Returns the minimum amount of private memory, in bytes, used by each
work-item in the kernel.
"""
cdef size_t v = DPCTLKernel_GetPrivateMemSize(self._kernel_ref)
return v
@property
def max_num_sub_groups(self):
""" Returns the maximum number of sub-groups for this kernel.
"""
cdef uint32_t n = DPCTLKernel_GetMaxNumSubGroups(self._kernel_ref)
return n
@property
def max_sub_group_size(self):
""" Returns the maximum sub-groups size for this kernel.
"""
cdef uint32_t sz = DPCTLKernel_GetMaxSubGroupSize(self._kernel_ref)
return sz
@property
def compile_num_sub_groups(self):
""" Returns the number of sub-groups specified by this kernel,
or 0 (if not specified).
"""
cdef size_t n = DPCTLKernel_GetCompileNumSubGroups(self._kernel_ref)
return n
@property
def compile_sub_group_size(self):
""" Returns the required sub-group size specified by this kernel,
or 0 (if not specified).
"""
cdef size_t n = DPCTLKernel_GetCompileSubGroupSize(self._kernel_ref)
return n
cdef api DPCTLSyclKernelRef SyclKernel_GetKernelRef(SyclKernel ker):
""" C-API function to access opaque kernel reference from
Python object of type :class:`dpctl.compiler.SyclKernel`.
"""
return ker.get_kernel_ref()
cdef api SyclKernel SyclKernel_Make(DPCTLSyclKernelRef KRef, const char *name):
"""
C-API function to create :class:`dpctl.compiler.SyclKernel`
instance from opaque sycl kernel reference.
"""
cdef DPCTLSyclKernelRef copied_KRef = DPCTLKernel_Copy(KRef)
if (name is NULL):
return SyclKernel._create(copied_KRef, "default_name")
else:
return SyclKernel._create(copied_KRef, name.decode("utf-8"))
cdef class SyclKernelBundle:
""" Wraps a ``sycl::kernel_bundle<sycl::bundle_state::executable>`` object
created using SYCL interoperability layer with underlying backends. Only the
OpenCL and Level-Zero backends are currently supported.
SyclKernelBundle exposes the C API from
``dpctl_sycl_kernel_bundle_interface.h``. A SyclKernelBundle can be
created from an OpenCL C source string
(:func:`.create_kernel_bundle_from_source`), a SPIR-V binary file
(:func:`.create_kernel_bundle_from_spirv`), or a SYCL source string
(:func:`.create_kernel_bundle_from_sycl_source`).
Creation from SYCL source uses the DPC++ ``kernel_compiler`` extension,
which requires both a compiler and a device that support it. Use
:func:`.is_sycl_source_compilation_available` to check for compiler
support.
"""
@staticmethod
cdef SyclKernelBundle _create(DPCTLSyclKernelBundleRef KBRef,
bint is_sycl_source):
cdef SyclKernelBundle ret = SyclKernelBundle.__new__(SyclKernelBundle)
ret._kernel_bundle_ref = KBRef
ret._is_sycl_source = is_sycl_source
return ret
def __dealloc__(self):
DPCTLKernelBundle_Delete(self._kernel_bundle_ref)
cdef DPCTLSyclKernelBundleRef get_kernel_bundle_ref(self):
return self._kernel_bundle_ref
cpdef SyclKernel get_sycl_kernel(self, str kernel_name):
"""get_sycl_kernel(kernel_name)
Returns the kernel with the given name defined in this kernel bundle.
Args:
kernel_name (str):
Name of the kernel, as it appears in the kernel bundle. For a
bundle created from a SPIR-V binary this is the name of the
entry point, which for a kernel written in SYCL is the mangled
name of its kernel class, e.g.
``'_ZTS20BasicSpecConstKernel'``.
Returns:
dpctl.compiler.SyclKernel:
The kernel object.
Raises:
ValueError:
If the kernel could not be created for any reason.
"""
cdef bytes name = kernel_name.encode("utf8")
cdef DPCTLSyclKernelRef KRef = NULL
if self._is_sycl_source:
KRef = DPCTLKernelBundle_GetSyclKernel(
self._kernel_bundle_ref, name
)
else:
KRef = DPCTLKernelBundle_GetKernel(self._kernel_bundle_ref, name)
if KRef is NULL:
# returning a SyclKernel with a NULL reference would defer the
# failure to the submission of the kernel
raise ValueError(
f"Kernel '{kernel_name}' could not be created from the kernel "
"bundle. The kernel bundle may not define a kernel with that "
"name, or the module it was built from may require device "
"libraries that were not linked into it."
)
return SyclKernel._create(KRef, kernel_name)
def has_sycl_kernel(self, str kernel_name):
name = kernel_name.encode("utf8")
if self._is_sycl_source:
return DPCTLKernelBundle_HasSyclKernel(
self._kernel_bundle_ref, name
)
return DPCTLKernelBundle_HasKernel(self._kernel_bundle_ref, name)
def addressof_ref(self):
"""Returns the address of the C API DPCTLSyclKernelBundleRef pointer
as a long.
Returns:
The address of the ``DPCTLSyclKernelBundleRef`` pointer used to
create this :class:`dpctl.SyclKernelBundle` object cast to a
``size_t``.
"""
return int(<size_t>self._kernel_bundle_ref)
cdef api DPCTLSyclKernelBundleRef SyclKernelBundle_GetKernelBundleRef(
SyclKernelBundle kb
):
""" C-API function to access opaque kernel bundle reference from
Python object of type :class:`dpctl.compiler.SyclKernelBundle`.
"""
return kb.get_kernel_bundle_ref()
cdef api SyclKernelBundle SyclKernelBundle_Make(DPCTLSyclKernelBundleRef KBRef):
"""
C-API function to create :class:`dpctl.compiler.SyclKernelBundle`
instance from opaque ``sycl::kernel_bundle<sycl::bundle_state::executable>``
reference.
"""
cdef DPCTLSyclKernelBundleRef copied_KBRef = DPCTLKernelBundle_Copy(KBRef)
return SyclKernelBundle._create(copied_KBRef, False)
cdef class SpecializationConstant:
"""
SpecializationConstant(spec_id, *args)
Python class representing SYCL specialization constants that can be used
when creating a :class:`dpctl.compiler.SyclKernelBundle` from SPIR-V.
There are multiple ways to create a :class:`.SpecializationConstant`:
- ``SpecializationConstant(spec_id, obj)``
If the constructor is invoked with a single variadic argument, the
argument is expected to either expose the Python buffer protocol or be
coercible to a NumPy array. If the argument is coercible to a NumPy array
or is one, it must have a supported data type (bool, integral, or
floating point). The specialization constant will be constructed from the
data in the buffer
- ``SpecializationConstant(spec_id, dtype, obj)``
If the constructor is invoked with two variadic arguments, and the first
argument is a string, it is interpreted as a NumPy ``dtype`` string and
the second argument will be coerced to a NumPy array with that data type.
The data type specified by the first argument must be a supported data
type (bool, integral, or floating point).
- ``SpecializationConstant(spec_id, nbytes, raw_ptr)``
If the constructor is invoked with two variadic arguments where both are
integers, the first argument is interpreted as the number of bytes and
the second argument is interpreted as a pointer to the data.
Note that construction of the :class:`.SpecializationConstant` copies the
input, so modifications made after construction of the
:class:`.SpecializationConstant` will not be reflected in the
:class:`.SyclKernelBundle`.
Args:
spec_id (int):
The SPIR-V specialization ID.
args:
Variadic argument, see class documentation.
Raises:
TypeError: In case of incorrect arguments given to constructor,
failure to coerce to a buffer, or unsupported data type when
coercing to a buffer.
ValueError: If the provided object fails to construct a buffer.
"""
cdef _spec_const _spec_const
def __cinit__(self, spec_id, *args):
cdef int ret_code = 0
cdef object target_obj = None
cdef Py_buffer _local_buffer
cdef void *copied_data
if not isinstance(spec_id, numbers.Integral):
raise TypeError(
"Specialization constant ID must be of type `int`, got "
f"{type(spec_id)}"
)
if len(args) == 0 or len(args) > 2:
raise TypeError(
"Constructor takes 2 or 3 arguments, got "
f"{len(args) + 1}."
)
if spec_id < 0 or spec_id > UINT32_MAX:
raise ValueError(
"Specialization constant ID must fit in a 32-bit unsigned "
f"integer (0 <= id <= {UINT32_MAX}), got {spec_id}"
)
self._spec_const.id = <uint32_t>spec_id
if len(args) == 2:
if (
isinstance(args[0], numbers.Integral) and
isinstance(args[1], numbers.Integral)
):
if args[0] <= 0:
raise ValueError(
"Size must be a positive integer when constructing "
f"from a pointer and size, got {args[0]}"
)
target_obj = PyBytes_FromStringAndSize(
<const char *><size_t>args[1], <Py_ssize_t>args[0]
)
elif isinstance(args[0], str):
target_obj = np.ascontiguousarray(args[1], dtype=args[0])
else:
raise TypeError(
"Invalid arguments."
)
elif len(args) == 1:
target_obj = args[0]
if not PyObject_CheckBuffer(target_obj):
# attempt to coerce to a numpy array
target_obj = np.ascontiguousarray(target_obj)
if isinstance(target_obj, np.ndarray):
if target_obj.dtype.kind not in ("b", "i", "u", "f", "c"):
raise TypeError(
"Coercion of input to buffer resulted in an unsupported "
f"data type '{target_obj.dtype}'. When coercing objects, "
"`SpecializationConstant` expects the data to coerce to a "
"supported type: bool, integral, or real or complex "
"floating point. To pass arbitrary data, use a "
"`memoryview` or `bytes` object, or pass the pointer and "
"size directly."
)
ret_code = PyObject_GetBuffer(
target_obj, &(_local_buffer), PyBUF_SIMPLE | PyBUF_ANY_CONTIGUOUS
)
if ret_code != 0:
raise ValueError(
"Failed to get buffer view for the provided object."
)
if _local_buffer.len <= 0:
PyBuffer_Release(&(_local_buffer))
raise ValueError(
"Specialization constant value must not be zero-sized."
)
self._spec_const.size = <size_t>_local_buffer.len
copied_data = malloc(self._spec_const.size)
if copied_data == NULL:
PyBuffer_Release(&(_local_buffer))
raise MemoryError(
"Failed to allocate memory for specialization constant data."
)
memcpy(copied_data, _local_buffer.buf, self._spec_const.size)
self._spec_const.value = copied_data
PyBuffer_Release(&(_local_buffer))
def __dealloc__(self):
if self._spec_const.value != NULL:
free(<void*>self._spec_const.value)
def __repr__(self):
return f"SpecializationConstant({self._spec_const.id})"
def __eq__(self, other):
if not isinstance(other, SpecializationConstant):
return NotImplemented
cdef SpecializationConstant _other = <SpecializationConstant>other
if (
self._spec_const.id != _other._spec_const.id or
self._spec_const.size != _other._spec_const.size
):
return False
if self._spec_const.value == _other._spec_const.value:
return True
return memcmp(
self._spec_const.value,
_other._spec_const.value,
self._spec_const.size
) == 0
def __hash__(self):
cdef bytes value_bytes
if self._spec_const.value != NULL:
value_bytes = (<char *>self._spec_const.value)[
:self._spec_const.size
]
else:
value_bytes = b""
return hash((self._spec_const.id, value_bytes))
@property
def id(self):
"""Returns the specialization ID for this specialization constant."""
return self._spec_const.id
@property
def size(self):
"""
Returns the size in bytes of the data for this specialization constant.
"""
return self._spec_const.size
cdef size_t addressof(self):
"""
Returns the address of the _spec_const for this
:class:`.SpecializationConstant` cast to ``size_t``.
"""
return <size_t>&(self._spec_const)
def addressof_ref(self):
"""Returns the address of the ``_spec_const`` struct for this
:class:`.SpecializationConstant` cast to ``size_t``.
Returns:
The address of the internal ``_spec_const`` struct used by
this :class:`.SpecializationConstant` object cast to a
``size_t``.
"""
return self.addressof()
cpdef create_kernel_bundle_from_source(SyclQueue q, str src, str copts=""):
"""
Creates a Sycl interoperability kernel bundle from an OpenCL source
string.
We use the ``DPCTLKernelBundle_CreateFromOCLSource()`` C API function
to create a ``sycl::kernel_bundle<sycl::bundle_state::executable>``
from an OpenCL source program that can contain multiple kernels.
Note: This function is currently only supported for the OpenCL backend.
Parameters:
q (:class:`dpctl.SyclQueue`)
The :class:`dpctl.SyclQueue` for which the
:class:`.SyclKernelBundle` is going to be built.
src (str)
Source string for an OpenCL program.
copts (str, optional)
Optional compilation flags that will be used
when compiling the kernel bundle. Default: ``""``.
Returns:
kernel_bundle (:class:`.SyclKernelBundle`)
A :class:`.SyclKernelBundle` object wrapping the
``sycl::kernel_bundle<sycl::bundle_state::executable>``
returned by the C API.
Raises:
SyclKernelBundleCompilationError
If a SYCL kernel bundle could not be created.
"""
cdef DPCTLSyclKernelBundleRef KBref
cdef bytes bSrc = src.encode("utf8")
cdef bytes bCOpts = copts.encode("utf8")
cdef const char *Src = <const char*>bSrc
cdef const char *COpts = <const char*>bCOpts
cdef DPCTLSyclContextRef CRef = q.get_sycl_context().get_context_ref()
cdef DPCTLSyclDeviceRef DRef = q.get_sycl_device().get_device_ref()
KBref = DPCTLKernelBundle_CreateFromOCLSource(CRef, DRef, Src, COpts)
if KBref is NULL:
raise SyclKernelBundleCompilationError()
return SyclKernelBundle._create(KBref, False)
cpdef create_kernel_bundle_from_spirv(
SyclQueue q,
const unsigned char[:] IL,
str copts="",
list specializations=None,
):
"""
Creates a Sycl interoperability kernel bundle from an SPIR-V binary.
We use the :c:func:`DPCTLKernelBundle_CreateFromOCLSpirv` C API function
to create a ``sycl::kernel_bundle<sycl::bundle_state::executable>``
object from an compiled SPIR-V binary file.
Parameters:
q (:class:`dpctl.SyclQueue`)
The :class:`dpctl.SyclQueue` for which the
:class:`.SyclKernelBundle` is going to be built.
IL (bytes)
SPIR-V binary IL file for an OpenCL program.
copts (str, optional)
Optional compilation flags that will be used
when compiling the kernel bundle. Default: ``""``.
specializations (list, optional)
A list of :class:`.SpecializationConstant` objects to be used
when creating the kernel bundle. Default: ``None``.
Returns:
kernel_bundle (:class:`.SyclKernelBundle`)
A :class:`.SyclKernelBundle` object wrapping the
``sycl::kernel_bundle<sycl::bundle_state::executable>``
returned by the C API.
Raises:
SyclKernelBundleCompilationError
If a SYCL kernel bundle could not be created.
"""
cdef DPCTLSyclKernelBundleRef KBref
cdef const unsigned char *dIL = &IL[0]
cdef DPCTLSyclContextRef CRef = q.get_sycl_context().get_context_ref()
cdef DPCTLSyclDeviceRef DRef = q.get_sycl_device().get_device_ref()
cdef size_t length = IL.shape[0]
cdef bytes bCOpts = copts.encode("utf8")
cdef const char *COpts = <const char*>bCOpts
cdef size_t num_spconsts
cdef _spec_const *spconsts
cdef SpecializationConstant spconst
if specializations is not None and len(specializations) > 0:
num_spconsts = len(specializations)
spconsts = <_spec_const *>(
malloc(num_spconsts * sizeof(_spec_const))
)
if spconsts == NULL:
raise MemoryError(
"Failed to allocate memory for specialization constants."
)
for i, _spconst in enumerate(specializations):
if not isinstance(_spconst, SpecializationConstant):
free(spconsts)
raise TypeError(
"All items in specializations must be of type "
f"`SpecializationConstant`, got {type(_spconst)}"
)
spconst = <SpecializationConstant>_spconst
spconsts[i] = spconst._spec_const
else:
num_spconsts = 0
spconsts = NULL
try:
KBref = DPCTLKernelBundle_CreateFromSpirv(
CRef,
DRef,
<const void*>dIL,
length, COpts,
num_spconsts,
spconsts,
)
if KBref is NULL:
raise SyclKernelBundleCompilationError()
finally:
if spconsts != NULL:
free(spconsts)
return SyclKernelBundle._create(KBref, False)
cpdef create_kernel_bundle_from_sycl_source(SyclQueue q,
unicode source,
list headers=None,
list registered_names=None,
list copts=None):
"""
Creates an executable SYCL kernel_bundle from SYCL source code.
This uses the DPC++ ``kernel_compiler`` extension to create a
``sycl::kernel_bundle<sycl::bundle_state::executable>`` object from
SYCL source code.
Parameters:
q (:class:`dpctl.SyclQueue`)
The :class:`dpctl.SyclQueue` for which the
:class:`.SyclKernelBundle` is going to be built.
source (unicode)
SYCL source code string.
headers (list, optional)
Optional list of virtual headers, where each entry in the list
needs to be a tuple of header name and header content. See the
documentation of the ``include_files`` property in the DPC++
``kernel_compiler`` extension for more information.
Default: ``None``
registered_names (list, optional)
Optional list of kernel names to register. See the
documentation of the ``registered_names`` property in the DPC++
``kernel_compiler`` extension for more information.
Default: ``None``
copts (list, optional)
Optional list of compilation flags that will be used
when compiling the program.
Default: ``None``
Returns:
kernel_bundle (:class:`.SyclKernelBundle`)
A :class:`.SyclKernelBundle` object wrapping the
``sycl::kernel_bundle<sycl::bundle_state::executable>``
returned by the C API.
Raises:
SyclKernelBundleCompilationError
If a SYCL kernel bundle could not be created. The exception
message contains the build log for more details.
"""
cdef DPCTLSyclKernelBundleRef KBref = NULL
cdef DPCTLSyclContextRef CRef = q.get_sycl_context().get_context_ref()
cdef DPCTLSyclDeviceRef DRef = q.get_sycl_device().get_device_ref()
cdef bytes bSrc = source.encode("utf8")
cdef const char *Src = <const char*>bSrc
# initialized to NULL so that the `finally` clause below can release
# whichever of these were created before an exception was raised
cdef DPCTLBuildOptionListRef BuildOpts = NULL
cdef DPCTLKernelNameListRef KernelNames = NULL
cdef DPCTLVirtualHeaderListRef VirtualHeaders = NULL
cdef DPCTLKernelBuildLogRef BuildLog = NULL
cdef bytes bOpt
cdef const char* sOpt
cdef bytes bName
cdef const char* sName
cdef bytes bContent
cdef const char* sContent
cdef const char* buildLogContent
if headers is None:
headers = []
if registered_names is None:
registered_names = []
if copts is None:
copts = []
try:
BuildOpts = DPCTLBuildOptionList_Create()
KernelNames = DPCTLKernelNameList_Create()
VirtualHeaders = DPCTLVirtualHeaderList_Create()
BuildLog = DPCTLKernelBuildLog_Create()
for opt in copts:
if not isinstance(opt, unicode):
raise TypeError(
"Every element of `copts` must be a string, got "
f"{type(opt)}"
)
bOpt = opt.encode("utf8")
sOpt = <const char*>bOpt
DPCTLBuildOptionList_Append(BuildOpts, sOpt)
for name in registered_names:
if not isinstance(name, unicode):
raise TypeError(
"Every element of `registered_names` must be a string, "
f"got {type(name)}"
)
bName = name.encode("utf8")
sName = <const char*>bName
DPCTLKernelNameList_Append(KernelNames, sName)
for header in headers:
if not isinstance(header, tuple) or len(header) != 2:
raise TypeError(
"Every element of `headers` must be a 2-tuple of header "
"name and header content"
)
name, content = header
if (
not isinstance(name, unicode)
or not isinstance(content, unicode)
):
raise TypeError(
"Header names and header content must be strings, got "
f"({type(name)}, {type(content)})"
)
bName = name.encode("utf8")
sName = <const char*>bName
bContent = content.encode("utf8")
sContent = <const char*>bContent
DPCTLVirtualHeaderList_Append(VirtualHeaders, sName, sContent)
KBref = DPCTLKernelBundle_CreateFromSYCLSource(
CRef, DRef, Src, VirtualHeaders, KernelNames, BuildOpts, BuildLog
)
if KBref is NULL:
buildLogContent = DPCTLKernelBuildLog_Get(BuildLog)
raise SyclKernelBundleCompilationError(
str(buildLogContent, "utf-8")
)
finally:
DPCTLBuildOptionList_Delete(BuildOpts)
DPCTLKernelNameList_Delete(KernelNames)
DPCTLVirtualHeaderList_Delete(VirtualHeaders)
DPCTLKernelBuildLog_Delete(BuildLog)
return SyclKernelBundle._create(KBref, True)