Skip to content

Commit bf4e5a1

Browse files
committed
Make SyclDevice and SyclQueue picklable
Root devices pickle by filter string and name; unpickling checks the name. Queues pickle by device and properties and unpickle into the device's default context; queues on non-default contexts and on sub-devices raise PicklingError. copy and deepcopy return the same object. Closes #1716
1 parent 2ed816f commit bf4e5a1

7 files changed

Lines changed: 206 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313
* Added `dpctl::utils::defer_release` to `dpctl4pybind11.hpp`, which calls a release callback once the given events have completed [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
1414
* Added `dpctl.SyclQueue.get_last_event` and `dpctl.SyclQueue.is_get_last_event_available`, and the `DPCTLQueue_GetLastEvent` and `DPCTLQueue_GetLastEvent_Available` C-API functions, wrapping the DPC++ `sycl_ext_oneapi_in_order_queue_events` extension [gh-2299](https://github.com/IntelPython/dpctl/pull/2299)
1515

16+
* `dpctl.SyclDevice` and `dpctl.SyclQueue` can be pickled; root devices are restored by filter string, queues by device and properties into the device's default context. `copy.copy` and `copy.deepcopy` return the same object
17+
1618
### Changed
1719
* Object lifetime during offload is now managed by a list of releases deferred until the events that gate them have completed, rather than by a `host_task`. `dpctl` keeps one thread for looking over the list and running the releases that have come due, started by the first release deferred and again in the child of a `fork`, which takes the GIL to do so and lets a release call into the interpreter and free USM allocations [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)
1820
* `import_dpctl()` now returns 0 on success and -1 with a Python exception set on failure, and `dpctl4pybind11.hpp` raises that exception rather than failing on the first C-API call [gh-2359](https://github.com/IntelPython/dpctl/pull/2359)

‎dpctl/_sycl_device.pyx‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ from ._sycl_platform cimport SyclPlatform
155155

156156
import collections
157157
import functools
158+
import pickle
158159
import warnings
159160

160161
__all__ = [
@@ -371,6 +372,21 @@ def _cached_filter_string(d : SyclDevice):
371372
return ":".join((br_str, dt_str, str(relId)))
372373

373374

375+
def _rebuild_device(str filter_string, str name):
376+
"""Unpickles a :class:`dpctl.SyclDevice`.
377+
378+
Raises:
379+
pickle.UnpicklingError: if the device selected by ``filter_string``
380+
is not named ``name``.
381+
"""
382+
dev = SyclDevice(filter_string)
383+
if dev.name != name:
384+
raise pickle.UnpicklingError(
385+
f"Device '{filter_string}' is '{dev.name}', expected '{name}'"
386+
)
387+
return dev
388+
389+
374390
cdef class SyclDevice(_SyclDevice):
375391
""" SyclDevice(arg=None)
376392
A Python wrapper for the ``sycl::device`` C++ class.
@@ -1652,6 +1668,24 @@ cdef class SyclDevice(_SyclDevice):
16521668
"""
16531669
return DPCTLDevice_Hash(self._device_ref)
16541670

1671+
def __reduce__(self):
1672+
"""Pickles a root device by its filter string and name.
1673+
1674+
Raises:
1675+
pickle.PicklingError: if the device is not a root device.
1676+
"""
1677+
try:
1678+
filter_string = self.filter_string
1679+
except ValueError as e:
1680+
raise pickle.PicklingError(f"Cannot pickle {self!r}: {e}") from e
1681+
return _rebuild_device, (filter_string, self.name)
1682+
1683+
def __copy__(self):
1684+
return self
1685+
1686+
def __deepcopy__(self, memo):
1687+
return self
1688+
16551689
cdef tuple create_sub_devices_equally(self, size_t count):
16561690
""" Returns a tuple of sub-devices partitioned from this SYCL device
16571691
based on the ``count`` parameter.

‎dpctl/_sycl_queue.pyx‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"""
2424

2525
from ._backend cimport ( # noqa: E211
26+
DPCTLContext_AreEq,
2627
DPCTLContext_Create,
2728
DPCTLContext_Delete,
2829
DPCTLDefaultSelector_Create,
@@ -107,6 +108,7 @@ import atexit
107108
import collections.abc
108109
import logging
109110
import os
111+
import pickle
110112
import struct
111113
import sys
112114
import warnings
@@ -792,6 +794,13 @@ cdef DPCTLSyclEventRef _memset_impl(
792794
return ERef
793795

794796

797+
def _rebuild_queue(SyclDevice dev, tuple props):
798+
"""Unpickles a :class:`dpctl.SyclQueue` into the default context of
799+
``dev``.
800+
"""
801+
return SyclQueue(dev, property=props)
802+
803+
795804
cdef class _SyclQueue:
796805
""" Barebone data owner class used by SyclQueue.
797806
"""
@@ -2275,6 +2284,44 @@ cdef class SyclQueue(_SyclQueue):
22752284
"""
22762285
return DPCTLQueue_Hash(self._queue_ref)
22772286

2287+
def __reduce__(self):
2288+
"""Pickles the queue's device and properties. The unpickled queue
2289+
uses the default context of the device.
2290+
2291+
Raises:
2292+
pickle.PicklingError: if the queue's context is not the default
2293+
context of its device, or the device is not a root device.
2294+
"""
2295+
cdef DPCTLSyclContextRef CRef = NULL
2296+
cdef bint is_default_ctx = False
2297+
# sub-devices have no cached context, SyclDevice.__reduce__ rejects them
2298+
if self._device.parent_device is None:
2299+
CRef = DPCTLDeviceMgr_GetCachedContext(
2300+
self._device.get_device_ref()
2301+
)
2302+
if CRef is not NULL:
2303+
is_default_ctx = DPCTLContext_AreEq(
2304+
CRef, self._context.get_context_ref()
2305+
)
2306+
DPCTLContext_Delete(CRef)
2307+
if not is_default_ctx:
2308+
raise pickle.PicklingError(
2309+
f"Cannot pickle {self!r}: its context is not the default "
2310+
"context of its device"
2311+
)
2312+
props = []
2313+
if DPCTLQueue_IsInOrder(self._queue_ref):
2314+
props.append("in_order")
2315+
if DPCTLQueue_HasEnableProfiling(self._queue_ref):
2316+
props.append("enable_profiling")
2317+
return _rebuild_queue, (self._device, tuple(props))
2318+
2319+
def __copy__(self):
2320+
return self
2321+
2322+
def __deepcopy__(self, memo):
2323+
return self
2324+
22782325
def _get_capsule(self):
22792326
cdef DPCTLSyclQueueRef QRef = NULL
22802327
QRef = DPCTLQueue_Copy(self._queue_ref)

‎dpctl/tests/helper/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from ._helper import (
2020
create_invalid_capsule,
2121
get_queue_or_skip,
22+
get_sub_device_or_skip,
2223
has_cpu,
2324
has_gpu,
2425
has_sycl_platforms,
@@ -30,4 +31,5 @@
3031
"has_gpu",
3132
"has_sycl_platforms",
3233
"get_queue_or_skip",
34+
"get_sub_device_or_skip",
3335
]

‎dpctl/tests/helper/_helper.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,13 @@ def get_queue_or_skip(args=()):
4949
except dpctl.SyclQueueCreationError:
5050
pytest.skip(f"Queue could not be created from {args}")
5151
return q
52+
53+
54+
def get_sub_device_or_skip():
55+
for dev in dpctl.get_devices():
56+
for partition in ("next_partitionable", [1, 1]):
57+
try:
58+
return dev.create_sub_devices(partition=partition)[0]
59+
except dpctl.SyclSubDeviceCreationError:
60+
pass
61+
pytest.skip("No device can be partitioned")

‎dpctl/tests/test_sycl_device.py‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,15 @@
1616

1717
"""Defines unit test cases for the SyclDevice class."""
1818

19+
import copy
20+
import pickle
21+
1922
import pytest
2023

2124
import dpctl
2225
from dpctl import SyclDeviceCreationError
2326

24-
from .helper import get_queue_or_skip
27+
from .helper import get_queue_or_skip, get_sub_device_or_skip
2528

2629

2730
def test_standard_selectors(device_selector, check):
@@ -455,3 +458,38 @@ def test_peer_access_value_keyword_validation():
455458
bad_value = "wrong"
456459
with pytest.raises(ValueError):
457460
dev0.can_access_peer(dev1, value=bad_value)
461+
462+
463+
def test_device_pickling():
464+
devs = dpctl.get_devices()
465+
if not devs:
466+
pytest.skip("No devices available")
467+
for dev in devs:
468+
dev2 = pickle.loads(pickle.dumps(dev))
469+
assert dev2 == dev
470+
assert dev2.filter_string == dev.filter_string
471+
472+
473+
def test_device_pickling_sub_device():
474+
sub_dev = get_sub_device_or_skip()
475+
with pytest.raises(pickle.PicklingError):
476+
pickle.dumps(sub_dev)
477+
478+
479+
def test_device_unpickling_name_mismatch():
480+
from dpctl._sycl_device import _rebuild_device
481+
482+
try:
483+
dev = dpctl.SyclDevice()
484+
except SyclDeviceCreationError:
485+
pytest.skip("No default device available")
486+
with pytest.raises(pickle.UnpicklingError):
487+
_rebuild_device(dev.filter_string, dev.name + " (other)")
488+
489+
490+
def test_device_copy():
491+
sub_dev = get_sub_device_or_skip()
492+
root_dev = sub_dev.parent_device
493+
for dev in (root_dev, sub_dev):
494+
assert copy.copy(dev) is dev
495+
assert copy.deepcopy(dev) is dev

‎dpctl/tests/test_sycl_queue.py‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,22 @@
1616

1717
"""Defines unit test cases for the SyclQueue class."""
1818

19+
import copy
1920
import ctypes
21+
import pickle
22+
import subprocess
2023
import sys
2124

2225
import pytest
2326

2427
import dpctl
2528
import dpctl.memory
2629

27-
from .helper import create_invalid_capsule
30+
from .helper import (
31+
create_invalid_capsule,
32+
get_queue_or_skip,
33+
get_sub_device_or_skip,
34+
)
2835

2936

3037
def test_standard_selectors(device_selector, check):
@@ -480,3 +487,67 @@ def test_submit_keep_args_alive_deprecated():
480487
ht_ev.wait()
481488
# attributed to the caller
482489
assert record[0].filename == __file__
490+
491+
492+
@pytest.mark.parametrize(
493+
"props",
494+
[
495+
(),
496+
("in_order",),
497+
("enable_profiling",),
498+
("in_order", "enable_profiling"),
499+
],
500+
)
501+
def test_queue_pickling(props):
502+
try:
503+
q = dpctl.SyclQueue(property=props or "default")
504+
except dpctl.SyclQueueCreationError:
505+
pytest.skip("Default-constructed queue could not be created")
506+
q2 = pickle.loads(pickle.dumps(q))
507+
assert isinstance(q2, dpctl.SyclQueue)
508+
assert q2.sycl_device == q.sycl_device
509+
assert q2.sycl_context == q.sycl_context
510+
assert q2.is_in_order == ("in_order" in props)
511+
assert q2.has_enable_profiling == ("enable_profiling" in props)
512+
513+
514+
def test_queue_pickling_non_default_context():
515+
q = get_queue_or_skip()
516+
dev = q.sycl_device
517+
ctx = dpctl.SyclContext([dev])
518+
if ctx == q.sycl_context:
519+
pytest.skip("Context created from device list is the default context")
520+
with pytest.raises(pickle.PicklingError):
521+
pickle.dumps(dpctl.SyclQueue(ctx, dev))
522+
523+
524+
def test_queue_pickling_sub_device():
525+
sub_dev = get_sub_device_or_skip()
526+
q = dpctl.SyclQueue(sub_dev)
527+
with pytest.raises(pickle.PicklingError):
528+
pickle.dumps(q)
529+
530+
531+
def test_queue_unpickling_in_subprocess():
532+
q = get_queue_or_skip()
533+
q = dpctl.SyclQueue(q.sycl_device, property="in_order")
534+
script = (
535+
"import pickle, sys\n"
536+
"q = pickle.loads(sys.stdin.buffer.read())\n"
537+
"print(q.sycl_device.filter_string, q.is_in_order)\n"
538+
)
539+
res = subprocess.run(
540+
[sys.executable, "-c", script],
541+
input=pickle.dumps(q),
542+
capture_output=True,
543+
check=True,
544+
)
545+
assert res.stdout.decode().split() == [q.sycl_device.filter_string, "True"]
546+
547+
548+
def test_queue_copy():
549+
q = get_queue_or_skip()
550+
assert copy.copy(q) is q
551+
assert copy.deepcopy(q) is q
552+
d = copy.deepcopy({"queue": q})
553+
assert d["queue"] is q

0 commit comments

Comments
 (0)