Repository navigation
Expand file tree
/
Copy pathtest_sycl_queue.py
More file actions
603 lines (505 loc) · 18.2 KB
/
Copy pathtest_sycl_queue.py
File metadata and controls
603 lines (505 loc) · 18.2 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
# 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.
"""Defines unit test cases for the SyclQueue class."""
import copy
import ctypes
import pickle
import subprocess
import sys
import pytest
import dpctl
import dpctl.memory
from dpctl._sycl_queue_manager import get_device_cached_queue
from .helper import (
create_invalid_capsule,
get_queue_or_skip,
get_sub_device_or_skip,
is_adaptivecpp,
is_wsl_or_windows,
skip_if_usm_unsupported,
)
def test_standard_selectors(device_selector, check):
"""
Tests if the standard SYCL device_selectors are able to select a device.
"""
try:
device = device_selector()
if device.default_selector_score < 0:
pytest.skip()
q = dpctl.SyclQueue(device)
check(q.get_sycl_device())
except dpctl.SyclDeviceCreationError:
pytest.skip()
def test_valid_filter_selectors(valid_filter, check):
"""
Tests if we can create a SyclDevice using a supported filter selector
string.
"""
device = None
try:
q = dpctl.SyclQueue(valid_filter)
device = q.get_sycl_device()
assert q.is_in_order is False
q2 = dpctl.SyclQueue(valid_filter, property="in_order")
# assert device == q2.get_sycl_device()
assert q2.is_in_order is True
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create device with supported filter")
check(device)
def test_invalid_filter_selectors(invalid_filter):
"""
An invalid filter string should always be caught and a
SyclQueueCreationError raised.
"""
expected_exception = (
dpctl.SyclQueueCreationError
if isinstance(invalid_filter, str)
else TypeError
)
with pytest.raises(expected_exception):
dpctl.SyclQueue(invalid_filter)
def test_unexpected_keyword():
"""
An unexpected keyword use raises TypeError.
"""
with pytest.raises(TypeError):
dpctl.SyclQueue(device="cpu")
def test_context_not_equals():
try:
gpuQ = dpctl.SyclQueue("gpu")
except dpctl.SyclQueueCreationError:
pytest.skip()
ctx_gpu = gpuQ.get_sycl_context()
try:
cpuQ = dpctl.SyclQueue("cpu")
except dpctl.SyclQueueCreationError:
pytest.skip()
ctx_cpu = cpuQ.get_sycl_context()
assert ctx_cpu != ctx_gpu
assert hash(ctx_cpu) != hash(ctx_gpu)
assert gpuQ != cpuQ
assert hash(cpuQ) != hash(gpuQ)
def test_context_equals():
try:
gpuQ1 = dpctl.SyclQueue("gpu")
gpuQ0 = dpctl.SyclQueue("gpu")
except dpctl.SyclQueueCreationError:
pytest.skip()
ctx0 = gpuQ0.get_sycl_context()
ctx1 = gpuQ1.get_sycl_context()
assert ctx0 == ctx1
assert hash(ctx0) == hash(ctx1)
def test_has_enable_profiling():
try:
q = dpctl.SyclQueue(property="enable_profiling")
except dpctl.SyclQueueCreationError:
pytest.skip("Could not create queue with profiling property enabled")
assert q.has_enable_profiling
def test_hashing_of_queue():
"""
Test that a :class:`dpctl.SyclQueue` object can be used as
a dictionary key.
"""
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Default-constructed queue could not be created")
queue_dict = {q: "default_queue"}
assert queue_dict
def test_channeling_device_properties(capsys):
try:
q = dpctl.SyclQueue()
dev = q.sycl_device
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create device from default selector")
q.print_device_info() # should execute without raising
q_captured = capsys.readouterr()
q_output = q_captured.out
dev.print_device_info()
d_captured = capsys.readouterr()
d_output = d_captured.out
assert q_output, "No output captured"
assert q_output == d_output, "Mismatch in print_device_info"
assert q_captured.err == "" and d_captured.err == ""
for pr in ["backend", "name", "driver_version"]:
assert getattr(q, pr) == getattr(
dev, pr
), f"Mismatch found for property {pr}"
def test_queue_submit_barrier(valid_filter):
try:
q = dpctl.SyclQueue(valid_filter)
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create device with supported filter")
ev1 = q.submit_barrier()
ev2 = q.submit_barrier()
ev3 = q.submit_barrier([ev1, ev2])
ev3.wait()
ev1.wait()
ev2.wait()
with pytest.raises(TypeError):
q.submit_barrier(range(3))
def test_queue_is_get_last_event_available():
assert isinstance(dpctl.SyclQueue.is_get_last_event_available(), bool)
def test_queue_get_last_event():
if not dpctl.SyclQueue.is_get_last_event_available():
pytest.skip("sycl_ext_oneapi_in_order_queue_events not available")
try:
q = dpctl.SyclQueue(property="in_order")
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created for default-selected device")
buf = dpctl.memory.MemoryUSMDevice(1024, queue=q)
ev = q.memset_async(buf, 1, 1024)
last_ev = q.get_last_event()
assert isinstance(last_ev, dpctl.SyclEvent)
last_ev.wait()
assert ev.execution_status == dpctl.event_status_type.complete
def test_queue_get_last_event_out_of_order():
if not dpctl.SyclQueue.is_get_last_event_available():
pytest.skip("sycl_ext_oneapi_in_order_queue_events not available")
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created for default-selected device")
with pytest.raises(ValueError):
q.get_last_event()
def test_queue_submit_barrier_waits_for_prior_work():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Default queue could not be created")
from dpctl.memory import MemoryUSMDevice, USMAllocationError
nbytes = 256 * 1024 * 1024
try:
m1 = MemoryUSMDevice(nbytes, queue=q)
m2 = MemoryUSMDevice(nbytes, queue=q)
except USMAllocationError:
pytest.skip("Not enough memory")
# compile the barrier kernel first
q.submit_barrier().wait()
ev = q.memcpy_async(m1, m2, nbytes)
q.submit_barrier().wait()
assert ev.execution_status == dpctl.event_status_type.complete
def test_queue__repr__():
try:
q1 = dpctl.SyclQueue(property=0)
except dpctl.SyclQueueCreationError:
pytest.skip()
r1 = q1.__repr__()
assert type(r1) is str
try:
q2 = dpctl.SyclQueue(property="in_order")
except dpctl.SyclQueueCreationError:
pytest.skip()
r2 = q2.__repr__()
assert type(r2) is str
try:
q3 = dpctl.SyclQueue(property="enable_profiling")
except dpctl.SyclQueueCreationError:
pytest.skip()
r3 = q3.__repr__()
assert type(r3) is str
try:
q4 = dpctl.SyclQueue(property="default")
except dpctl.SyclQueueCreationError:
pytest.skip()
r4 = q4.__repr__()
assert type(r4) is str
try:
q5 = dpctl.SyclQueue(property=["in_order", "enable_profiling", 0])
except dpctl.SyclQueueCreationError:
pytest.skip()
r5 = q5.__repr__()
assert type(r5) is str
def test_queue_invalid_property():
with pytest.raises(ValueError):
dpctl.SyclQueue(property=4.5)
with pytest.raises(ValueError):
dpctl.SyclQueue(property=["abc", ()])
def test_queue_capsule():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Can not defaul-construct SyclQueue")
cap = q._get_capsule()
cap2 = q._get_capsule()
q2 = dpctl.SyclQueue(cap)
assert q == q2
del cap2 # call deleter on non-renamed capsule
assert q2 != [] # compare with other types
def test_queue_ctor():
# construct from device
try:
d = dpctl.SyclDevice()
except dpctl.SyclDeviceCreationError:
pytest.skip("Could not create default device")
q = dpctl.SyclQueue(d)
assert q.sycl_device == d
ctx = dpctl.SyclContext(d)
q = dpctl.SyclQueue(ctx, d)
assert q.sycl_context == ctx
assert q.sycl_device == d
def test_cpython_api_SyclQueue_GetQueueRef():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Can not default-construct SyclQueue")
mod = sys.modules[q.__class__.__module__]
# get capsule storign SyclQueue_GetQueueRef function ptr
q_ref_fn_cap = mod.__pyx_capi__["SyclQueue_GetQueueRef"]
# construct Python callable to invoke "SyclQueue_GetQueueRef"
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]
q_ref_fn_ptr = cap_ptr_fn(
q_ref_fn_cap, b"DPCTLSyclQueueRef (struct PySyclQueueObject *)"
)
callable_maker = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)
get_queue_ref_fn = callable_maker(q_ref_fn_ptr)
r2 = q.addressof_ref()
r1 = get_queue_ref_fn(q)
assert r1 == r2
def test_cpython_api_SyclQueue_Make():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Can not defaul-construct SyclQueue")
mod = sys.modules[q.__class__.__module__]
# get capsule storing SyclQueue_Make function ptr
make_SyclQueue_fn_cap = mod.__pyx_capi__["SyclQueue_Make"]
# construct Python callable to invoke "SyclQueue_Make"
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]
make_SyclQueue_fn_ptr = cap_ptr_fn(
make_SyclQueue_fn_cap, b"struct PySyclQueueObject *(DPCTLSyclQueueRef)"
)
callable_maker = ctypes.PYFUNCTYPE(ctypes.py_object, ctypes.c_void_p)
make_SyclQueue_fn = callable_maker(make_SyclQueue_fn_ptr)
q2 = make_SyclQueue_fn(q.addressof_ref())
assert q.sycl_device == q2.sycl_device
assert q.sycl_context == q2.sycl_context
def test_constructor_many_arg():
with pytest.raises(TypeError):
dpctl.SyclQueue(None, None, None, None)
with pytest.raises(TypeError):
dpctl.SyclQueue(None, None)
try:
ctx = dpctl.SyclContext()
except dpctl.SyclContextCreationError:
pytest.skip()
with pytest.raises(TypeError):
dpctl.SyclQueue(ctx, None)
with pytest.raises(TypeError):
dpctl.SyclQueue(ctx)
def test_constructor_inconsistent_ctx_dev():
try:
q = dpctl.SyclQueue("cpu")
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create CPU queue")
cpuD = q.sycl_device
n_eu = cpuD.max_compute_units
n_half = n_eu // 2
try:
d0, d1 = cpuD.create_sub_devices(partition=[n_half, n_eu - n_half])
except Exception:
pytest.skip("Could not create CPU sub-devices")
ctx = dpctl.SyclContext(d0)
with pytest.raises(dpctl.SyclQueueCreationError):
dpctl.SyclQueue(ctx, d1)
def test_constructor_invalid_capsule():
cap = create_invalid_capsule()
with pytest.raises(TypeError):
dpctl.SyclQueue(cap)
def test_queue_wait():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create default queue")
q.wait()
def test_queue_memops():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Failed to create device with supported filter")
from dpctl.memory import MemoryUSMShared
skip_if_usm_unsupported(MemoryUSMShared, q)
m1 = MemoryUSMShared(512, queue=q)
m2 = MemoryUSMShared(512, queue=q)
q.memcpy(m1, m2, 512)
with pytest.raises(TypeError):
q.memcpy(m1, [], 512)
with pytest.raises(TypeError):
q.memcpy([], m2, 512)
# AdaptiveCpp prefetches by migrating the allocation to the device, which
# the OpenCL CPU runtime rejects with CL_INVALID_VALUE
acpp_opencl_cpu = (
is_adaptivecpp()
and q.sycl_device.backend == dpctl.backend_type.opencl
and q.sycl_device.has_aspect_cpu
)
acpp_skip = is_adaptivecpp() and (is_wsl_or_windows() or acpp_opencl_cpu)
if not acpp_skip:
q.prefetch(m1, 512)
with pytest.raises(TypeError):
q.prefetch([], 512)
# AdaptiveCpp does not implement mem_advise
if not is_adaptivecpp():
q.mem_advise(m1, 512, 0)
with pytest.raises(TypeError):
q.mem_advise([], 512, 0)
@pytest.fixture(scope="session")
def dpctl_cython_extension(tmp_path_factory):
import os
import os.path
import shutil
import subprocess
import sys
import sysconfig
curr_dir = os.path.dirname(__file__)
dr = tmp_path_factory.mktemp("_cython_api")
for fn in ["_cython_api.pyx", "setup_cython_api.py"]:
shutil.copy(
src=os.path.join(curr_dir, fn),
dst=dr,
follow_symlinks=False,
)
res = subprocess.run(
[sys.executable, "setup_cython_api.py", "build_ext", "--inplace"],
cwd=dr,
env=os.environ,
)
if res.returncode == 0:
import glob
from importlib.util import module_from_spec, spec_from_file_location
sfx = sysconfig.get_config_vars()["EXT_SUFFIX"]
pth = glob.glob(os.path.join(dr, "_cython_api*" + sfx))
if not pth:
pytest.fail("Cython extension was not built")
spec = spec_from_file_location("_cython_api", pth[0])
builder_module = module_from_spec(spec)
spec.loader.exec_module(builder_module)
return builder_module
else:
pytest.fail("Cython extension could not be built")
def test_cython_api(dpctl_cython_extension):
try:
q = dpctl_cython_extension.call_create_from_context_and_devices()
except (dpctl.SyclDeviceCreationError, dpctl.SyclQueueCreationError):
pytest.skip()
try:
d = dpctl.SyclDevice()
except dpctl.SyclDeviceCreationError:
pytest.skip("Default-construction of SyclDevice failed")
assert q.sycl_device == d
def test_keep_args_alive_validates_events():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created for default-selected device")
usm = dpctl.memory.MemoryUSMDevice(4096, queue=q)
with pytest.raises(TypeError):
q.keep_args_alive((usm,), [None])
def test_keep_args_alive_depends_length_differs_from_iteration():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created for default-selected device")
class Events:
def __init__(self, events):
self._events = events
def __len__(self):
return 1
def __iter__(self):
return iter(self._events)
usm = dpctl.memory.MemoryUSMDevice(4096, queue=q)
events = [q.submit_barrier() for _ in range(4)]
q.keep_args_alive((usm,), Events(events)).wait()
q.keep_args_alive((usm,), (e for e in events)).wait()
def test_submit_keep_args_alive_deprecated():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created for default-selected device")
usm = dpctl.memory.MemoryUSMDevice(4096, queue=q)
with pytest.warns(DeprecationWarning) as record:
ht_ev = q._submit_keep_args_alive((usm,), [])
ht_ev.wait()
# attributed to the caller
assert record[0].filename == __file__
@pytest.mark.parametrize(
"props",
[
(),
("in_order",),
("enable_profiling",),
("in_order", "enable_profiling"),
],
)
def test_queue_pickling(props):
try:
q = dpctl.SyclQueue(property=props or "default")
except dpctl.SyclQueueCreationError:
pytest.skip("Default-constructed queue could not be created")
q2 = pickle.loads(pickle.dumps(q))
assert isinstance(q2, dpctl.SyclQueue)
assert q2.sycl_device == q.sycl_device
assert q2.sycl_context == q.sycl_context
assert q2.is_in_order == ("in_order" in props)
assert q2.has_enable_profiling == ("enable_profiling" in props)
assert (q2 == get_device_cached_queue(q.sycl_device)) == (not props)
def test_queue_unpickling_cached_queue():
dev = get_queue_or_skip().sycl_device
cached = get_device_cached_queue(dev)
q0, q1 = dpctl.SyclQueue(dev), dpctl.SyclQueue(dev)
assert q0 != q1
assert pickle.loads(pickle.dumps(q0)) == cached
assert pickle.loads(pickle.dumps(q1)) == cached
q2 = dpctl.SyclQueue(dev, property="in_order")
assert pickle.loads(pickle.dumps(q2)) != pickle.loads(pickle.dumps(q2))
def test_queue_pickling_non_default_context():
q = get_queue_or_skip()
dev = q.sycl_device
ctx = dpctl.SyclContext([dev])
if ctx == q.sycl_context:
pytest.skip("Context created from device list is the default context")
with pytest.raises(pickle.PicklingError, match="SyclQueue.*context"):
pickle.dumps(dpctl.SyclQueue(ctx, dev))
def test_queue_pickling_sub_device():
sub_dev = get_sub_device_or_skip()
q = dpctl.SyclQueue(sub_dev)
with pytest.raises(pickle.PicklingError, match="not a root device"):
pickle.dumps(q)
def test_queue_unpickling_in_subprocess():
q = get_queue_or_skip()
q = dpctl.SyclQueue(q.sycl_device, property="in_order")
script = (
"import pickle, sys\n"
"q = pickle.loads(sys.stdin.buffer.read())\n"
"print(q.sycl_device.filter_string, q.is_in_order)\n"
)
res = subprocess.run(
[sys.executable, "-c", script],
input=pickle.dumps(q),
capture_output=True,
check=True,
)
assert res.stdout.decode().split() == [q.sycl_device.filter_string, "True"]
def test_queue_copy():
q = get_queue_or_skip()
assert copy.copy(q) is q
assert copy.deepcopy(q) is q
d = copy.deepcopy({"queue": q})
assert d["queue"] is q