Skip to content
Draft

File #3702

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cuda_core/cuda/core/_cpp/rt/rt.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
#include "driver_api.hpp"
#include "error.hpp"
#include "api.hpp"
#include "context_scope.hpp"
12 changes: 12 additions & 0 deletions cuda_core/cuda/core/_device.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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, driver
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,
Expand Down Expand Up @@ -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`.
Expand Down
20 changes: 20 additions & 0 deletions cuda_core/cuda/core/_device.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`.

Expand Down
4 changes: 4 additions & 0 deletions cuda_core/cuda/core/_rt.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,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(
Expand Down
4 changes: 4 additions & 0 deletions cuda_core/cuda/core/_rt.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,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" (
Expand Down
10 changes: 10 additions & 0 deletions cuda_core/cuda/core/storage/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
134 changes: 134 additions & 0 deletions cuda_core/cuda/core/storage/_batch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# 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._context import Context
from cuda.core._memory._buffer import Buffer

from ._file import _File, _open_file, _Path
from ._transfer import _BatchOwners, _call_in_context

_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, context: Context | None = None) -> 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:
file._check_buffer_device(buffer)
active.append((file, buffer, offset, size, len(counts)))
counts.append(0)
if active:
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:
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))
Loading
Loading