Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions accelerator/xpu_accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# DeepSpeed Team

import ctypes

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the required commit sign-off

This is a non-merge commit, but its message contains no Signed-off-by trailer, so it violates the repository's commit requirement. Add the sign-off using the configured Git name and email before merging.

AGENTS.md reference: AGENTS.md:L8-L8

Useful? React with 👍 / 👎.

import torch
from deepspeed.accelerator.abstract_accelerator import DeepSpeedAccelerator
import functools
Expand All @@ -15,6 +16,57 @@
except ImportError as e:
oneccl_imported_p = False

# Mangled names of ``sycl::ext::oneapi::experimental::prepare_for_device_copy(const void*, size_t, const queue&)``
# and ``release_from_device_copy(const void*, const queue&)``. These are the SYCL
# equivalent of ``cudaHostRegister``/``cudaHostUnregister``. Neither SYCL nor torch
# exposes a C entry point for them, so the C++ symbols are resolved directly. The
# names live in SYCL's ``_V1`` inline ABI namespace and are stable across the
# libsycl.so.8 (oneAPI 2025.x) and libsycl.so.9 (oneAPI 2026.x) runtimes.
SYCL_PREPARE_FOR_DEVICE_COPY = "_ZN4sycl3_V13ext6oneapi12experimental23prepare_for_device_copyEPKvmRKNS0_5queueE"
SYCL_RELEASE_FROM_DEVICE_COPY = "_ZN4sycl3_V13ext6oneapi12experimental24release_from_device_copyEPKvRKNS0_5queueE"

# Only ever bind to the SYCL runtime torch already initialized. Opening a second
# one (e.g. via the ``libsycl.so`` development symlink, which may resolve to a
# different oneAPI install) leaves both with their own driver state and aborts at
# interpreter shutdown with UR_RESULT_ERROR_UNINITIALIZED.
RTLD_NOLOAD = 0x00004


def _mapped_sycl_runtime_path():
"""Path of the libsycl the current process already mapped, or None.

Read from /proc/self/maps rather than hardcoding a soname: the soname is
version-dependent (oneAPI 2025.x ships libsycl.so.8, 2026.x ships .so.9) and
the path also disambiguates between several oneAPI installs on one machine.
"""
try:
with open("/proc/self/maps") as maps:
for line in maps:
path = line.rstrip("\n").rpartition(" ")[2]
if "/libsycl.so" in path:
return path
except OSError:
return None
return None


def _sycl_host_copy_funcs():
"""Resolve the SYCL host-registration functions, or return None when unavailable."""
runtime_path = _mapped_sycl_runtime_path()
if runtime_path is None:
return None
try:
libsycl = ctypes.CDLL(runtime_path, mode=RTLD_NOLOAD)
prepare = getattr(libsycl, SYCL_PREPARE_FOR_DEVICE_COPY)
release = getattr(libsycl, SYCL_RELEASE_FROM_DEVICE_COPY)
except (OSError, AttributeError):
return None
prepare.restype = None
prepare.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p]
release.restype = None
release.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
return prepare, release


class XPU_Accelerator(DeepSpeedAccelerator):

Expand Down Expand Up @@ -234,6 +286,34 @@ def _torch_pin_memory(self, tensor):
def _torch_is_pinned(self, tensor):
return tensor.is_pinned(device=self.current_device_name())

def register_host_memory(self, address, num_bytes):
# Resolve the queue first: it initializes torch's XPU runtime, which is
# what loads libsycl.so.8 and makes the RTLD_NOLOAD lookup below succeed.
sycl_queue = self._sycl_queue()
funcs = _sycl_host_copy_funcs()
if funcs is None:
from deepspeed.utils import logger
logger.warning_once("SYCL host-memory registration is unavailable (prepare_for_device_copy not found in "
"the loaded SYCL runtime); native pinned memory stays mlock-only.")
return False
prepare, _ = funcs
prepare(address, num_bytes, sycl_queue)
return True
Comment on lines +299 to +301

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the new XPU registration path

When DS_PIN_MEMORY_BACKEND=native is used on XPU, this call now registers the allocation with SYCL, but docs/code-docs/source/memory.rst still explicitly says native allocations are not registered with XPU and describes device registration as CUDA-only (lines 340–347 and 390–405). This leaves XPU users incorrectly warned that asynchronous copies will block and omits the new fallback behavior, so update the existing pin-memory documentation with this feature.

AGENTS.md reference: AGENTS.md:L26-L26

Useful? React with 👍 / 👎.


def unregister_host_memory(self, address):
sycl_queue = self._sycl_queue()
funcs = _sycl_host_copy_funcs()
if funcs is None:
return None
_, release = funcs
release(address, sycl_queue)

def _sycl_queue(self):
# prepare_for_device_copy registers with the queue's SYCL context, so any
# queue on the current device yields the same registration.
torch.xpu.init()
return torch.xpu.current_stream().sycl_queue

def op_builder_dir(self):
try:
# is op_builder from deepspeed or a 3p version? this should only succeed if it's deepspeed
Expand Down
12 changes: 7 additions & 5 deletions benchmarks/pin_memory/h2d_d2h_bench.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0

# DeepSpeed Team
"""Compare torch and native pinned-memory H2D/D2H bandwidth on one CUDA GPU."""
"""Compare torch and native pinned-memory H2D/D2H bandwidth on one accelerator device."""

import argparse
import json
Expand Down Expand Up @@ -55,7 +55,9 @@ def _time_copy(accelerator, copy_fn, stream, warmup, iters):

def _allocate_host(accelerator, numel, arm):
if arm == "torch":
return torch.empty(numel, dtype=torch.float32, pin_memory=True)
# Go through the accelerator so non-CUDA backends pin against their own
# device rather than torch's CUDA-only ``pin_memory=True`` fast path.
return accelerator._torch_pin_memory(torch.empty(numel, dtype=torch.float32))

return accelerator.pin_memory(torch.empty(numel, dtype=torch.float32), make_copy=False)

Expand All @@ -65,8 +67,8 @@ def _run_arm(args):
os.environ[key] = value

accelerator = get_accelerator()
if accelerator.device_name() != "cuda" or not accelerator.is_available():
raise RuntimeError("CUDA GPU is required")
if not accelerator.is_available():
raise RuntimeError(f"No {accelerator.device_name()} device is available")
accelerator.set_device(0)
stream = accelerator.Stream()

Expand All @@ -86,7 +88,7 @@ def _run_arm(args):
"size_mib": size_mib,
"h2d_gbps": num_bytes / h2d_seconds / 1e9,
"d2h_gbps": num_bytes / d2h_seconds / 1e9,
"torch_is_pinned": host.is_pinned(),
"torch_is_pinned": accelerator._torch_is_pinned(host),
"accelerator_is_pinned": accelerator.is_pinned(host),
}
print(f"RESULT={json.dumps(result, sort_keys=True)}", flush=True)
Expand Down
65 changes: 65 additions & 0 deletions tests/unit/v1/pin_memory/test_pin_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from deepspeed.accelerator.cpu_accelerator import CPU_Accelerator
from deepspeed.accelerator.cuda_accelerator import CUDA_Accelerator
from deepspeed.accelerator import xpu_accelerator
from deepspeed.accelerator.xpu_accelerator import XPU_Accelerator
from deepspeed.utils.pin_memory import NativePinnedMemory


Expand Down Expand Up @@ -197,6 +199,69 @@ def cudaHostUnregister(self, address):
assert errors == [0, 0]


def test_xpu_device_registration_calls_sycl(monkeypatch):

prepared = []
released = []
queue = 0xFEED

def prepare(address, num_bytes, sycl_queue):
prepared.append((address, num_bytes, sycl_queue))

def release(address, sycl_queue):
released.append((address, sycl_queue))

monkeypatch.setattr(xpu_accelerator, "_sycl_host_copy_funcs", lambda: (prepare, release))
accelerator = XPU_Accelerator.__new__(XPU_Accelerator)
monkeypatch.setattr(accelerator, "_sycl_queue", lambda: queue)

assert accelerator.register_host_memory(1234, 4096) is True
accelerator.unregister_host_memory(1234)
assert prepared == [(1234, 4096, queue)]
assert released == [(1234, queue)]


def test_xpu_sycl_lookup_reuses_torch_runtime(monkeypatch):
"""Only the already-mapped runtime may be opened, and only with RTLD_NOLOAD.

Opening a second SYCL runtime (or a hardcoded soname that may resolve to a
different oneAPI install) aborts at interpreter shutdown.
"""
calls = []
mapped = "/some/env/lib/libsycl.so.9"

def fake_cdll(name, mode=0):
calls.append((name, mode))
raise OSError("not loaded")

monkeypatch.setattr(xpu_accelerator, "_mapped_sycl_runtime_path", lambda: mapped)
monkeypatch.setattr(xpu_accelerator.ctypes, "CDLL", fake_cdll)

assert xpu_accelerator._sycl_host_copy_funcs() is None
assert calls == [(mapped, xpu_accelerator.RTLD_NOLOAD)]


def test_xpu_sycl_lookup_without_mapped_runtime(monkeypatch):
"""No libsycl mapped means XPU was never initialized; must not try to load one."""

def fail_cdll(name, mode=0):
raise AssertionError("must not dlopen a SYCL runtime that is not already mapped")

monkeypatch.setattr(xpu_accelerator, "_mapped_sycl_runtime_path", lambda: None)
monkeypatch.setattr(xpu_accelerator.ctypes, "CDLL", fail_cdll)

assert xpu_accelerator._sycl_host_copy_funcs() is None


def test_xpu_device_registration_without_sycl_symbols(monkeypatch):
"""Missing prepare_for_device_copy must degrade to mlock-only, not raise."""
monkeypatch.setattr(xpu_accelerator, "_sycl_host_copy_funcs", lambda: None)
accelerator = XPU_Accelerator.__new__(XPU_Accelerator)

assert accelerator.register_host_memory(1234, 4096) is False
assert accelerator.unregister_host_memory(1234) is None


def test_cpu_native_pin_with_register_env_on(monkeypatch, native_pins):
"""CPU accelerator has no register hook; native pin still works with default-on."""
monkeypatch.setenv("DS_PIN_MEMORY_REGISTER_DEVICE", "1")
Expand Down
Loading