r/HPC • u/Emergency-Tutor-7 • 1d ago
Mapped pinned host memory for CUDA kernels, and where it stops being a good idea
On a node whose working set is larger than device memory, the interesting question is not how to copy faster, it is whether to copy at all. cudaMallocManaged answers that with page migration: one address space, residency decided at fault time, VRAM oversubscribed by eviction. On a slow interconnect with irregular access, that policy is often not the one you would have picked.
vram-stream opens a CUDA workspace with two regions, one in device memory and one in system RAM, and makes both addressable from the same kernel. The RAM region is allocated with cuMemHostAlloc and CU_MEMHOSTALLOC_DEVICEMAP, then mapped with cuMemHostGetDevicePointer_v2, after checking that the device reports CAN_MAP_HOST_MEMORY. A kernel load from that region travels over PCIe or NVLink with link latency, with no page fault and no migration, and the CPU reaches the same bytes through ram_host_pointer after stream synchronisation.
What you pay is pinned memory, which the driver and the operating system cap, so this is a fixed budget rather than an elastic one, and every access costs link bandwidth. That shapes the design: open_cuda_cache reads a contiguous buffer in fixed-size blocks and keeps one pinned buffer and one VRAM buffer per slot, copies and kernels run in separate CUDA streams, CUDA events protect the pinned buffer from being overwritten mid-flight, and cache.prefetch(n) pulls the next blocks in before the kernel that needs them starts.
The PyTorch side uses the same mechanism instead of a second one: prefetch_dataloader supplies cached batches, and optional integrations move model state and saved activations to RAM through FSDP2 or the Hugging Face Trainer with DeepSpeed, which is where write-once-read-once tensors live in practice.
There is a benchmark rather than a throughput claim: vram-stream benchmark --block-mib 16 --blocks 2 --slots 2 --passes 4 measures both CUDA memory paths on the card in the machine, and the README quotes no number because PCIe generation and NVLink topology move the comparison more than any figure would survive as a general statement.
Correctness is one command: vram-stream memory --device 0 --vram-mib 16 --ram-mib 16 allocates both regions, launches a kernel that combines values from VRAM and system RAM and writes results back to both, then verifies the first and last aligned 32-bit words of each region, with the bundled PTX kernel compiled by the driver at run time.
Install is pip install vram-stream, or npm i -g vram-stream. What it does not do: it is not a managed-memory replacement, pinning fails past the lockable limit instead of degrading gracefully, throughput is bounded by the interconnect, and the workspace assumes the selected CUDA context on the thread that opened it. MIT, 0.4.0: https://github.com/Furox-Art/vram-stream