From 524f8caf8f41b3c690a653ce07f7e1b5fa5b79a4 Mon Sep 17 00:00:00 2001 From: Martin Durant Date: Tue, 24 Nov 2026 16:26:52 -0500 Subject: [PATCH 1/2] RFC: cuFile in cuda.core --- cuda_core/cuda/core/_cpp/rt/rt.hpp | 1 + cuda_core/cuda/core/_rt.pxd | 4 + cuda_core/cuda/core/_rt.pyx | 4 + cuda_core/cuda/core/storage/__init__.py | 10 + cuda_core/cuda/core/storage/_batch.py | 129 ++++++ cuda_core/cuda/core/storage/_file.py | 525 ++++++++++++++++++++++ cuda_core/cuda/core/storage/_transfer.pyx | 293 ++++++++++++ cuda_core/docs/source/api.rst | 9 + cuda_core/docs/source/api_private.rst | 10 + cuda_core/docs/source/storage.rst | 142 ++++++ cuda_core/tests/test_storage.py | 383 ++++++++++++++++ 11 files changed, 1510 insertions(+) create mode 100644 cuda_core/cuda/core/storage/__init__.py create mode 100644 cuda_core/cuda/core/storage/_batch.py create mode 100644 cuda_core/cuda/core/storage/_file.py create mode 100644 cuda_core/cuda/core/storage/_transfer.pyx create mode 100644 cuda_core/docs/source/storage.rst create mode 100644 cuda_core/tests/test_storage.py diff --git a/cuda_core/cuda/core/_cpp/rt/rt.hpp b/cuda_core/cuda/core/_cpp/rt/rt.hpp index 7b843017225c..3ff05c91e5d5 100644 --- a/cuda_core/cuda/core/_cpp/rt/rt.hpp +++ b/cuda_core/cuda/core/_cpp/rt/rt.hpp @@ -11,3 +11,4 @@ #include "driver_api.hpp" #include "error.hpp" #include "api.hpp" +#include "context_scope.hpp" diff --git a/cuda_core/cuda/core/_rt.pxd b/cuda_core/cuda/core/_rt.pxd index 60617192c4ba..a4230a0d6446 100644 --- a/cuda_core/cuda/core/_rt.pxd +++ b/cuda_core/cuda/core/_rt.pxd @@ -217,6 +217,10 @@ cdef GreenCtxHandle create_green_ctx_handle( cdef GreenCtxHandle create_green_ctx_handle_ref(cydriver.CUgreenCtx ctx) except+ nogil cdef ContextHandle get_primary_context(int device_id) except+ nogil cdef ContextHandle get_current_context() except+ nogil +cdef cydriver.CUresult enter_context( + const ContextHandle& h_context, cydriver.CUcontext* previous, int* changed) noexcept nogil +cdef cydriver.CUresult exit_context( + cydriver.CUcontext previous, int changed, cydriver.CUresult operation_status) noexcept nogil cdef cydriver.CUresult context_synchronize( const ContextHandle& h_context) noexcept nogil cdef cydriver.CUresult context_get_stream_priority_range( diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index c8f165203c31..ce460e54c19c 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -82,6 +82,10 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": ContextHandle get_primary_context "cuda_core::rt::get_primary_context" ( int device_id) except+ nogil ContextHandle get_current_context "cuda_core::rt::get_current_context" () except+ nogil + cydriver.CUresult enter_context "cuda_core::rt::detail::enter_context" ( + const ContextHandle& h_context, cydriver.CUcontext* previous, int* changed) noexcept nogil + cydriver.CUresult exit_context "cuda_core::rt::detail::exit_context" ( + cydriver.CUcontext previous, int changed, cydriver.CUresult operation_status) noexcept nogil cydriver.CUresult context_synchronize "cuda_core::rt::context_synchronize" ( const ContextHandle& h_context) noexcept nogil cydriver.CUresult context_get_stream_priority_range "cuda_core::rt::context_get_stream_priority_range" ( diff --git a/cuda_core/cuda/core/storage/__init__.py b/cuda_core/cuda/core/storage/__init__.py new file mode 100644 index 000000000000..4c7787fba31d --- /dev/null +++ b/cuda_core/cuda/core/storage/__init__.py @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Binary file I/O between the filesystem and CUDA device memory.""" + +from ._batch import read_batch, write_batch +from ._file import open, open_file + +__all__ = ["open", "open_file", "read_batch", "write_batch"] diff --git a/cuda_core/cuda/core/storage/_batch.py b/cuda_core/cuda/core/storage/_batch.py new file mode 100644 index 000000000000..2624e1f45082 --- /dev/null +++ b/cuda_core/cuda/core/storage/_batch.py @@ -0,0 +1,129 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +import os +from collections.abc import Iterable +from contextlib import ExitStack +from ctypes import addressof, c_ssize_t, c_uint + +from cuda.core._memory._buffer import Buffer + +from ._file import _File, _open_file, _Path +from ._transfer import _BatchOwners + +_FileOrPath = _File | _Path +_Entry = tuple[_FileOrPath, Buffer, int] | tuple[_FileOrPath, Buffer, int, int | None] + + +def read_batch(entries: Iterable[_Entry]) -> list[int]: + """Read several file ranges into GPU buffers in one cuFile batch. + + Each entry is ``(file, buffer, offset)`` or ``(file, buffer, offset, size)``. + A file can be a path or a handle from :func:`cuda.core.storage.open_file`. + Handles opened for paths are closed when the call exits. Offsets and sizes + are in bytes. An omitted or ``None`` size uses the buffer's full size. + Zero-size entries return zero. + + Waits on the host and returns byte counts in input order. The operations + may execute in any order. Use independent ranges and buffers where + accesses would conflict. Have a CUDA context current, and synchronize any + prior CUDA work that uses these buffers before calling. Keep the files + and buffers open through the call. A failed entry raises after the batch + completes, and other entries may already have transferred data. + """ + return _batch(entries, writing=False) + + +def write_batch(entries: Iterable[_Entry]) -> list[int]: + """Write from GPU buffers into several file ranges in one cuFile batch. + + Entries, byte counts, and synchronization follow :func:`read_batch`. + Each entry supplies the GPU buffer containing its source bytes. Paths + are opened for positional writes. Missing files are created and existing + bytes outside the written ranges are preserved. + """ + return _batch(entries, writing=True) + + +def _batch(entries: Iterable[_Entry], *, writing: bool) -> list[int]: + with ExitStack() as files: + opened: dict[bytes, _File] = {} + counts: list[int] = [] + active = [] + for entry in entries: + target, buffer, offset, *sizes = entry + if len(sizes) > 1: + raise TypeError("expected (file or path, buffer, offset[, size])") + if isinstance(target, _File): + file = target + else: + path = os.fsencode(target) + file = opened.get(path) + if file is None: + mode = "wb" if writing else "rb" + file = files.enter_context(_open_file(path, mode, direct=False, truncate=False)) + opened[path] = file + offset, size = file._prepare(buffer, offset, sizes[0] if sizes else None, writing=writing) + if (buffer.size or buffer.handle) and (not buffer.is_device_accessible or buffer.is_host_accessible): + raise ValueError("cuFile I/O requires device-resident GPU memory") + if size: + active.append((file, buffer, offset, size, len(counts))) + counts.append(0) + if active: + _submit_batch(active, counts, writing=writing) + return counts + + +def _submit_batch(active: list[tuple[_File, Buffer, int, int, int]], counts: list[int], *, writing: bool) -> None: + cufile = active[0][0]._cufile + count = len(active) + params = cufile.IOParams(count) + events = cufile.IOEvents(count) + owners = _BatchOwners(active, params, events) + opcode = cufile.Opcode.WRITE if writing else cufile.Opcode.READ + for index, (file, buffer, offset, size, _) in enumerate(active): + param = params[index] + param.mode = cufile.BatchMode.BATCH + param.fh = file._handle + param.opcode = opcode + param.cookie = index + 1 + param.u.batch.dev_ptr_base = buffer.handle + param.u.batch.file_offset = offset + param.u.batch.dev_ptr_offset = 0 + param.u.batch.size_ = size + + returned = c_uint() + completed: set[int] = set() + failures = [] + batch = cufile.batch_io_set_up(count) + try: + cufile.batch_io_submit(batch, count, params.ptr, 0) + while len(completed) < count: + returned.value = count - len(completed) + cufile.batch_io_get_status(batch, 1, addressof(returned), events.ptr, 0) + for i in range(returned.value): + event = events[i] + index = event.cookie - 1 + if not 0 <= index < count or index in completed: + raise RuntimeError("internal cuda.core error, please report: invalid cuFile batch completion") + completed.add(index) + entry_index = active[index][4] + result = c_ssize_t(event.ret).value + if event.status == cufile.Status.COMPLETE and result >= 0: + counts[entry_index] = result + else: + failures.append(f"entry {entry_index}: {event.status.name} (cuFile result {result})") + except BaseException as error: + try: + cufile.batch_io_destroy(batch) + except Exception as cleanup: + if len(completed) != count: + for file, *_ in active: + file._unresolved_batch = True + owners.abandon() + error.add_note(f"destroying the cuFile batch failed: {cleanup}") + raise + cufile.batch_io_destroy(batch) + if failures: + raise OSError("cuFile batch failed: " + "; ".join(failures)) diff --git a/cuda_core/cuda/core/storage/_file.py b/cuda_core/cuda/core/storage/_file.py new file mode 100644 index 000000000000..a013f5336b4e --- /dev/null +++ b/cuda_core/cuda/core/storage/_file.py @@ -0,0 +1,525 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import operator +import os +import stat +import sys +import threading +import warnings +from collections import OrderedDict +from collections.abc import Iterable +from types import ModuleType, TracebackType + +from cuda.core import CUDAWarning, Stream +from cuda.core._memory._buffer import Buffer + +from ._transfer import _allocate, _CountPool, _new_stream, _resize_output, _Transfer, _validate_stream + +# cuObject and other remote storage backends can reuse the GPU buffer and +# transfer lifetime machinery when they have compatible completion semantics. +_Path = str | bytes | os.PathLike[str] | os.PathLike[bytes] +_FileEntry = tuple[Buffer, int] | tuple[Buffer, int, int | None] +_MAX_OFFSET = (1 << 63) - 1 +_MODES = { + "rb": os.O_RDONLY, + "r+b": os.O_RDWR, + "wb": os.O_WRONLY | os.O_CREAT, + "w+b": os.O_RDWR | os.O_CREAT, + "xb": os.O_WRONLY | os.O_CREAT | os.O_EXCL, + "x+b": os.O_RDWR | os.O_CREAT | os.O_EXCL, +} + + +def open_file(path: _Path, mode: str = "rb", *, direct: bool = False) -> _File: + """Open a regular binary file for transfers between disk and GPU memory. + + Parameters + ---------- + path : str or bytes or os.PathLike + Path to a local filesystem file. + mode : str, optional + Binary mode. Use ``"rb"`` to read, ``"wb"`` to create or truncate, + or ``"xb"`` to create exclusively. Add ``+`` for read/write access. + direct : bool, optional + Open with Linux ``O_DIRECT``. cuFile chooses the transfer path based + on the filesystem, hardware, and its configuration. It can use host + staging internally. + + Returns + ------- + :class:`._File` + An open file for positional asynchronous and batch I/O. Use as a + context manager or call ``close()``. + + Notes + ----- + Requires Linux and the cuFile runtime. + """ + return _open_file(path, mode, direct=direct, truncate=True) + + +def _open_file(path: _Path, mode: str, *, direct: bool, truncate: bool) -> _File: + if sys.platform != "linux": + raise RuntimeError("cuFile storage is available only on Linux") + if mode in ("rb+", "wb+", "xb+"): + mode = mode[0] + "+b" + if mode not in _MODES: + raise ValueError("mode must be a binary mode: rb, r+b, wb, w+b, xb, or x+b") + from cuda.bindings import cufile + + # Resolve the optional runtime before opening a path for writing. + cufile.get_version() + file = _File(cufile, mode) + fd = os.open(path, _MODES[mode] | (os.O_DIRECT if direct else 0)) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise ValueError("cuFile storage requires a regular file") + desc = cufile.Descr() + desc.type = cufile.FileHandleType.OPAQUE_FD + desc.handle.fd = fd + desc.fs_ops = 0 + file._handle = cufile.handle_register(desc.ptr) + if truncate and mode.startswith("w"): + os.ftruncate(fd, 0) + except BaseException as error: + if file._handle is not None: + try: + cufile.handle_deregister(file._handle) + except Exception as exc: + error.add_note(f"cuFile deregistration failed: {exc}") + try: + os.close(fd) + except OSError as exc: + error.add_note(f"closing the file descriptor failed: {exc}") + raise + file._fd = fd + return file + + +def open(path: _Path, mode: str = "rb", *, stream: Stream | None, direct: bool = False) -> _StreamFile: + """Open a binary GPU file with a cursor bound to a CUDA stream. + + Pass an explicit CUDA stream, or pass `stream=None` to create one on the + current context (device 0's primary context if none is current). + `mode` and `direct` have the same meaning as in :func:`open_file`. + Closing the returned object closes the underlying file and any stream + created by this function. + """ + owns_stream = stream is None + if stream is None: + stream = _new_stream() + else: + _validate_stream(stream) + with_file = None + try: + with_file = open_file(path, mode, direct=direct) + return _StreamFile(with_file, stream, owns_file=True, owns_stream=owns_stream) + except BaseException as error: + if with_file is not None: + with_file.__exit__(type(error), error, error.__traceback__) + if owns_stream: + try: + stream.close() + except Exception as cleanup: + error.add_note(f"closing the CUDA stream failed: {cleanup}") + raise + + +class _Request: + """Completion of one positional transfer submitted to a CUDA stream.""" + + def __init__(self, cufile: ModuleType, writing: bool, *, empty: bool = False): + self._cufile = cufile + self._writing = writing + self._native = None if empty else _Transfer() + self._count = 0 if empty else None + self._observed = False + self._lock = threading.Lock() + + def _complete(self, *, wait: bool) -> int | None: + # Keep a local reference to release CUDA owners after unlocking. + if not self._lock.acquire(blocking=wait): + return None + try: + native = self._native + if native is not None: + count = native.complete(wait) + if count is not None: + self._count = count + self._native = None + return self._count + finally: + self._lock.release() + + @property + def is_done(self) -> bool: + """Whether the transfer has finished. Use `result()` for its status.""" + return self._complete(wait=False) is not None + + def result(self) -> int: + """Wait for this transfer and return the number of bytes transferred. + + A successful read may be short, including zero bytes at EOF. Raises + on a transfer error. Repeated calls return the same outcome. + """ + count: int = self._complete(wait=True) # type: ignore[assignment] + with self._lock: + self._observed = True + if count == -1: + operation = "write" if self._writing else "read" + raise OSError(f"cuFile asynchronous {operation} failed") + if count < 0: + raise self._cufile.cuFileError(-count) + return count + + +class _File: + """A binary file for positional device I/O, returned by `open_file()`.""" + + def __init__(self, cufile: ModuleType, mode: str): + self._fd: int | None = None + self._handle: int | None = None + self._cufile = cufile + self._readable = mode.startswith("r") or "+" in mode + self._writable = not mode.startswith("r") or "+" in mode + self._pending: OrderedDict[_Request, None] = OrderedDict() + self._pending_lock = threading.Lock() + self._count_pool: _CountPool | None = _CountPool() + self._unresolved_batch = False + + @property + def closed(self) -> bool: + """Whether this file has been closed.""" + return self._fd is None + + @property + def size(self) -> int: + """Current file size in bytes. Wait for pending writes to observe their size.""" + fd = self._fd + if fd is None: + raise ValueError("I/O on a closed cuFile file") + return os.fstat(fd).st_size + + def __enter__(self) -> _File: + if self.closed: + raise ValueError("I/O on a closed cuFile file") + return self + + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: + try: + self.close() + except Exception as cleanup: + if exc is None: + raise + exc.add_note(f"closing the cuFile file failed: {cleanup}") + + def __del__(self): + if self._fd is not None and not sys.is_finalizing(): + try: + self.close() + except Exception as exc: + warnings.warn(f"closing the cuFile file failed: {exc}", CUDAWarning, stacklevel=2) + + def close(self) -> None: + """Wait for outstanding I/O, deregister the file, and close its descriptor. + + Raises if an outstanding request failed and its error has not already + been retrieved. When completion cannot be established, keeps the file + open so the caller can retry. + """ + fd = self._fd + if fd is None: + return + if self._unresolved_batch: + raise RuntimeError("cuFile batch completion could not be established; the file is still retained") + for request in self._pending: + request._complete(wait=True) + self._cufile.handle_deregister(self._handle) + self._fd = None + self._handle = None + error = None + try: + os.close(fd) + except OSError as exc: + error = exc + for request in self._pending: + if request._count < 0 and not request._observed: # type: ignore[operator] + try: + request.result() + except Exception as exc: + if error is None: + error = exc + else: + error.add_note(str(exc)) + self._pending.clear() + self._count_pool = None + if error is not None: + raise error + + def _check_access(self, writing: bool) -> None: + if self.closed: + raise ValueError("I/O on a closed cuFile file") + if self._unresolved_batch: + raise RuntimeError("cuFile batch completion could not be established") + if not (self._writable if writing else self._readable): + raise OSError("cuFile file is not writable" if writing else "cuFile file is not readable") + + def _prepare(self, buffer: Buffer, offset: int, size: int | None, *, writing: bool) -> tuple[int, int]: + self._check_access(writing) + offset = operator.index(offset) + if not isinstance(buffer, Buffer): + raise TypeError("cuFile I/O requires a cuda.core.Buffer") + if buffer.is_closed: + raise RuntimeError("Buffer has been closed") + size = buffer.size if size is None else operator.index(size) + if size < 0 or size > buffer.size: + raise ValueError("size must be between zero and the GPU buffer size") + if offset < 0 or offset + size > _MAX_OFFSET: + raise ValueError("the file byte range must fit in a nonnegative signed 64-bit offset") + return offset, size + + def _transfer(self, buffer: Buffer, offset: int, size: int | None, *, writing: bool, stream: Stream) -> _Request: + offset, size = self._prepare(buffer, offset, size, writing=writing) + _validate_stream(stream) + if ( + size == 0 + and (buffer.size or buffer.handle) + and (not buffer.is_device_accessible or buffer.is_host_accessible) + ): + raise ValueError("cuFile I/O requires device-resident GPU memory") + request = _Request(self._cufile, writing, empty=size == 0) + native = request._native + if native is not None: + # Check one prior request per submission to bound the polling + # cost and give every stream a chance to retire completed I/O. + with self._pending_lock: + previous = next(iter(self._pending), None) + if previous is not None: + self._pending.move_to_end(previous) + if previous is not None: + count = previous._complete(wait=False) + if count is not None and (count >= 0 or previous._observed): + with self._pending_lock: + self._pending.pop(previous, None) + # Publish before submission in case the CUDA event or context + # restoration fails after cuFile has accepted the operation. + with request._lock: + with self._pending_lock: + self._pending[request] = None + native.submit( + self._cufile, + self._handle, # type: ignore[arg-type] + buffer, + size, + offset, + stream, + writing, + self._count_pool, # type: ignore[arg-type] + ) + return request + + def read_async(self, size: int | None = None, *, offset: int = 0, stream: Stream) -> tuple[Buffer, _Request]: + """Allocate a GPU buffer and enqueue a positional read on `stream`. + + The buffer has capacity `size` bytes, or the current file size minus + `offset` (at least zero) when `size` is omitted. Returns the buffer + and a request whose `result()` gives the valid byte count. The buffer + retains its full capacity after a short read. + """ + self._check_access(writing=False) + offset = operator.index(offset) + if not 0 <= offset <= _MAX_OFFSET: + raise ValueError("the file offset must fit in a nonnegative signed 64-bit offset") + size = max(0, self.size - offset) if size is None else operator.index(size) + if not 0 <= size <= _MAX_OFFSET - offset: + raise ValueError("invalid read size for the file offset") + buffer = _allocate(size, stream) + return buffer, self.readinto_async(buffer, offset=offset, stream=stream) + + def readinto_async(self, buffer: Buffer, *, offset: int = 0, stream: Stream, size: int | None = None) -> _Request: + """Queue a positional GPU read on `stream` and return its request. + + `size` defaults to the buffer's byte size. Subsequent CUDA work in + this stream runs after the transfer. Use the request's `result()` + to check for errors and get the number of valid bytes. + """ + return self._transfer(buffer, offset, size, writing=False, stream=stream) + + def write_async(self, buffer: Buffer, *, offset: int = 0, stream: Stream, size: int | None = None) -> _Request: + """Queue a positional GPU write on `stream` and return its request. + + `size` defaults to the buffer's byte size. Use the request's + `result()` to check for errors and get the number of bytes written. + """ + return self._transfer(buffer, offset, size, writing=True, stream=stream) + + def writeinto_async(self, buffer: Buffer, *, offset: int = 0, stream: Stream, size: int | None = None) -> _Request: + """Write the supplied GPU buffer into this file, as in `write_async()`.""" + return self.write_async(buffer, offset=offset, stream=stream, size=size) + + def read_batch(self, entries: Iterable[_FileEntry]) -> list[int]: + """Read a batch of `(buffer, offset[, size])` entries from this file. + + Waits for the batch and returns byte counts in input order. See + :func:`cuda.core.storage.read_batch` for ordering and error semantics. + """ + from ._batch import read_batch + + self._check_access(writing=False) + return read_batch((self, *entry) for entry in entries) + + def write_batch(self, entries: Iterable[_FileEntry]) -> list[int]: + """Write a batch of `(buffer, offset[, size])` entries into this file. + + Waits for the batch and returns byte counts in input order. See + :func:`cuda.core.storage.write_batch` for ordering and error semantics. + """ + from ._batch import write_batch + + self._check_access(writing=True) + return write_batch((self, *entry) for entry in entries) + + def streaming(self, stream: Stream | None) -> _StreamFile: + """Return a file-like view with an independent cursor at byte zero. + + Pass a CUDA stream or explicitly pass `None` to create one, as in + :func:`open`. Closing the view closes a stream it created and + leaves the backing file open. Closing the file invalidates the view. + """ + if self.closed: + raise ValueError("I/O on a closed cuFile file") + owns_stream = stream is None + if stream is None: + stream = _new_stream() + else: + _validate_stream(stream) + return _StreamFile(self, stream, owns_file=False, owns_stream=owns_stream) + + +class _StreamFile: + """A binary file-like object whose GPU I/O is ordered on one CUDA stream.""" + + def __init__(self, file: _File, stream: Stream, *, owns_file: bool, owns_stream: bool): + self._file = file + self._stream = stream + self._owns_file = owns_file + self._owns_stream = owns_stream + self._closed = False + self._position = 0 + + @property + def stream(self) -> Stream: + """The CUDA stream on which this object's I/O is submitted.""" + return self._stream + + @property + def closed(self) -> bool: + """Whether this object or its backing file has been closed.""" + return self._closed or self._file.closed + + def __enter__(self) -> _StreamFile: + self.tell() + return self + + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: + try: + self.close() + except Exception as cleanup: + if exc is None: + raise + exc.add_note(f"closing the streamed cuFile file failed: {cleanup}") + + def close(self) -> None: + """Close this view and any file or stream it owns.""" + try: + if self._owns_file: + self._file.close() + finally: + if not self._owns_file or self._file.closed: + self._closed = True + if self._owns_stream: + self._stream.close() + + def tell(self) -> int: + """Return the current byte offset.""" + if self.closed: + raise ValueError("I/O on a closed cuFile file") + return self._position + + def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: + """Move the cursor and return the new byte offset. + + `whence` can be `os.SEEK_SET`, `os.SEEK_CUR`, or `os.SEEK_END`. + Seeking beyond EOF is allowed. + """ + position = self.tell() + offset = operator.index(offset) + whence = operator.index(whence) + if whence == os.SEEK_CUR: + offset += position + elif whence == os.SEEK_END: + offset += self._file.size + elif whence != os.SEEK_SET: + raise ValueError("invalid whence") + if not 0 <= offset <= _MAX_OFFSET: + raise ValueError("the file position must fit in a nonnegative signed 64-bit offset") + self._position = offset + return offset + + def readinto(self, buffer: Buffer, size: int | None = None) -> int: + """Read into a GPU buffer at the cursor, then advance by bytes read. + + Enqueues the read on this object's stream and waits for it. Returns + the actual byte count, which can be less than `size` at EOF. + The default is the buffer's byte size. + """ + request = self._file.readinto_async(buffer, offset=self.tell(), stream=self._stream, size=size) + count = request.result() + self._position += count + return count + + def read(self, size: int = -1) -> Buffer: + """Read up to `size` bytes into a new GPU buffer and advance the cursor. + + A size of `-1` reads to the current EOF. The returned buffer's + byte size is the actual number read, including zero at EOF. + """ + size = operator.index(size) + buffer, request = self._file.read_async(None if size == -1 else size, offset=self.tell(), stream=self._stream) + count = request.result() + _resize_output(buffer, count) + self._position += count + return buffer + + def readuntil(self, end: int | None = None) -> Buffer: + """Read up to the exclusive byte offset `end` into a new GPU buffer. + + If `end` is omitted, use the current file size. The cursor advances + by the actual bytes read. When it is already at or beyond `end`, + return a zero-byte buffer. + """ + if end is None: + return self.read() + end = operator.index(end) + if not 0 <= end <= _MAX_OFFSET: + raise ValueError("end must fit in a nonnegative signed 64-bit offset") + return self.read(max(0, end - self.tell())) + + def write(self, buffer: Buffer, size: int | None = None) -> int: + """Write from a GPU buffer at the cursor and advance by bytes written. + + Enqueues the write on this object's stream and waits for it. The + default size is the buffer's byte size. Returns the actual byte count. + """ + request = self._file.write_async(buffer, offset=self.tell(), stream=self._stream, size=size) + count = request.result() + self._position += count + return count diff --git a/cuda_core/cuda/core/storage/_transfer.pyx b/cuda_core/cuda/core/storage/_transfer.pyx new file mode 100644 index 000000000000..cff6dd69b532 --- /dev/null +++ b/cuda_core/cuda/core/storage/_transfer.pyx @@ -0,0 +1,293 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +import os + +cimport cython +from cpython.ref cimport Py_DECREF, Py_INCREF +from libc.stdint cimport int64_t, intptr_t +from libcpp.vector cimport vector + +from cuda.bindings cimport cydriver +from cuda.core._context cimport Context +from cuda.core._event cimport Event +from cuda.core._memory._buffer cimport Buffer, Buffer_check_open, Buffer_from_deviceptr_handle +from cuda.core._rt cimport ( + ContextHandle, + DevicePtrHandle, + EventHandle, + MemoryPoolHandle, + StreamHandle, + as_cu, + attach_rollback_failure, + clear_last_error_detail, + context_get_device, + create_event_handle, + deviceptr_alloc_from_pool, + deviceptr_alloc_host, + enter_context, + exit_context, + get_current_context, + get_device_mempool, + get_last_error, + get_primary_context, +) +from cuda.core._stream cimport Stream, Stream_check_open, Stream_is_default_token +from cuda.core._utils.cuda_utils cimport HANDLE_RETURN + + +def _new_stream(): + from cuda.core import Device + + Device(0) # Initialize the driver without changing the current context. + cdef ContextHandle context + cdef cydriver.CUdevice device + with nogil: + context = get_current_context() + if not context: + HANDLE_RETURN(get_last_error()) + context = get_primary_context(0) + if not context: + HANDLE_RETURN(get_last_error()) + HANDLE_RETURN(context_get_device(context, &device)) + return Stream._init(ctx=Context._from_handle(Context, context, device), device_id=device) + + +cdef class _BatchOwners: + cdef vector[DevicePtrHandle] _buffers + cdef object _owners + + def __init__(self, entries, params, events): + cdef Buffer buffer + self._owners = entries, params, events + for entry in entries: + buffer = entry[1] + self._buffers.push_back(buffer._h_ptr) + + def abandon(self): + # Completion and destruction both failed. Preserve the live native pointers. + Py_INCREF(self) + + +def _validate_stream(Stream stream not None): + Stream_check_open(stream) + # Default stream tokens cannot identify the same queue from every thread. + if Stream_is_default_token(stream): + raise ValueError("cuFile requires an explicit CUDA stream") + + +cdef void _check_capture(cydriver.CUstream stream) except *: + cdef cydriver.CUstreamCaptureStatus status + with nogil: + HANDLE_RETURN(cydriver.cuStreamIsCapturing(stream, &status)) + if status != cydriver.CUstreamCaptureStatus.CU_STREAM_CAPTURE_STATUS_NONE: + raise RuntimeError("cuFile I/O is unavailable during CUDA stream capture") + + +def _allocate(size_t size, Stream stream not None): + _validate_stream(stream) + _check_capture(as_cu(stream._h_stream)) + cdef MemoryPoolHandle pool + cdef DevicePtrHandle allocation + cdef Context context = stream.context + with nogil: + pool = get_device_mempool(context._device_id) + if not pool: + HANDLE_RETURN(get_last_error()) + if not pool: + raise RuntimeError("internal cuda.core error, please report: missing device memory pool") + with nogil: + allocation = deviceptr_alloc_from_pool(size, pool, stream._h_stream) + if not allocation: + HANDLE_RETURN(get_last_error()) + raise RuntimeError("internal cuda.core error, please report: missing allocation handle") + return Buffer_from_deviceptr_handle(allocation, size, None) + + +def _resize_output(Buffer buffer not None, size_t size): + # This buffer was freshly allocated by the reader and has never been published. + buffer._size = size + + +cdef class _CountSlab: + """One pinned allocation shared by transfers in the same CUDA context.""" + + # Keep the native context alive while its handle is used as a cache key. + cdef ContextHandle _context + cdef DevicePtrHandle _allocation + cdef Py_ssize_t* _slots + cdef Py_ssize_t _capacity, _used, _free + cdef cython.pymutex _lock + + def __cinit__(self, Context context): + cdef size_t size + setting = "CUDA_PYTHON_CUFILE_PINNED_SLAB_SIZE" + value = int(os.environ.get(setting, 512 * 1024)) + if value < sizeof(Py_ssize_t): + raise ValueError(f"{setting} must be at least {sizeof(Py_ssize_t)} bytes") + size = value + self._context = context._h_context + with nogil: + self._allocation = deviceptr_alloc_host(size) + if not self._allocation: + HANDLE_RETURN(get_last_error()) + if not self._allocation: + raise RuntimeError("internal cuda.core error, please report: missing cuFile count slab") + self._slots = as_cu(self._allocation) + self._capacity = size // sizeof(Py_ssize_t) + self._free = -1 + + cdef Py_ssize_t* acquire(self) noexcept: + cdef Py_ssize_t index + with self._lock: + if self._free >= 0: + index = self._free + self._free = self._slots[index] + elif self._used < self._capacity: + index = self._used + self._used += 1 + else: + return NULL + return &self._slots[index] + + cdef void release(self, Py_ssize_t* slot) noexcept: + # Use the idle slots themselves to store the freelist indices. + with self._lock: + slot[0] = self._free + self._free = slot - self._slots + + +cdef class _CountPool: + """Cache at most one slab per context for an open file.""" + + cdef dict _slabs + + def __cinit__(self): + self._slabs = {} + + cdef _CountSlab slab(self, Context context): + key = as_cu(context._h_context) + slab = self._slabs.get(key) + if slab is None: + slab = self._slabs.setdefault(key, _CountSlab(context)) + return slab + + +cdef class _Transfer: + """Native arguments and allocation owners for a single cuFile operation.""" + + cdef DevicePtrHandle _buffer, _pinned_count + cdef StreamHandle _stream + cdef Event _event + cdef _CountSlab _count_slab + cdef size_t _size + # libcufile runs on 64-bit Linux, where off_t is signed 64-bit. + cdef int64_t _file_offset, _buffer_offset + cdef Py_ssize_t* _count + cdef bint _submitted + + def submit(self, cufile, intptr_t file, Buffer buffer not None, + size_t size, int64_t offset, Stream stream not None, bint writing, + _CountPool count_pool not None): + _validate_stream(stream) + Buffer_check_open(buffer) + cdef Context stream_context = stream.context + self._buffer = buffer._h_ptr + self._stream = stream._h_stream + self._size = size + self._file_offset = offset + cdef ContextHandle context = stream_context._h_context + cdef cydriver.CUstream raw_stream = as_cu(self._stream) + cdef cydriver.CUcontext previous + cdef int changed + cdef EventHandle event + cdef cydriver.CUresult restore + cdef _CountSlab slab + _check_capture(raw_stream) + + with nogil: + HANDLE_RETURN(enter_context(context, &previous, &changed)) + try: + if not buffer.is_device_accessible or buffer.is_host_accessible: + raise ValueError("cuFile I/O requires device-resident GPU memory") + if buffer.device_id != stream_context._device_id: + raise ValueError("buffer and cuFile stream must be on the same CUDA device") + with nogil: + event = create_event_handle( + context, + cydriver.CUevent_flags.CU_EVENT_DISABLE_TIMING | cydriver.CUevent_flags.CU_EVENT_BLOCKING_SYNC, + False, True, False, stream_context._device_id) + if not event: + HANDLE_RETURN(get_last_error()) + if not event: + raise RuntimeError("internal cuda.core error, please report: missing cuFile transfer event") + slab = count_pool.slab(stream_context) + self._count = slab.acquire() + if self._count == NULL: + # Keep cached pinned memory bounded at high queue depths. + with nogil: + self._pinned_count = deviceptr_alloc_host(sizeof(Py_ssize_t)) + if not self._pinned_count: + HANDLE_RETURN(get_last_error()) + if not self._pinned_count: + raise RuntimeError("internal cuda.core error, please report: missing cuFile transfer count") + self._count = as_cu(self._pinned_count) + else: + self._count_slab = slab + self._count[0] = 0 + completion = Event._from_handle(event) + + # Publish ownership before submission. If recording the event or + # restoring the context fails, close can still wait for the I/O. + submit = cufile.write_async if writing else cufile.read_async + submission_error = cufile.cuFileError + Py_INCREF(self) + self._submitted = True + try: + submit(file, as_cu(self._buffer), &self._size, + &self._file_offset, &self._buffer_offset, + self._count, raw_stream) + except submission_error: + self._submitted = False + Py_DECREF(self) + raise + with nogil: + HANDLE_RETURN(cydriver.cuEventRecord(as_cu(event), raw_stream)) + self._event = completion + except: + if not self._submitted: + self._release_count() + with nogil: + restore = exit_context(previous, changed, cydriver.CUresult.CUDA_SUCCESS) + if restore != cydriver.CUresult.CUDA_SUCCESS: + clear_last_error_detail() + attach_rollback_failure(b"cuCtxSetCurrent", restore, b"restoring the caller's context") + raise + with nogil: + HANDLE_RETURN(exit_context(previous, changed, cydriver.CUresult.CUDA_SUCCESS)) + + cdef void _release_count(self) noexcept: + if self._count_slab is not None: + self._count_slab.release(self._count) + self._count = NULL + + def complete(self, bint wait): + """Return the signed byte count, or None while pending.""" + if not self._submitted: + return 0 + if self._event is None: + if not wait: + return None + with nogil: + HANDLE_RETURN(cydriver.cuStreamSynchronize(as_cu(self._stream))) + elif wait: + self._event.sync() + elif not self._event.is_done: + return None + + cdef object count = self._count[0] + self._submitted = False + self._release_count() + Py_DECREF(self) + return count diff --git a/cuda_core/docs/source/api.rst b/cuda_core/docs/source/api.rst index bfc9bf042f23..e1f242a6f5b9 100644 --- a/cuda_core/docs/source/api.rst +++ b/cuda_core/docs/source/api.rst @@ -104,6 +104,15 @@ using events or other CUDA synchronization mechanisms as needed. See for a complete example. +GPU file I/O +------------ + +.. toctree:: + :maxdepth: 1 + + storage + + CUDA compilation toolchain -------------------------- diff --git a/cuda_core/docs/source/api_private.rst b/cuda_core/docs/source/api_private.rst index 9a061a9dde37..5ce9775216cf 100644 --- a/cuda_core/docs/source/api_private.rst +++ b/cuda_core/docs/source/api_private.rst @@ -72,6 +72,16 @@ CUDA protocols typing.IsStreamType +GPU file I/O +------------ + +.. autosummary:: + :toctree: generated/ + + storage._file._File + storage._file._StreamFile + storage._file._Request + NVML ---- diff --git a/cuda_core/docs/source/storage.rst b/cuda_core/docs/source/storage.rst new file mode 100644 index 000000000000..3c342b7d8bb7 --- /dev/null +++ b/cuda_core/docs/source/storage.rst @@ -0,0 +1,142 @@ +.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +.. SPDX-License-Identifier: Apache-2.0 + +GPU file I/O +============ + +.. currentmodule:: cuda.core.storage + +:func:`open_file` and :func:`open` transfer bytes between a regular filesystem +file and device memory through NVIDIA cuFile. They accept binary modes and device-resident +:class:`~cuda.core.Buffer` objects. The cuFile runtime is required on Linux. +cuFile can stage data through host memory internally, depending on its +configuration, the filesystem, and the hardware. Pass ``direct=True`` to +request opening the file with ``O_DIRECT``. + +Direct GPU transfers +-------------------- + +``direct=True`` requests direct filesystem I/O. The path between storage +and GPU memory also depends on whether cuFile can use peer-to-peer DMA for +that GPU, controller, filesystem mount, and operation. A successful transfer +can still have used host staging. + +For local NVMe on Linux, NVIDIA documents direct support for ext4 and XFS. +Use ext4 with ordered journaling. The host also needs a supported GDS driver +path, such as NVMe PCI P2PDMA with a compatible Linux kernel and NVIDIA open +driver, or a supported ``nvidia-fs`` setup. For an initial test, use an aligned +GPU buffer, file offset, and transfer size, all on 4 KiB boundaries. Test +writes over an existing allocated range because extending a file or writing +into a hole can change the available I/O path. + +Run ``gdscheck -p`` to see the available paths, and use cuFile statistics for +the actual workload to distinguish GDS operations from POSIX fallback. See +NVIDIA's `NVMe P2PDMA setup guide +`_ +and `cuFile statistics documentation +`_. + +Positional transfers +-------------------- + +Use :func:`open_file` for independent transfers at explicit byte offsets. +The file's ``size`` attribute reports its current size in bytes. Wait for +any pending writes before relying on their effect on the size. + +.. code-block:: python + + from cuda.core.storage import open_file + + with open_file("frames.bin", "rb") as file: + frame_a, first = file.read_async(4096, offset=4096, stream=stream) + second = file.readinto_async(frame_b, offset=8192, stream=stream) + count_a = first.result() + count_b = second.result() + +``read_async`` returns a new buffer and its request. The buffer has the requested +capacity, or the file size minus the offset if no size was supplied. After a +short read, only the prefix identified by the request's byte count contains new +data. ``readinto_async`` reads into an existing buffer. ``write_async`` and +``writeinto_async`` both write from a supplied GPU buffer. Operations on existing +buffers default to the full buffer size. Pass ``size=`` to transfer a prefix. + +An asynchronous transfer is ordered with CUDA work submitted before and after +it on the same explicit stream. Use CUDA events to establish dependencies +between streams. Calling ``request.result()`` waits for the transfer and +reports its byte count or error. A later CUDA operation on the same stream +can access the buffer once the transfer completes. The caller must account for +short reads and transfer errors before using data that depends on the result. + +The open file retains pending transfers, including when the Python request is +discarded. Close the file to wait for outstanding transfers and release its +descriptor. Keep externally owned allocations valid through completion. +Stream I/O requires cuFile stream support and an explicit +:class:`~cuda.core.Stream` created for the buffer's device. Default stream +tokens and stream capture are unsupported. + +The first nonempty stream transfer on an open file and CUDA context allocates +a pinned host slab for transfer byte counts. Set +``CUDA_PYTHON_CUFILE_PINNED_SLAB_SIZE`` to change its size in bytes from the +default of 512 KiB. Each in-flight transfer uses one slot. If all slots are +in use, additional transfers allocate their own count storage. + +Batch transfers +--------------- + +Use ``file.read_batch()`` or ``file.write_batch()`` for several ranges of one +file. The top-level :func:`read_batch` and :func:`write_batch` accept paths +and open files in the same native cuFile batch. The functions close the files +they open for paths. Writing to a path creates a missing file and preserves +existing bytes outside the written ranges. + +.. code-block:: python + + from cuda.core.storage import open_file, read_batch + + with open_file("a.bin") as a: + counts = read_batch([(a, header, 0), ("b.bin", frame, 8192, 4096)]) + counts = a.read_batch([(header, 0), (frame, 4096)]) + +Batch calls wait on the host and return byte counts in input order. Operations +within a batch can run in any order. Synchronize earlier CUDA work on any +affected buffers before submitting a batch. The active cuFile configuration +determines the maximum number of nonempty entries in a batch. + +Stream-bound files +------------------ + +Bind a stream when opening the file to get a file-like object with a byte +cursor. Each read or write submits the transfer to that stream, waits for its +result, and advances the cursor by the actual byte count. + +.. code-block:: python + + from cuda.core import storage + + with storage.open("frames.bin", stream=None) as reader: + header = reader.read(4096) + first_frame = reader.readuntil(8192) + remaining = reader.read() + +Both ``read()`` and ``readuntil()`` allocate and return a GPU buffer. An +omitted limit reads up to the current file size. The limit for ``read(size)`` +is a byte count. The limit for ``readuntil(end)`` is an exclusive file offset. +The returned buffer's size is the actual number of bytes read. Use +``readinto(buffer)`` to reuse a buffer or ``write(buffer)`` to write its bytes. +The cursor supports ``seek()`` and ``tell()``. + +Both ``storage.open()`` and ``file.streaming()`` require an explicit stream +argument. Pass ``None`` to create an owned CUDA stream on the current context, +or on device 0's primary context when none is current. Closing a file from +``storage.open()`` also closes its backing file. Each ``file.streaming()`` +view starts at byte zero and borrows the already-open file. Closing the +backing file invalidates all its views. The caller must coordinate cursor +mutations and closing a file with other operations on it. + +API reference +------------- + +.. autofunction:: open_file +.. autofunction:: open +.. autofunction:: read_batch +.. autofunction:: write_batch diff --git a/cuda_core/tests/test_storage.py b/cuda_core/tests/test_storage.py new file mode 100644 index 000000000000..ba693d00d87d --- /dev/null +++ b/cuda_core/tests/test_storage.py @@ -0,0 +1,383 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +import ctypes +import os +import sys +from contextlib import ExitStack +from types import SimpleNamespace + +import pytest + +from cuda import bindings +from cuda.bindings import driver +from cuda.core import Device, storage +from cuda.core.storage import _file, open_file + +pytestmark = [ + pytest.mark.skipif(sys.platform != "linux", reason="cuFile requires Linux"), + pytest.mark.thread_unsafe(reason="mock storage tests patch module-level CUDA bindings"), +] + + +@pytest.fixture +def fake_cufile(monkeypatch): + """Use ordinary file descriptors to exercise the Python file and cursor contract.""" + + class FakeBuffer: + is_closed = False + is_device_accessible = True + is_host_accessible = False + + def __init__(self, size): + self.size = size + self.handle = bytearray(size) + + def read(fd, dst, size, offset, _): + data = os.pread(fd, size, offset) + dst[: len(data)] = data + return len(data) + + def write(fd, src, size, offset, _): + return os.pwrite(fd, src[:size], offset) + + class Transfer: + def submit(self, cufile, fd, buffer, size, offset, stream, writing, count_pool): + if buffer.is_host_accessible: + raise ValueError("cuFile I/O requires device-resident GPU memory") + io = cufile.write if writing else cufile.read + self.count = io(fd, buffer.handle, size, offset, 0) + + def complete(self, wait): + return getattr(self, "count", 0) if wait else None + + def descriptor(): + desc = SimpleNamespace(handle=SimpleNamespace()) + desc.ptr = desc + return desc + + backend = SimpleNamespace( + get_version=lambda: 1090, + Descr=descriptor, + FileHandleType=SimpleNamespace(OPAQUE_FD=1), + handle_register=lambda desc: desc.handle.fd, + handle_deregister=lambda _handle: None, + read=read, + write=write, + ) + monkeypatch.setattr(bindings, "cufile", backend, raising=False) + monkeypatch.setattr(_file, "Buffer", FakeBuffer) + monkeypatch.setattr(_file, "_Transfer", Transfer) + monkeypatch.setattr(_file, "_validate_stream", lambda _stream: None) + monkeypatch.setattr(_file, "_allocate", lambda size, _stream: FakeBuffer(size)) + monkeypatch.setattr(_file, "_resize_output", lambda buffer, size: setattr(buffer, "size", size)) + return backend, FakeBuffer + + +def test_cursor_reads_and_independent_views(fake_cufile, tmp_path): + path = tmp_path / "data.bin" + path.write_bytes(b"012345") + stream = object() + with storage.open(path, stream=stream) as reader: + backing_file = reader._file + assert reader.stream is stream + assert reader.read(2).handle == b"01" + assert reader.readuntil(4).handle == b"23" + tail = reader.read(8) + assert tail.size == 2 + assert tail.handle[: tail.size] == b"45" + assert reader.tell() == 6 + assert reader.readuntil().size == 0 + assert reader.seek(-3, os.SEEK_END) == 3 + assert reader.read().handle == b"345" + assert reader.closed + assert backing_file.closed + + with open_file(path) as file: + with file.streaming(stream) as first, file.streaming(stream) as second: + first.read(3) + assert second.tell() == 0 + assert first.closed + assert not file.closed + + +def test_positional_operations_and_close(fake_cufile, tmp_path): + _, Buffer = fake_cufile + path = tmp_path / "data.bin" + src = Buffer(4) + src.handle[:] = b"cuda" + stream = object() + with open_file(path, "w+b") as file: + assert file.write_async(src, stream=stream).result() == 4 + request = file.writeinto_async(src, offset=4, stream=stream, size=2) + assert not request.is_done + assert file.size == 6 + dst = Buffer(4) + assert file.readinto_async(dst, offset=3, stream=stream).result() == 3 + assert dst.handle[:3] == b"acu" + allocated, suffix = file.read_async(offset=3, stream=stream) + assert allocated.size == suffix.result() == 3 + oversized, short = file.read_async(8, offset=3, stream=stream) + assert oversized.size == 8 + assert short.result() == 3 + empty, eof = file.read_async(offset=9, stream=stream) + assert empty.size == eof.result() == 0 + with pytest.raises(ValueError, match="buffer size"): + file.readinto_async(dst, stream=stream, size=5) + with pytest.raises(TypeError, match="cuda.core.Buffer"): + file.readinto_async(bytearray(4), stream=stream) + with pytest.raises(ValueError, match="device-resident"): + dst.is_host_accessible = True + file.readinto_async(dst, stream=stream) + assert request.is_done + assert request.result() == 2 + assert path.read_bytes() == b"cudacu" + + +def test_registration_failure_preserves_existing_file(fake_cufile, monkeypatch, tmp_path): + backend, _ = fake_cufile + path = tmp_path / "data.bin" + path.write_bytes(b"keep") + seen = [] + + def fail_registration(desc): + seen.append(desc.handle.fd) + raise OSError("registration failed") + + monkeypatch.setattr(backend, "handle_register", fail_registration) + with pytest.raises(OSError, match="registration failed"): + open_file(path, "wb") + assert path.read_bytes() == b"keep" + with pytest.raises(OSError): + os.fstat(seen[0]) + + +def test_binary_modes(fake_cufile, tmp_path): + with pytest.raises(ValueError, match="binary mode"): + open_file(tmp_path / "data", "r") + + +def test_owned_stream_is_explicit(fake_cufile, monkeypatch, tmp_path): + closed_streams = [] + monkeypatch.setattr(_file, "_new_stream", lambda: SimpleNamespace(close=lambda: closed_streams.append(1))) + path = tmp_path / "data" + path.touch() + with pytest.raises(TypeError, match="stream"): + storage.open(path) + with open_file(path) as file: + with pytest.raises(TypeError, match="stream"): + file.streaming() + with file.streaming(None): + assert not closed_streams + assert closed_streams == [1] + assert not file.closed + with storage.open(path, stream=None): + assert closed_streams == [1] + assert closed_streams == [1, 1] + + +def test_close_waits_after_submission_error(fake_cufile, monkeypatch, tmp_path): + backend, Buffer = fake_cufile + steps = [] + + class Transfer: + def submit(self, *args): + steps.append("submitted") + raise RuntimeError("event record failed") + + def complete(self, wait): + assert wait + steps.append("completed") + return 4 + + monkeypatch.setattr(_file, "_Transfer", Transfer) + monkeypatch.setattr(backend, "handle_deregister", lambda _handle: steps.append("deregistered")) + with open_file(tmp_path / "data", "wb") as file, pytest.raises(RuntimeError, match="event record failed"): + file.write_async(Buffer(4), offset=0, stream=object()) + assert steps == ["submitted", "completed", "deregistered"] + + +@pytest.fixture +def cufile_device(tmp_path): + from cuda.pathfinder import DynamicLibNotFoundError + + try: + if driver.cuInit(0)[0] != driver.CUresult.CUDA_SUCCESS: + pytest.skip("CUDA driver is unavailable") + except DynamicLibNotFoundError as exc: + pytest.skip(str(exc)) + cufile = pytest.importorskip("cuda.bindings.cufile") + try: + cufile.get_version() + except DynamicLibNotFoundError as exc: + pytest.skip(str(exc)) + + device = Device() + device.set_current() + try: + with open_file(tmp_path / "probe.bin", "w+b"): + pass + except cufile.cuFileError as exc: + if exc.status in ( + cufile.OpError.IO_NOT_SUPPORTED, + cufile.OpError.PLATFORM_NOT_SUPPORTED, + cufile.OpError.DRIVER_NOT_INITIALIZED, + ): + pytest.skip(str(exc)) + raise + return device + + +def test_stream_ordered_cufile(tmp_path, cufile_device): + device = cufile_device + stream = device.create_stream() + path = tmp_path / "data.bin" + other = tmp_path / "other.bin" + with open_file(path, "w+b") as file, device.allocate(4096, stream=stream) as src: + src.fill(ord("a"), stream=stream) + first = file.write_async(src, offset=0, stream=stream) + src.fill(ord("b"), stream=stream) + second = file.write_async(src, offset=4096, stream=stream) + assert first.result() == second.result() == 4096 + with file.streaming(stream) as reader: + with reader.readuntil() as data, storage.open(other, "wb", stream=stream) as writer: + assert writer.write(data) == 8192 + with reader.read() as eof: + assert eof.size == 0 + stream.sync() + assert other.read_bytes() == b"a" * 4096 + b"b" * 4096 + + with storage.open(path, stream=None) as reader, reader.read(4096) as first_block: + owned_stream = reader.stream + assert first_block.size == 4096 + assert owned_stream.is_closed + assert not stream.is_closed + + +def test_cufile_batch_across_files(tmp_path, cufile_device): + device = cufile_device + stream = device.create_stream() + first_path = tmp_path / "first.bin" + second_path = tmp_path / "second.bin" + with ExitStack() as stack: + first = stack.enter_context(open_file(first_path, "w+b")) + second = stack.enter_context(open_file(second_path, "w+b")) + src = stack.enter_context(device.allocate(4096, stream=stream)) + a = stack.enter_context(device.allocate(4096, stream=stream)) + b = stack.enter_context(device.allocate(4096, stream=stream)) + src.fill(ord("x"), stream=stream) + stream.sync() + assert storage.write_batch([(first, src, 0), (second, src, 4096)]) == [4096, 4096] + assert storage.read_batch([(second, b, 4096), (first, a, 0, 0), (first, a, 0)]) == [4096, 0, 4096] + assert first.write_batch([(b, 4096), (a, 8192)]) == [4096, 4096] + assert first.read_batch([(a, 8192), (b, 4096)]) == [4096, 4096] + assert first_path.read_bytes() == b"x" * 12288 + assert second_path.read_bytes() == b"\0" * 4096 + b"x" * 4096 + + +def test_transfer_count_slots_reuse_and_overflow(cufile_device, monkeypatch): + from cuda.core.storage._transfer import _CountPool, _Transfer + + count_type = ctypes.c_ssize_t + slot_size = ctypes.sizeof(count_type) + monkeypatch.setenv("CUDA_PYTHON_CUFILE_PINNED_SLAB_SIZE", str(2 * slot_size)) + pool = _CountPool() + addresses = [] + + def submit_read(_file, _buffer, _size, _offset, _buffer_offset, count, _stream): + assert count_type.from_address(count).value == 0 + addresses.append(count) + count_type.from_address(count).value = len(addresses) + + fake = SimpleNamespace(read_async=submit_read, cuFileError=OSError) + device = cufile_device + stream = device.create_stream() + try: + with device.allocate(4096, stream=stream) as buffer: + first, second, overflow, reused = (_Transfer() for _ in range(4)) + for transfer in (first, second, overflow): + transfer.submit(fake, 0, buffer, 4096, 0, stream, False, pool) + assert addresses[1] == addresses[0] + slot_size + assert len(set(addresses)) == 3 + assert first.complete(True) == 1 + reused.submit(fake, 0, buffer, 4096, 0, stream, False, pool) + assert addresses[3] == addresses[0] + assert second.complete(True) == 2 + assert overflow.complete(True) == 3 + assert reused.complete(True) == 4 + finally: + stream.close() + + +@pytest.mark.parametrize("accepted", [False, True]) +def test_transfer_count_slot_after_submission_error(cufile_device, monkeypatch, accepted): + from cuda.core.storage._transfer import _CountPool, _Transfer + + count_type = ctypes.c_ssize_t + monkeypatch.setenv("CUDA_PYTHON_CUFILE_PINNED_SLAB_SIZE", str(ctypes.sizeof(count_type))) + pool = _CountPool() + addresses = [] + error_type = RuntimeError if accepted else OSError + + def submit_read(_file, _buffer, _size, _offset, _buffer_offset, count, _stream): + addresses.append(count) + if len(addresses) == 1: + if accepted: + count_type.from_address(count).value = 1 + raise error_type("submission failed") + count_type.from_address(count).value = 2 + + fake = SimpleNamespace(read_async=submit_read, cuFileError=OSError) + device = cufile_device + stream = device.create_stream() + try: + with device.allocate(4096, stream=stream) as buffer: + first, second = _Transfer(), _Transfer() + with pytest.raises(error_type, match="submission failed"): + first.submit(fake, 0, buffer, 4096, 0, stream, False, pool) + second.submit(fake, 0, buffer, 4096, 0, stream, False, pool) + assert first.complete(True) == int(accepted) + assert second.complete(True) == 2 + assert (addresses[0] != addresses[1]) == accepted + finally: + stream.close() + + +def test_batch_path_handles_close_on_validation_error(fake_cufile, monkeypatch, tmp_path): + backend, Buffer = fake_cufile + opened, closed = [], [] + first_path = tmp_path / "first.bin" + first_path.touch() + path = tmp_path / "owned.bin" + path.touch() + + def register(desc): + opened.append(desc.handle.fd) + return desc.handle.fd + + monkeypatch.setattr(backend, "handle_register", register) + monkeypatch.setattr(backend, "handle_deregister", closed.append) + with open_file(first_path) as file: + with pytest.raises(ValueError, match="file byte range"): + storage.read_batch([(file, Buffer(0), 0), (path, Buffer(0), 0), (os.fsencode(path), Buffer(0), -1)]) + assert len(opened) == 2 + assert closed == opened[1:] + assert not file.closed + assert closed == opened[::-1] + + +def test_cufile_batch_paths_preserve_existing_data(tmp_path, cufile_device): + device = cufile_device + stream = device.create_stream() + existing = tmp_path / "existing.bin" + missing = tmp_path / "new.bin" + existing.write_bytes(b"a" * 12288) + with open_file(existing, "rb") as file, device.allocate(4096, stream=stream) as data: + data.fill(ord("b"), stream=stream) + stream.sync() + assert storage.write_batch([(existing, data, 4096), (str(missing), data, 0)]) == [4096, 4096] + assert storage.read_batch([(os.fsencode(missing), data, 0), (file, data, 0, 0)]) == [4096, 0] + assert not file.closed + assert existing.read_bytes() == b"a" * 4096 + b"b" * 4096 + b"a" * 4096 + assert missing.read_bytes() == b"b" * 4096 From bd45ae802ec1593cfd102f8282a72eec9fb9bbd0 Mon Sep 17 00:00:00 2001 From: Martin Durant Date: Wed, 2 Dec 2026 10:35:39 -0500 Subject: [PATCH 2/2] Suggested API changes --- cuda_core/cuda/core/_device.pyi | 12 + cuda_core/cuda/core/_device.pyx | 20 ++ cuda_core/cuda/core/storage/_batch.py | 13 +- cuda_core/cuda/core/storage/_file.py | 283 +++++++++++++++------- cuda_core/cuda/core/storage/_transfer.pyi | 35 +++ cuda_core/cuda/core/storage/_transfer.pyx | 70 ++++-- cuda_core/docs/source/storage.rst | 74 ++++-- cuda_core/tests/test_storage.py | 178 ++++++++++---- 8 files changed, 507 insertions(+), 178 deletions(-) create mode 100644 cuda_core/cuda/core/storage/_transfer.pyi diff --git a/cuda_core/cuda/core/_device.pyi b/cuda_core/cuda/core/_device.pyi index cf8e1e186671..246ace3993da 100644 --- a/cuda_core/cuda/core/_device.pyi +++ b/cuda_core/cuda/core/_device.pyi @@ -10,6 +10,7 @@ from cuda.core._memory._buffer import Buffer, MemoryResource from cuda.core._stream import IsStreamType, Stream, StreamOptions from cuda.core._utils.cuda_utils import ComputeCapability from cuda.core.graph import GraphBuilder +from cuda.core.storage._file import _File, _Path, _StreamFile from cuda.core.texture import (MipmappedArray, MipmappedArrayOptions, OpaqueArray, OpaqueArrayOptions, ResourceDescriptor, SurfaceObject, @@ -689,6 +690,17 @@ class Device: :obj:`~_stream.Stream` Newly created stream object. + """ + def open_file(self, path: _Path, mode: str='rb', *, direct: bool=False) -> _File: + """Open a binary file for positional GPU I/O on this device. + + See :func:`cuda.core.storage.open_file` for the mode and direct I/O options. + """ + def open(self, path: _Path, mode: str='rb', *, stream: Stream | None=None, direct: bool=False) -> _StreamFile: + """Open a binary GPU file with a byte cursor on this device. + + Pass a stream to set the default for asynchronous methods. + See :func:`cuda.core.storage.open` for the file options. """ def create_event(self, options: EventOptions | None=None) -> Event: """Create an :obj:`~_event.Event` on this device without recording it to a :obj:`~_stream.Stream`. diff --git a/cuda_core/cuda/core/_device.pyx b/cuda_core/cuda/core/_device.pyx index 5ce22959e985..a59da82a2369 100644 --- a/cuda_core/cuda/core/_device.pyx +++ b/cuda_core/cuda/core/_device.pyx @@ -46,6 +46,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: import cuda.core.system # no-cython-lint from cuda.core.graph import GraphBuilder + from cuda.core.storage._file import _File, _Path, _StreamFile from cuda.core.texture import ( MipmappedArray, MipmappedArrayOptions, @@ -1432,6 +1433,25 @@ class Device: self._check_context_initialized() return Stream._init(obj=obj, options=options, device_id=self._device_id, ctx=self._context) + def open_file(self, path: _Path, mode: str = "rb", *, direct: bool = False) -> _File: + """Open a binary file for positional GPU I/O on this device. + + See :func:`cuda.core.storage.open_file` for the mode and direct I/O options. + """ + from cuda.core.storage import open_file + + return open_file(path, mode, device=self, direct=direct) + + def open(self, path: _Path, mode: str = "rb", *, stream: Stream | None = None, direct: bool = False) -> _StreamFile: + """Open a binary GPU file with a byte cursor on this device. + + Pass a stream to set the default for asynchronous methods. + See :func:`cuda.core.storage.open` for the file options. + """ + from cuda.core.storage import open as open_gpu_file + + return open_gpu_file(path, mode, device=self, stream=stream, direct=direct) + def create_event(self, options: EventOptions | None = None) -> Event: """Create an :obj:`~_event.Event` on this device without recording it to a :obj:`~_stream.Stream`. diff --git a/cuda_core/cuda/core/storage/_batch.py b/cuda_core/cuda/core/storage/_batch.py index 2624e1f45082..b400b30e264c 100644 --- a/cuda_core/cuda/core/storage/_batch.py +++ b/cuda_core/cuda/core/storage/_batch.py @@ -7,10 +7,11 @@ from contextlib import ExitStack from ctypes import addressof, c_ssize_t, c_uint +from cuda.core._context import Context from cuda.core._memory._buffer import Buffer from ._file import _File, _open_file, _Path -from ._transfer import _BatchOwners +from ._transfer import _BatchOwners, _call_in_context _FileOrPath = _File | _Path _Entry = tuple[_FileOrPath, Buffer, int] | tuple[_FileOrPath, Buffer, int, int | None] @@ -46,7 +47,7 @@ def write_batch(entries: Iterable[_Entry]) -> list[int]: return _batch(entries, writing=True) -def _batch(entries: Iterable[_Entry], *, writing: bool) -> list[int]: +def _batch(entries: Iterable[_Entry], *, writing: bool, context: Context | None = None) -> list[int]: with ExitStack() as files: opened: dict[bytes, _File] = {} counts: list[int] = [] @@ -68,14 +69,18 @@ def _batch(entries: Iterable[_Entry], *, writing: bool) -> list[int]: if (buffer.size or buffer.handle) and (not buffer.is_device_accessible or buffer.is_host_accessible): raise ValueError("cuFile I/O requires device-resident GPU memory") if size: + file._check_buffer_device(buffer) active.append((file, buffer, offset, size, len(counts))) counts.append(0) if active: - _submit_batch(active, counts, writing=writing) + if context is None: + _submit_batch(active, counts, writing) + else: + _call_in_context(context, _submit_batch, active, counts, writing) return counts -def _submit_batch(active: list[tuple[_File, Buffer, int, int, int]], counts: list[int], *, writing: bool) -> None: +def _submit_batch(active: list[tuple[_File, Buffer, int, int, int]], counts: list[int], writing: bool) -> None: cufile = active[0][0]._cufile count = len(active) params = cufile.IOParams(count) diff --git a/cuda_core/cuda/core/storage/_file.py b/cuda_core/cuda/core/storage/_file.py index a013f5336b4e..039e0471adf9 100644 --- a/cuda_core/cuda/core/storage/_file.py +++ b/cuda_core/cuda/core/storage/_file.py @@ -14,10 +14,20 @@ from collections.abc import Iterable from types import ModuleType, TracebackType -from cuda.core import CUDAWarning, Stream +from cuda.core import CUDAWarning, Device, Stream +from cuda.core._context import Context from cuda.core._memory._buffer import Buffer -from ._transfer import _allocate, _CountPool, _new_stream, _resize_output, _Transfer, _validate_stream +from ._transfer import ( + _allocate, + _allocate_sync, + _call_in_context, + _CountPool, + _file_context, + _resize_output, + _Transfer, + _validate_stream, +) # cuObject and other remote storage backends can reuse the GPU buffer and # transfer lifetime machinery when they have compatible completion semantics. @@ -34,7 +44,7 @@ } -def open_file(path: _Path, mode: str = "rb", *, direct: bool = False) -> _File: +def open_file(path: _Path, mode: str = "rb", *, device: Device | int, direct: bool = False) -> _File: """Open a regular binary file for transfers between disk and GPU memory. Parameters @@ -44,6 +54,9 @@ def open_file(path: _Path, mode: str = "rb", *, direct: bool = False) -> _File: mode : str, optional Binary mode. Use ``"rb"`` to read, ``"wb"`` to create or truncate, or ``"xb"`` to create exclusively. Add ``+`` for read/write access. + device : Device or int + CUDA device or ordinal for transfers. The file retains the device's + configured context, or its primary context if it has no configured context. direct : bool, optional Open with Linux ``O_DIRECT``. cuFile chooses the transfer path based on the filesystem, hardware, and its configuration. It can use host @@ -52,17 +65,32 @@ def open_file(path: _Path, mode: str = "rb", *, direct: bool = False) -> _File: Returns ------- :class:`._File` - An open file for positional asynchronous and batch I/O. Use as a + An open file for positional synchronous, asynchronous, and batch I/O. Use as a context manager or call ``close()``. Notes ----- Requires Linux and the cuFile runtime. """ - return _open_file(path, mode, direct=direct, truncate=True) + device = _resolve_device(device) + return _open_file( + path, mode, direct=direct, truncate=True, device_id=device.device_id, context=_file_context(device) + ) -def _open_file(path: _Path, mode: str, *, direct: bool, truncate: bool) -> _File: +def _resolve_device(device: Device | int) -> Device: + return device if isinstance(device, Device) else Device(operator.index(device)) + + +def _open_file( + path: _Path, + mode: str, + *, + direct: bool, + truncate: bool, + device_id: int | None = None, + context: Context | None = None, +) -> _File: if sys.platform != "linux": raise RuntimeError("cuFile storage is available only on Linux") if mode in ("rb+", "wb+", "xb+"): @@ -73,7 +101,7 @@ def _open_file(path: _Path, mode: str, *, direct: bool, truncate: bool) -> _File # Resolve the optional runtime before opening a path for writing. cufile.get_version() - file = _File(cufile, mode) + file = _File(cufile, mode, device_id, context) fd = os.open(path, _MODES[mode] | (os.O_DIRECT if direct else 0)) try: if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -100,33 +128,19 @@ def _open_file(path: _Path, mode: str, *, direct: bool, truncate: bool) -> _File return file -def open(path: _Path, mode: str = "rb", *, stream: Stream | None, direct: bool = False) -> _StreamFile: - """Open a binary GPU file with a cursor bound to a CUDA stream. +def open( + path: _Path, mode: str = "rb", *, device: Device | int, stream: Stream | None = None, direct: bool = False +) -> _StreamFile: + """Open a binary GPU file with a byte cursor. - Pass an explicit CUDA stream, or pass `stream=None` to create one on the - current context (device 0's primary context if none is current). - `mode` and `direct` have the same meaning as in :func:`open_file`. - Closing the returned object closes the underlying file and any stream - created by this function. + Pass a CUDA stream to set the default for asynchronous methods. + `mode`, `device`, and `direct` have the same meaning as in :func:`open_file`. + Closing the returned object closes the underlying file. """ - owns_stream = stream is None - if stream is None: - stream = _new_stream() - else: - _validate_stream(stream) - with_file = None - try: - with_file = open_file(path, mode, direct=direct) - return _StreamFile(with_file, stream, owns_file=True, owns_stream=owns_stream) - except BaseException as error: - if with_file is not None: - with_file.__exit__(type(error), error, error.__traceback__) - if owns_stream: - try: - stream.close() - except Exception as cleanup: - error.add_note(f"closing the CUDA stream failed: {cleanup}") - raise + device = _resolve_device(device) + if stream is not None: + _validate_stream(stream, device.device_id) + return _StreamFile(open_file(path, mode, device=device, direct=direct), stream, owns_file=True) class _Request: @@ -178,12 +192,18 @@ def result(self) -> int: class _File: - """A binary file for positional device I/O, returned by `open_file()`.""" + """A binary file for positional device I/O, returned by `open_file()`. + + Blocking transfers use the file's CUDA context. Synchronize prior CUDA + work on the affected buffers before calling a blocking method. + """ - def __init__(self, cufile: ModuleType, mode: str): + def __init__(self, cufile: ModuleType, mode: str, device_id: int | None, context: Context | None): self._fd: int | None = None self._handle: int | None = None self._cufile = cufile + self._device_id = device_id + self._context = context self._readable = mode.startswith("r") or "+" in mode self._writable = not mode.startswith("r") or "+" in mode self._pending: OrderedDict[_Request, None] = OrderedDict() @@ -286,7 +306,10 @@ def _prepare(self, buffer: Buffer, offset: int, size: int | None, *, writing: bo def _transfer(self, buffer: Buffer, offset: int, size: int | None, *, writing: bool, stream: Stream) -> _Request: offset, size = self._prepare(buffer, offset, size, writing=writing) - _validate_stream(stream) + return self._submit_transfer(buffer, offset, size, writing=writing, stream=stream) + + def _submit_transfer(self, buffer: Buffer, offset: int, size: int, *, writing: bool, stream: Stream) -> _Request: + self._check_stream(stream) if ( size == 0 and (buffer.size or buffer.handle) @@ -324,14 +347,14 @@ def _transfer(self, buffer: Buffer, offset: int, size: int | None, *, writing: b ) return request - def read_async(self, size: int | None = None, *, offset: int = 0, stream: Stream) -> tuple[Buffer, _Request]: - """Allocate a GPU buffer and enqueue a positional read on `stream`. + def _check_stream(self, stream: Stream) -> None: + _validate_stream(stream, -1 if self._device_id is None else self._device_id) - The buffer has capacity `size` bytes, or the current file size minus - `offset` (at least zero) when `size` is omitted. Returns the buffer - and a request whose `result()` gives the valid byte count. The buffer - retains its full capacity after a short read. - """ + def _check_buffer_device(self, buffer: Buffer) -> None: + if self._device_id is not None and buffer.device_id != self._device_id: + raise ValueError("cuFile file and buffer must be on the same CUDA device") + + def _read_size(self, offset: int, size: int | None) -> tuple[int, int]: self._check_access(writing=False) offset = operator.index(offset) if not 0 <= offset <= _MAX_OFFSET: @@ -339,6 +362,66 @@ def read_async(self, size: int | None = None, *, offset: int = 0, stream: Stream size = max(0, self.size - offset) if size is None else operator.index(size) if not 0 <= size <= _MAX_OFFSET - offset: raise ValueError("invalid read size for the file offset") + return offset, size + + def _require_context(self) -> Context: + context = self._context + if context is None: + raise RuntimeError("cuFile context required for async/stream-oriented API") + return context + + def _transfer_sync(self, buffer: Buffer, offset: int, size: int | None, *, writing: bool) -> int: + offset, size = self._prepare(buffer, offset, size, writing=writing) + return _call_in_context(self._require_context(), self._transfer_sync_in_context, buffer, offset, size, writing) + + def _transfer_sync_in_context(self, buffer: Buffer, offset: int, size: int, writing: bool) -> int: + if (buffer.size or buffer.handle) and (not buffer.is_device_accessible or buffer.is_host_accessible): + raise ValueError("cuFile I/O requires device-resident GPU memory") + if size == 0: + return 0 + self._check_buffer_device(buffer) + io = self._cufile.write if writing else self._cufile.read + count: int = io(self._handle, buffer.handle, size, offset, 0) + if count < 0: + raise self._cufile.cuFileError(-count) + return count + + def read(self, size: int | None = None, *, offset: int = 0) -> Buffer: + """Read up to `size` bytes at `offset` into a new GPU buffer. + + Omit `size` to read up to the current EOF. The returned buffer's + size is the actual number of bytes read, including zero at EOF. + """ + offset, size = self._read_size(offset, size) + buffer = _allocate_sync(size, self._require_context()) + count = self.readinto(buffer, offset=offset) + _resize_output(buffer, count) + return buffer + + def readinto(self, buffer: Buffer, *, offset: int = 0, size: int | None = None) -> int: + """Read into a GPU buffer at `offset` and return the actual byte count. + + `size` defaults to the buffer's byte size. The read may be short at EOF. + """ + return self._transfer_sync(buffer, offset, size, writing=False) + + def write(self, buffer: Buffer, *, offset: int = 0, size: int | None = None) -> int: + """Write a GPU buffer at `offset` and return the actual byte count. + + `size` defaults to the buffer's byte size. + """ + return self._transfer_sync(buffer, offset, size, writing=True) + + def read_async(self, size: int | None = None, *, offset: int = 0, stream: Stream) -> tuple[Buffer, _Request]: + """Allocate a GPU buffer and enqueue a positional read on `stream`. + + The buffer has capacity `size` bytes, or the current file size minus + `offset` (at least zero) when `size` is omitted. Returns the buffer + and a request whose `result()` gives the valid byte count. The buffer + retains its full capacity after a short read. + """ + offset, size = self._read_size(offset, size) + self._check_stream(stream) buffer = _allocate(size, stream) return buffer, self.readinto_async(buffer, offset=offset, stream=stream) @@ -359,20 +442,16 @@ def write_async(self, buffer: Buffer, *, offset: int = 0, stream: Stream, size: """ return self._transfer(buffer, offset, size, writing=True, stream=stream) - def writeinto_async(self, buffer: Buffer, *, offset: int = 0, stream: Stream, size: int | None = None) -> _Request: - """Write the supplied GPU buffer into this file, as in `write_async()`.""" - return self.write_async(buffer, offset=offset, stream=stream, size=size) - def read_batch(self, entries: Iterable[_FileEntry]) -> list[int]: """Read a batch of `(buffer, offset[, size])` entries from this file. Waits for the batch and returns byte counts in input order. See :func:`cuda.core.storage.read_batch` for ordering and error semantics. """ - from ._batch import read_batch + from ._batch import _batch self._check_access(writing=False) - return read_batch((self, *entry) for entry in entries) + return _batch(((self, *entry) for entry in entries), writing=False, context=self._context) def write_batch(self, entries: Iterable[_FileEntry]) -> list[int]: """Write a batch of `(buffer, offset[, size])` entries into this file. @@ -380,42 +459,44 @@ def write_batch(self, entries: Iterable[_FileEntry]) -> list[int]: Waits for the batch and returns byte counts in input order. See :func:`cuda.core.storage.write_batch` for ordering and error semantics. """ - from ._batch import write_batch + from ._batch import _batch self._check_access(writing=True) - return write_batch((self, *entry) for entry in entries) + return _batch(((self, *entry) for entry in entries), writing=True, context=self._context) - def streaming(self, stream: Stream | None) -> _StreamFile: + def streaming(self, stream: Stream | None = None) -> _StreamFile: """Return a file-like view with an independent cursor at byte zero. - Pass a CUDA stream or explicitly pass `None` to create one, as in - :func:`open`. Closing the view closes a stream it created and - leaves the backing file open. Closing the file invalidates the view. + Pass a CUDA stream to set the default for asynchronous methods. + Closing the view leaves the backing file open. Closing the file + invalidates the view. """ if self.closed: raise ValueError("I/O on a closed cuFile file") - owns_stream = stream is None - if stream is None: - stream = _new_stream() - else: - _validate_stream(stream) - return _StreamFile(self, stream, owns_file=False, owns_stream=owns_stream) + if stream is not None: + self._check_stream(stream) + return _StreamFile(self, stream, owns_file=False) class _StreamFile: - """A binary file-like object whose GPU I/O is ordered on one CUDA stream.""" + """A binary GPU file with a byte cursor and an optional CUDA stream. + + Blocking I/O uses the file's CUDA context. Synchronize prior CUDA work + on the buffers before calling a blocking method. Asynchronous methods + reserve the requested byte range at submission and advance the cursor by + its size. The request reports the actual byte count or error. + """ - def __init__(self, file: _File, stream: Stream, *, owns_file: bool, owns_stream: bool): + def __init__(self, file: _File, stream: Stream | None, *, owns_file: bool): self._file = file self._stream = stream self._owns_file = owns_file - self._owns_stream = owns_stream self._closed = False self._position = 0 @property - def stream(self) -> Stream: - """The CUDA stream on which this object's I/O is submitted.""" + def stream(self) -> Stream | None: + """The default CUDA stream for asynchronous I/O, if one was supplied.""" return self._stream @property @@ -438,15 +519,13 @@ def __exit__( exc.add_note(f"closing the streamed cuFile file failed: {cleanup}") def close(self) -> None: - """Close this view and any file or stream it owns.""" + """Close this view and any file it owns.""" try: if self._owns_file: self._file.close() finally: if not self._owns_file or self._file.closed: self._closed = True - if self._owns_stream: - self._stream.close() def tell(self) -> int: """Return the current byte offset.""" @@ -477,12 +556,10 @@ def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: def readinto(self, buffer: Buffer, size: int | None = None) -> int: """Read into a GPU buffer at the cursor, then advance by bytes read. - Enqueues the read on this object's stream and waits for it. Returns - the actual byte count, which can be less than `size` at EOF. - The default is the buffer's byte size. + Returns the actual byte count, which can be less than `size` at EOF. + The default size is the buffer's byte size. """ - request = self._file.readinto_async(buffer, offset=self.tell(), stream=self._stream, size=size) - count = request.result() + count = self._file.readinto(buffer, offset=self.tell(), size=size) self._position += count return count @@ -493,10 +570,8 @@ def read(self, size: int = -1) -> Buffer: byte size is the actual number read, including zero at EOF. """ size = operator.index(size) - buffer, request = self._file.read_async(None if size == -1 else size, offset=self.tell(), stream=self._stream) - count = request.result() - _resize_output(buffer, count) - self._position += count + buffer = self._file.read(None if size == -1 else size, offset=self.tell()) + self._position += buffer.size return buffer def readuntil(self, end: int | None = None) -> Buffer: @@ -506,20 +581,62 @@ def readuntil(self, end: int | None = None) -> Buffer: by the actual bytes read. When it is already at or beyond `end`, return a zero-byte buffer. """ + return self.read(self._size_until(end)) + + def _size_until(self, end: int | None) -> int: if end is None: - return self.read() + return -1 end = operator.index(end) if not 0 <= end <= _MAX_OFFSET: raise ValueError("end must fit in a nonnegative signed 64-bit offset") - return self.read(max(0, end - self.tell())) + return max(0, end - self.tell()) def write(self, buffer: Buffer, size: int | None = None) -> int: """Write from a GPU buffer at the cursor and advance by bytes written. - Enqueues the write on this object's stream and waits for it. The - default size is the buffer's byte size. Returns the actual byte count. + The default size is the buffer's byte size. Returns the actual byte count. """ - request = self._file.write_async(buffer, offset=self.tell(), stream=self._stream, size=size) - count = request.result() + count = self._file.write(buffer, offset=self.tell(), size=size) self._position += count return count + + def _resolve_stream(self, stream: Stream | None) -> Stream: + if stream is None: + stream = self._stream + if stream is None: + raise ValueError("asynchronous cuFile I/O requires a CUDA stream") + return stream + + def read_async(self, size: int = -1, *, stream: Stream | None = None) -> tuple[Buffer, _Request]: + """Queue a read at the cursor and return a new buffer and its request. + + The buffer has capacity `size`, or the remaining file size for `-1`. + Use the request's `result()` for the number of valid bytes. + """ + size = operator.index(size) + buffer, request = self._file.read_async( + None if size == -1 else size, offset=self.tell(), stream=self._resolve_stream(stream) + ) + self._position += buffer.size + return buffer, request + + def readuntil_async(self, end: int | None = None, *, stream: Stream | None = None) -> tuple[Buffer, _Request]: + """Queue a read up to exclusive offset `end`, or up to the current EOF.""" + return self.read_async(self._size_until(end), stream=stream) + + def readinto_async(self, buffer: Buffer, size: int | None = None, *, stream: Stream | None = None) -> _Request: + """Queue a read into a GPU buffer at the cursor and return its request.""" + return self._transfer_async(buffer, size, stream, writing=False) + + def write_async(self, buffer: Buffer, size: int | None = None, *, stream: Stream | None = None) -> _Request: + """Queue a write from a GPU buffer at the cursor and return its request.""" + return self._transfer_async(buffer, size, stream, writing=True) + + def _transfer_async(self, buffer: Buffer, size: int | None, stream: Stream | None, *, writing: bool) -> _Request: + offset = self.tell() + offset, size = self._file._prepare(buffer, offset, size, writing=writing) + request = self._file._submit_transfer( + buffer, offset, size, writing=writing, stream=self._resolve_stream(stream) + ) + self._position += size + return request diff --git a/cuda_core/cuda/core/storage/_transfer.pyi b/cuda_core/cuda/core/storage/_transfer.pyi new file mode 100644 index 000000000000..88af225352d1 --- /dev/null +++ b/cuda_core/cuda/core/storage/_transfer.pyi @@ -0,0 +1,35 @@ +# This file was generated by stubgen-pyx v0.2.23 from cuda_core/cuda/core/storage/_transfer.pyx + +from collections.abc import Callable +from typing import TypeVar + +from cuda.core._context import Context +from cuda.core._memory._buffer import Buffer +from cuda.core._stream import Stream + +_T = TypeVar('_T') + +class _BatchOwners: + def __init__(self, entries, params, events): ... + def abandon(self): ... + +class _CountSlab: + """One pinned allocation shared by transfers in the same CUDA context.""" + def __init__(self, context: Context): ... + +class _CountPool: + """Cache at most one slab per context for an open file.""" + def __init__(self): ... + +class _Transfer: + """Native arguments and allocation owners for a single cuFile operation.""" + def submit(self, cufile, file: int, buffer: Buffer, size: int, offset: int, stream: Stream, writing: bool, count_pool: _CountPool): ... + def complete(self, wait: bool): + """Return the signed byte count, or None while pending.""" + +def _file_context(device) -> Context: ... +def _allocate_sync(size: int, context: Context) -> Buffer: ... +def _call_in_context(context: Context, operation: Callable[..., _T], *args: object) -> _T: ... +def _validate_stream(stream: Stream, expected_device: int=-1): ... +def _allocate(size: int, stream: Stream): ... +def _resize_output(buffer: Buffer, size: int): ... diff --git a/cuda_core/cuda/core/storage/_transfer.pyx b/cuda_core/cuda/core/storage/_transfer.pyx index cff6dd69b532..b694dce7348e 100644 --- a/cuda_core/cuda/core/storage/_transfer.pyx +++ b/cuda_core/cuda/core/storage/_transfer.pyx @@ -3,6 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 import os +from collections.abc import Callable +from typing import TypeVar cimport cython from cpython.ref cimport Py_DECREF, Py_INCREF @@ -10,7 +12,7 @@ from libc.stdint cimport int64_t, intptr_t from libcpp.vector cimport vector from cuda.bindings cimport cydriver -from cuda.core._context cimport Context +from cuda.core._context cimport Context, Context_check_open from cuda.core._event cimport Event from cuda.core._memory._buffer cimport Buffer, Buffer_check_open, Buffer_from_deviceptr_handle from cuda.core._rt cimport ( @@ -22,13 +24,11 @@ from cuda.core._rt cimport ( as_cu, attach_rollback_failure, clear_last_error_detail, - context_get_device, create_event_handle, deviceptr_alloc_from_pool, deviceptr_alloc_host, enter_context, exit_context, - get_current_context, get_device_mempool, get_last_error, get_primary_context, @@ -37,21 +37,52 @@ from cuda.core._stream cimport Stream, Stream_check_open, Stream_is_default_toke from cuda.core._utils.cuda_utils cimport HANDLE_RETURN -def _new_stream(): - from cuda.core import Device +_T = TypeVar("_T") - Device(0) # Initialize the driver without changing the current context. - cdef ContextHandle context - cdef cydriver.CUdevice device - with nogil: - context = get_current_context() - if not context: - HANDLE_RETURN(get_last_error()) - context = get_primary_context(0) - if not context: + +def _file_context(device) -> Context: + cdef Context context = device._context + cdef int device_id = device.device_id + cdef ContextHandle handle + if context is not None: + Context_check_open(context) + handle = context._h_context + else: + with nogil: + handle = get_primary_context(device_id) + if not handle: HANDLE_RETURN(get_last_error()) - HANDLE_RETURN(context_get_device(context, &device)) - return Stream._init(ctx=Context._from_handle(Context, context, device), device_id=device) + if not handle: + raise RuntimeError("internal cuda.core error, please report: missing cuFile context") + return Context._from_handle(Context, handle, device_id) + + +def _allocate_sync(size_t size, Context context not None) -> Buffer: + from cuda.core._memory._synchronous_memory_resource import _SynchronousMemoryResource + + resource = _SynchronousMemoryResource(context._device_id, context) + return resource.allocate(size) + + +def _call_in_context(Context context not None, operation: Callable[..., _T], *args: object) -> _T: + cdef cydriver.CUcontext previous + cdef int changed + cdef cydriver.CUresult restore + Context_check_open(context) + with nogil: + HANDLE_RETURN(enter_context(context._h_context, &previous, &changed)) + try: + result = operation(*args) + except: + with nogil: + restore = exit_context(previous, changed, cydriver.CUresult.CUDA_SUCCESS) + if restore != cydriver.CUresult.CUDA_SUCCESS: + clear_last_error_detail() + attach_rollback_failure(b"cuCtxSetCurrent", restore, b"restoring the caller's context") + raise + with nogil: + HANDLE_RETURN(exit_context(previous, changed, cydriver.CUresult.CUDA_SUCCESS)) + return result cdef class _BatchOwners: @@ -70,11 +101,16 @@ cdef class _BatchOwners: Py_INCREF(self) -def _validate_stream(Stream stream not None): +def _validate_stream(Stream stream not None, int expected_device=-1): Stream_check_open(stream) # Default stream tokens cannot identify the same queue from every thread. if Stream_is_default_token(stream): raise ValueError("cuFile requires an explicit CUDA stream") + cdef Context context + if expected_device >= 0: + context = stream.context + if context._device_id != expected_device: + raise ValueError("cuFile file and stream must be on the same CUDA device") cdef void _check_capture(cydriver.CUstream stream) except *: diff --git a/cuda_core/docs/source/storage.rst b/cuda_core/docs/source/storage.rst index 3c342b7d8bb7..82ae78e41b26 100644 --- a/cuda_core/docs/source/storage.rst +++ b/cuda_core/docs/source/storage.rst @@ -8,7 +8,10 @@ GPU file I/O :func:`open_file` and :func:`open` transfer bytes between a regular filesystem file and device memory through NVIDIA cuFile. They accept binary modes and device-resident -:class:`~cuda.core.Buffer` objects. The cuFile runtime is required on Linux. +:class:`~cuda.core.Buffer` objects. Both take a required ``device=`` argument +accepting a :class:`~cuda.core.Device` or a CUDA device ordinal. The same +operations are available as :meth:`~cuda.core.Device.open_file` and +:meth:`~cuda.core.Device.open`. The cuFile runtime is required on Linux. cuFile can stage data through host memory internally, depending on its configuration, the filesystem, and the hardware. Pass ``direct=True`` to request opening the file with ``O_DIRECT``. @@ -43,11 +46,21 @@ Use :func:`open_file` for independent transfers at explicit byte offsets. The file's ``size`` attribute reports its current size in bytes. Wait for any pending writes before relying on their effect on the size. +For blocking I/O, use ``read(size, offset=...)`` to allocate a GPU buffer, +``readinto(buffer, offset=...)`` to fill an existing one, and +``write(buffer, offset=...)`` to write from a buffer. Offsets default to +zero. An omitted read size for an +allocating read means read to the current EOF. The returned buffer's size +is the actual number of bytes read. Methods that take an existing buffer +default to its full size and return the actual byte count. These methods +use ``cuFileRead`` or ``cuFileWrite`` in the file's CUDA context. Synchronize +prior CUDA work on the affected buffers before calling. + .. code-block:: python from cuda.core.storage import open_file - with open_file("frames.bin", "rb") as file: + with open_file("frames.bin", "rb", device=device) as file: frame_a, first = file.read_async(4096, offset=4096, stream=stream) second = file.readinto_async(frame_b, offset=8192, stream=stream) count_a = first.result() @@ -56,8 +69,8 @@ any pending writes before relying on their effect on the size. ``read_async`` returns a new buffer and its request. The buffer has the requested capacity, or the file size minus the offset if no size was supplied. After a short read, only the prefix identified by the request's byte count contains new -data. ``readinto_async`` reads into an existing buffer. ``write_async`` and -``writeinto_async`` both write from a supplied GPU buffer. Operations on existing +data. ``readinto_async`` reads into an existing buffer. ``write_async`` writes +from a supplied GPU buffer. Operations on existing buffers default to the full buffer size. Pass ``size=`` to transfer a prefix. An asynchronous transfer is ordered with CUDA work submitted before and after @@ -93,27 +106,33 @@ existing bytes outside the written ranges. from cuda.core.storage import open_file, read_batch - with open_file("a.bin") as a: + with open_file("a.bin", device=device) as a: counts = read_batch([(a, header, 0), ("b.bin", frame, 8192, 4096)]) counts = a.read_batch([(header, 0), (frame, 4096)]) Batch calls wait on the host and return byte counts in input order. Operations -within a batch can run in any order. Synchronize earlier CUDA work on any -affected buffers before submitting a batch. The active cuFile configuration -determines the maximum number of nonempty entries in a batch. - -Stream-bound files ------------------- - -Bind a stream when opening the file to get a file-like object with a byte -cursor. Each read or write submits the transfer to that stream, waits for its -result, and advances the cursor by the actual byte count. +within a batch can run in any order. The file methods use the file's CUDA +context, and the module-level functions use the caller's current context. +Synchronize earlier CUDA work on any affected buffers before submitting a +batch. The active cuFile configuration determines the maximum number of +nonempty entries in a batch. + +Files with a byte cursor +------------------------ + +Use :func:`open` for a file-like object with a byte cursor. Blocking reads and +writes call ``cuFileRead`` and ``cuFileWrite`` and advance the cursor by the +actual byte count. The file retains the device's configured context when +opened, or uses that device's primary context if it has no configured +context. Blocking I/O uses that context and restores the caller's previous +context. Synchronize any prior CUDA work on the affected buffers before +calling these methods. .. code-block:: python from cuda.core import storage - with storage.open("frames.bin", stream=None) as reader: + with storage.open("frames.bin", device=device) as reader: header = reader.read(4096) first_frame = reader.readuntil(8192) remaining = reader.read() @@ -125,13 +144,22 @@ The returned buffer's size is the actual number of bytes read. Use ``readinto(buffer)`` to reuse a buffer or ``write(buffer)`` to write its bytes. The cursor supports ``seek()`` and ``tell()``. -Both ``storage.open()`` and ``file.streaming()`` require an explicit stream -argument. Pass ``None`` to create an owned CUDA stream on the current context, -or on device 0's primary context when none is current. Closing a file from -``storage.open()`` also closes its backing file. Each ``file.streaming()`` -view starts at byte zero and borrows the already-open file. Closing the -backing file invalidates all its views. The caller must coordinate cursor -mutations and closing a file with other operations on it. +Use ``read_async()``, ``readuntil_async()``, ``readinto_async()``, or +``write_async()`` for stream-ordered transfers. The stream must belong to +the file's device. Pass it per call or set a default when opening the file +or creating a ``file.streaming()`` view. Omitting the stream or passing +``None`` leaves the file or view without a default stream. Each async call +reserves its requested byte range and advances the cursor on submission. +Use ``request.result()`` for the actual byte count or error. A short transfer +leaves the cursor at the end of the reserved range. Allocating async reads +return both the buffer and the request, and the buffer retains its full +capacity. + +Closing a file from ``storage.open()`` also closes its backing file and waits +for pending transfers. Each ``file.streaming()`` view starts at byte zero +and borrows the already-open file, which retains its pending transfers. +Closing the backing file invalidates all its views. The caller must +coordinate cursor mutations and closing a file with other operations on it. API reference ------------- diff --git a/cuda_core/tests/test_storage.py b/cuda_core/tests/test_storage.py index ba693d00d87d..d107cd639aa0 100644 --- a/cuda_core/tests/test_storage.py +++ b/cuda_core/tests/test_storage.py @@ -5,7 +5,7 @@ import ctypes import os import sys -from contextlib import ExitStack +from contextlib import ExitStack, closing from types import SimpleNamespace import pytest @@ -21,6 +21,13 @@ ] +@pytest.fixture +def file_device(): + device = object.__new__(Device) + device._device_id = 0 + return device + + @pytest.fixture def fake_cufile(monkeypatch): """Use ordinary file descriptors to exercise the Python file and cursor contract.""" @@ -29,6 +36,7 @@ class FakeBuffer: is_closed = False is_device_accessible = True is_host_accessible = False + device_id = 0 def __init__(self, size): self.size = size @@ -69,17 +77,25 @@ def descriptor(): monkeypatch.setattr(bindings, "cufile", backend, raising=False) monkeypatch.setattr(_file, "Buffer", FakeBuffer) monkeypatch.setattr(_file, "_Transfer", Transfer) - monkeypatch.setattr(_file, "_validate_stream", lambda _stream: None) + + def validate_stream(stream, expected_device): + if stream.device_id != expected_device: + raise ValueError("cuFile file and stream must be on the same CUDA device") + + monkeypatch.setattr(_file, "_validate_stream", validate_stream) + monkeypatch.setattr(_file, "_file_context", lambda device: device) + monkeypatch.setattr(_file, "_call_in_context", lambda _context, call, *args: call(*args)) monkeypatch.setattr(_file, "_allocate", lambda size, _stream: FakeBuffer(size)) + monkeypatch.setattr(_file, "_allocate_sync", lambda size, _context: FakeBuffer(size)) monkeypatch.setattr(_file, "_resize_output", lambda buffer, size: setattr(buffer, "size", size)) return backend, FakeBuffer -def test_cursor_reads_and_independent_views(fake_cufile, tmp_path): +def test_cursor_reads_and_independent_views(fake_cufile, file_device, tmp_path): path = tmp_path / "data.bin" path.write_bytes(b"012345") - stream = object() - with storage.open(path, stream=stream) as reader: + stream = SimpleNamespace(device_id=0) + with file_device.open(path, stream=stream) as reader: backing_file = reader._file assert reader.stream is stream assert reader.read(2).handle == b"01" @@ -94,7 +110,7 @@ def test_cursor_reads_and_independent_views(fake_cufile, tmp_path): assert reader.closed assert backing_file.closed - with open_file(path) as file: + with open_file(path, device=file_device) as file: with file.streaming(stream) as first, file.streaming(stream) as second: first.read(3) assert second.tell() == 0 @@ -102,15 +118,15 @@ def test_cursor_reads_and_independent_views(fake_cufile, tmp_path): assert not file.closed -def test_positional_operations_and_close(fake_cufile, tmp_path): +def test_positional_operations_and_close(fake_cufile, file_device, tmp_path): _, Buffer = fake_cufile path = tmp_path / "data.bin" src = Buffer(4) src.handle[:] = b"cuda" - stream = object() - with open_file(path, "w+b") as file: + stream = SimpleNamespace(device_id=0) + with open_file(path, "w+b", device=file_device) as file: assert file.write_async(src, stream=stream).result() == 4 - request = file.writeinto_async(src, offset=4, stream=stream, size=2) + request = file.write_async(src, offset=4, stream=stream, size=2) assert not request.is_done assert file.size == 6 dst = Buffer(4) @@ -135,7 +151,27 @@ def test_positional_operations_and_close(fake_cufile, tmp_path): assert path.read_bytes() == b"cudacu" -def test_registration_failure_preserves_existing_file(fake_cufile, monkeypatch, tmp_path): +def test_positional_sync_io(fake_cufile, file_device, tmp_path): + _, Buffer = fake_cufile + path = tmp_path / "data.bin" + src = Buffer(4) + src.handle[:] = b"cuda" + with file_device.open_file(path, "w+b") as file, file.streaming() as view: + assert file.write(src) == 4 + assert file.write(src, offset=4, size=2) == 2 + dst = Buffer(4) + assert file.readinto(dst, offset=3) == 3 + assert dst.handle[:3] == b"acu" + assert file.read(offset=3).handle == b"acu" + tail = file.read(8, offset=4) + assert tail.size == 2 + assert tail.handle[: tail.size] == b"cu" + assert file.read(offset=9).size == 0 + assert view.tell() == 0 + assert path.read_bytes() == b"cudacu" + + +def test_registration_failure_preserves_existing_file(fake_cufile, file_device, monkeypatch, tmp_path): backend, _ = fake_cufile path = tmp_path / "data.bin" path.write_bytes(b"keep") @@ -147,37 +183,69 @@ def fail_registration(desc): monkeypatch.setattr(backend, "handle_register", fail_registration) with pytest.raises(OSError, match="registration failed"): - open_file(path, "wb") + open_file(path, "wb", device=file_device) assert path.read_bytes() == b"keep" with pytest.raises(OSError): os.fstat(seen[0]) -def test_binary_modes(fake_cufile, tmp_path): +def test_binary_modes(fake_cufile, file_device, tmp_path): with pytest.raises(ValueError, match="binary mode"): - open_file(tmp_path / "data", "r") + open_file(tmp_path / "data", "r", device=file_device) -def test_owned_stream_is_explicit(fake_cufile, monkeypatch, tmp_path): - closed_streams = [] - monkeypatch.setattr(_file, "_new_stream", lambda: SimpleNamespace(close=lambda: closed_streams.append(1))) +def test_optional_stream_and_cursor_io(fake_cufile, file_device, tmp_path): + _, Buffer = fake_cufile path = tmp_path / "data" - path.touch() - with pytest.raises(TypeError, match="stream"): - storage.open(path) - with open_file(path) as file: - with pytest.raises(TypeError, match="stream"): - file.streaming() - with file.streaming(None): - assert not closed_streams - assert closed_streams == [1] + stream = SimpleNamespace(device_id=0) + src = Buffer(4) + src.handle[:] = b"cuda" + foreign_stream = SimpleNamespace(device_id=1) + with pytest.raises(TypeError, match="device"): + storage.open(path, "w+b") + with pytest.raises(TypeError, match="device"): + open_file(path, "w+b") + with pytest.raises(ValueError, match="same CUDA device"): + storage.open(path, "w+b", device=file_device, stream=foreign_stream) + assert not path.exists() + with storage.open(path, "w+b", device=file_device) as file: + assert file.stream is None + with pytest.raises(ValueError, match="requires a CUDA stream"): + file.write_async(src) + with pytest.raises(ValueError, match="same CUDA device"): + file.write_async(src, stream=foreign_stream) + foreign_buffer = Buffer(4) + foreign_buffer.device_id = 1 + with pytest.raises(ValueError, match="same CUDA device"): + file.write(foreign_buffer) + assert file.tell() == 0 + assert file.write(src, 3) == 3 + pending = file.write_async(src, size=2, stream=stream) + assert file.tell() == 5 + assert not pending.is_done + assert pending.result() == 2 + file.seek(0) + dst = Buffer(3) + assert file.readinto(dst) == 3 + assert dst.handle == b"cud" + with open_file(path, device=file_device) as file: + with file.streaming() as reader: + assert reader.stream is None + with file.streaming(stream) as reader: + dst = Buffer(3) + first = reader.readinto_async(dst) + last, second = reader.readuntil_async(8) + assert reader.tell() == 8 + assert last.size == 5 + assert not second.is_done + assert first.result() == 3 + assert dst.handle == b"cud" + assert second.result() == 2 + assert last.handle[:2] == b"cu" assert not file.closed - with storage.open(path, stream=None): - assert closed_streams == [1] - assert closed_streams == [1, 1] -def test_close_waits_after_submission_error(fake_cufile, monkeypatch, tmp_path): +def test_close_waits_after_submission_error(fake_cufile, file_device, monkeypatch, tmp_path): backend, Buffer = fake_cufile steps = [] @@ -193,8 +261,11 @@ def complete(self, wait): monkeypatch.setattr(_file, "_Transfer", Transfer) monkeypatch.setattr(backend, "handle_deregister", lambda _handle: steps.append("deregistered")) - with open_file(tmp_path / "data", "wb") as file, pytest.raises(RuntimeError, match="event record failed"): - file.write_async(Buffer(4), offset=0, stream=object()) + with ( + open_file(tmp_path / "data", "wb", device=file_device) as file, + pytest.raises(RuntimeError, match="event record failed"), + ): + file.write_async(Buffer(4), offset=0, stream=SimpleNamespace(device_id=0)) assert steps == ["submitted", "completed", "deregistered"] @@ -216,7 +287,7 @@ def cufile_device(tmp_path): device = Device() device.set_current() try: - with open_file(tmp_path / "probe.bin", "w+b"): + with device.open_file(tmp_path / "probe.bin", "w+b"): pass except cufile.cuFileError as exc: if exc.status in ( @@ -231,29 +302,34 @@ def cufile_device(tmp_path): def test_stream_ordered_cufile(tmp_path, cufile_device): device = cufile_device - stream = device.create_stream() path = tmp_path / "data.bin" other = tmp_path / "other.bin" - with open_file(path, "w+b") as file, device.allocate(4096, stream=stream) as src: + with ( + closing(device.create_stream()) as stream, + device.open(path, "w+b", stream=stream) as file, + device.allocate(4096, stream=stream) as src, + ): src.fill(ord("a"), stream=stream) - first = file.write_async(src, offset=0, stream=stream) + first = file.write_async(src) src.fill(ord("b"), stream=stream) - second = file.write_async(src, offset=4096, stream=stream) + second = file.write_async(src) assert first.result() == second.result() == 4096 - with file.streaming(stream) as reader: - with reader.readuntil() as data, storage.open(other, "wb", stream=stream) as writer: + + assert driver.cuCtxSetCurrent(driver.CUcontext(0)) == (driver.CUresult.CUDA_SUCCESS,) + try: + with storage.open(path, device=device.device_id) as reader, device.open(other, "wb") as writer: + assert reader.stream is None + with reader.readuntil() as data: assert writer.write(data) == 8192 with reader.read() as eof: assert eof.size == 0 - stream.sync() + status, context = driver.cuCtxGetCurrent() + assert status == driver.CUresult.CUDA_SUCCESS + assert int(context) == 0 + finally: + device.set_current() assert other.read_bytes() == b"a" * 4096 + b"b" * 4096 - with storage.open(path, stream=None) as reader, reader.read(4096) as first_block: - owned_stream = reader.stream - assert first_block.size == 4096 - assert owned_stream.is_closed - assert not stream.is_closed - def test_cufile_batch_across_files(tmp_path, cufile_device): device = cufile_device @@ -261,8 +337,8 @@ def test_cufile_batch_across_files(tmp_path, cufile_device): first_path = tmp_path / "first.bin" second_path = tmp_path / "second.bin" with ExitStack() as stack: - first = stack.enter_context(open_file(first_path, "w+b")) - second = stack.enter_context(open_file(second_path, "w+b")) + first = stack.enter_context(device.open_file(first_path, "w+b")) + second = stack.enter_context(device.open_file(second_path, "w+b")) src = stack.enter_context(device.allocate(4096, stream=stream)) a = stack.enter_context(device.allocate(4096, stream=stream)) b = stack.enter_context(device.allocate(4096, stream=stream)) @@ -344,7 +420,7 @@ def submit_read(_file, _buffer, _size, _offset, _buffer_offset, count, _stream): stream.close() -def test_batch_path_handles_close_on_validation_error(fake_cufile, monkeypatch, tmp_path): +def test_batch_path_handles_close_on_validation_error(fake_cufile, file_device, monkeypatch, tmp_path): backend, Buffer = fake_cufile opened, closed = [], [] first_path = tmp_path / "first.bin" @@ -358,7 +434,7 @@ def register(desc): monkeypatch.setattr(backend, "handle_register", register) monkeypatch.setattr(backend, "handle_deregister", closed.append) - with open_file(first_path) as file: + with file_device.open_file(first_path) as file: with pytest.raises(ValueError, match="file byte range"): storage.read_batch([(file, Buffer(0), 0), (path, Buffer(0), 0), (os.fsencode(path), Buffer(0), -1)]) assert len(opened) == 2 @@ -373,7 +449,7 @@ def test_cufile_batch_paths_preserve_existing_data(tmp_path, cufile_device): existing = tmp_path / "existing.bin" missing = tmp_path / "new.bin" existing.write_bytes(b"a" * 12288) - with open_file(existing, "rb") as file, device.allocate(4096, stream=stream) as data: + with device.open_file(existing, "rb") as file, device.allocate(4096, stream=stream) as data: data.fill(ord("b"), stream=stream) stream.sync() assert storage.write_batch([(existing, data, 4096), (str(missing), data, 0)]) == [4096, 4096]