From 46e6a3b01d66e1555c4dcd25f6b3db1f94b0022c Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Fri, 4 Dec 2026 19:33:13 -0800 Subject: [PATCH 1/2] async_transfer: add DevToHost, dual-stream H2D, DEFER_TASKRUN io_uring, and host-wide RAM pool budgeting Exclusive multi-tier weight offloading on multi-GPU hosts hits five concrete defects and bottlenecks in Helios's `AsyncTransfer` runtime: 1. No device-to-host Copy Engine path: `AsyncTransfer` only supported `DiskToHost` (1), `HostToDev` (2), `DiskToDev` (3), and `CancelEpoch` (4). A captured graph maintaining an exclusive VRAM/RAM cache had no way to demote a cold VRAM resident back to `HOST_POOL` over PCIe D2H instead of dropping it and re-reading from NVMe later. 2. Copy Engine head-of-line blocking: demand and background H2D copies shared one CUDA stream, so in-flight background prefetches delayed newly arrived demand misses, and the scheduler dispatched background work alongside active demand ops. 3. Multi-rank `io_uring` tail latency and contention: constructing the ring on the setup thread without `SINGLE_ISSUER | DEFER_TASKRUN`, issuing unfixed `Read` SQEs without registered host buffers, and draining storage batches in identical order across ranks caused cross-rank NVMe RAID-0 lockstep stalls and avoidable kernel page-pinning and interrupt overhead. 4. Mis-scoped `--pool-ram-memory` and peer-UVA page-table budgeting: `allocate_caches` divided available host RAM by `discrete_ranks` before applying `--pool-ram-memory`, so an explicit host reserve such as `-8G` on an 8-GPU host reserved 64 GiB (plus Selene's implicit host reserve), and `bytes(64G)` attempted to allocate 64 GiB per rank. On multi-GPU UVA processes with peer access, registering pinned host pools also maps page tables across peer contexts, so charging only single-rank `pinned / 512` underestimated per-GPU VRAM page-table usage. 5. Serialized multi-rank worker startup: `NativeModel::prepare_async_transfers` called `start_async_transfers()` one rank at a time, serializing per-rank fixed-buffer registration across all local GPUs. What changed: - Driver bindings (`helios/src/runtime_core/driver.rs`): added `cuCtxGetStreamPriorityRange`, `cuStreamCreateWithPriority`, `cuStreamWaitEvent`, and `cuMemcpyDtoHAsync_v2`. - Ring ABI and Kani proofs (`helios/src/async_transfer/ring.rs`, `helios/src/async_transfer/kani_proofs.rs`): added `Opcode::DevToHost = 5` and `ValidatedCommand::DevToHost`, enforcing priority, alignment, nonzero length, host and device pool bounds, completion-slot range, and bit-63 `COMPLETION_ERROR_BIT` exclusion in `validate_command` and the Kani command validation proof. Existing opcodes `1..=4` and the 256-byte `ControlHeader` layout are unchanged. - Scheduler and lifecycle verification (`helios/src/async_transfer/scheduler.rs`, `helios/src/async_transfer/lifecycle_tests.rs`, `verification/helios-lifecycle/AsyncTransfer.tla`, `AsyncTransfer.cfg`, `verification/helios-lifecycle/check.py`): - Before: `TransferScheduler` tracked IO and H2D DMA queues only, dispatching background work up to `max_bg_io`/`max_bg_dma` even when demand work was already in flight. - After: added `d2h_queues`, `inflight_d2h` (`InflightD2h` with `faulted` and `hardware_signaled`), `with_max_d2h`, `pop_next_d2h`, `mark_d2h_faulted`, and `complete_d2h`, and gated background IO/DMA dispatch so background work yields while any demand op is in flight. Updated `can_release_memory`, `advance_epoch`, `begin_drain`, and `finish_drain` to account for D2H ownership and drain. Extended `AsyncTransfer.tla` (20-element projection, `MaxD2h = 1`, `DispatchD2h`/`CompleteD2h`/`MarkD2hFaulted`), switched `lifecycle_tests.rs` to BFS with a test-only `queue_shape_key()` so priority and bounce classes are never collapsed during exploration, and added TLA+ and Rust mutations for D2H drain and fault-sentinel safety. - Transfer worker (`helios/src/async_transfer/worker.rs`): - Before: one normal-priority `copy_stream` executed all H2D copies, bounce staging capped at 16 slots within 256 MiB, storage reads entered queues in unrotated ring order, and the worker spun for a short fixed iteration count before sleeping. - After: split Copy Engine execution across a high-priority `copy_stream` (demand H2D and host-initiated signals), a normal-priority `bg_copy_stream` (background H2D), and a normal-priority `d2h_stream` (`Opcode::DevToHost`). Added `cuStreamWaitEvent` cross-stream serialization whenever different streams reuse an active completion slot, plus per-slot monotonic `stream_comp_max` tracking so priority preemption cannot regress `device_completions` backwards (matching host `fetch_max` monotonicity). Preserved faulted-DMA retention and `host_mirror_on_drain` across all three streams, widened `bounce_pool_geometry` to up to 32 slots within 512 MiB, added a 50 ms active spin window before backing off, rotated contiguous same-priority storage-read runs by worker ordinal before enqueueing (keeping `inflight_io` FIFO order aligned with `io_uring` SQ submission), and bound the `io_uring` ring plus registered host buffers on the worker thread before publishing `ChannelState::Running`. - Linux `io_uring` backend (`helios/src/async_transfer/io_backend.rs`): - Before: created the ring on the preparing thread without `DEFER_TASKRUN` or registered buffers and submitted plain `opcode::Read` SQEs. - After: added `bind_worker_thread()` (`setup_single_issuer`, `setup_defer_taskrun`, `setup_taskrun_flag`, `setup_no_sqarray` with kernel fallbacks), `register_buffers()` (1 GiB fixed-buffer chunks covering `HOST_POOL` and `bounce_pool` for `opcode::ReadFixed`, falling back to `opcode::Read` if kernel registration fails), and `taskrun() || cq_overflow()` plus a periodic `IORING_ENTER_GETEVENTS` watchdog in `poll_completions()` guarded by `self.queued_sqes == 0` so unsubmitted SQEs never flush outside `flush_queued_sqes` accounting. - Host-wide `--pool-ram-memory`, UVA page-table reserve, and parallel startup (`selene/src/offload.rs`, `helios/src/runtime_core/memory.rs`, `helios/src/runtime_core/model.rs`, `docs/cli-design.md`, `docs/runtime-core-design.md`, `helios/manifest.md`): - Before: `async_transfer_host_ram` always applied Selene's implicit host reserve and divided available/total RAM by `discrete_ranks` before applying `pool_ram_limit`, reserved `pinned / 512` VRAM per rank, and started rank channels sequentially. - After: added `host_pool_budget_and_total_with_reserve` in Selene (omitting the implicit host reserve when `--pool-ram-memory` is explicitly set), applied `--pool-ram-memory` host-wide before dividing across discrete ranks (subtracting host bounce bytes under `MemoryLimit::Reserve` so the full requested reserve stays free), charged aggregate peer-UVA page tables `pinned * discrete_ranks / 512` on discrete multi-rank hosts (leaving integrated unified-DRAM sizing and `host_future` coordination unchanged), started all rank workers concurrently via `std::thread::scope` in `NativeModel::prepare_async_transfers`, and updated the design and CLI specifications to match. Claimed benefit and result: - Enables full-duplex `DevToHost` demotion, priority-isolated demand vs background H2D execution, fixed-buffer `DEFER_TASKRUN` storage reads, accurate host-wide `--pool-ram-memory` budgeting, and concurrent multi-rank channel startup while keeping existing cores and ABI v1 headers compatible. - Isolated runtime measurement on 8x RTX PRO 6000 Blackwell (SM120 TP8, 8-drive PCIe Gen5 NVMe RAID-0, 251.1 GiB host RAM, `--pool-ram-memory -8G`, Kimi K3.1 Pro offloaded core): enabling worker-owned `DEFER_TASKRUN` reduced cross-rank demand-stall spread from >5,000 ms to 1,202 ms (37.75-38.95 s across all 8 ranks). End-to-end throughput gains from exclusive 2Q VRAM/RAM tiering depend on the companion `local-inference-lab/hyperflare-recipes` changes and are not attributed to this commit alone. Supporting evidence and limitations: - Formal lifecycle verification (`python3 verification/helios-lifecycle/check.py --tlc-jar tla2tools-1.7.4.jar --target-dir flare-cli/target --mutations`): passed (exit 0). `AsyncTransfer.tla` checked 1,847,851 generated states (125,668 distinct states, depth 24, 0 errors); 4,410 observed Rust scheduler transitions conformed to `AsyncTransfer.tla`; all 10 TLA+ models, 9 conformance suites, and 64/64 TLA+, observed-edge, and Rust mutations passed. - Rust test suites (`--locked --release`): - `eos`: 12 passed, 0 failed. - `selene` (`--features test-support`): 649 passed, 0 failed. - `selene-manager` (`--features test-support`): 448 passed, 0 failed, 1 ignored. - `flare`: 255 passed, 0 failed, 4 ignored. - `flare-cli`: 254 passed, 0 failed, 3 ignored. - `helios` (`--features runtime-core,server`): targeted `async_transfer::`, `runtime_core::memory::`, and `runtime_core::model::` passed 60/60 with `RUSTFLAGS="-D warnings"`; full `--lib` passed 1,973 tests and all integration targets (`actual_qwen38_tp2`, `deepseek_encoder`, `deepseek_output`, `message_boundaries` 14/14, `unverified_empty`) passed. - `RUSTFLAGS="-D warnings" cargo check --locked --release` passed for `flare-cli --features roce` and `heliopause`. - Live SM120 GPU verification: - Single-GPU CUDA test (`CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1` `async_transfer::worker::cuda_tests::live_cuda_async_transfer_end_to_end`): passed, exercising `DevToHost` round-trip, `bg_copy_stream` to `copy_stream` same-slot reuse, simultaneous `Prefetch`+`Demand` preemption monotonic non-regression on `device_completions`, `io_uring` `DEFER_TASKRUN` + `ReadFixed`, bounce staging, `IoFailure` sentinels, and `ControlRegionGuard`. - Live 8-GPU SM120 TP8 smoke test (`flare run` on GPUs `0,2,4,6,8,10,12,14`, `--pool-ram-memory -8G`, Kimi K3.1 Pro offloaded core): passed with 2,198,299 submitted/completed async transfers, 0 errors, 0 rejections, 0 cancellations, and clean 9.1 s shutdown drain. - Unrun checks and limitations: - `cargo-kani` is not installed locally; `kani_proofs.rs` was updated and compiled in tests, while CBMC proof execution awaits CI. - 6 `helios --lib` template tests (`prepared_templates_*`, `qwen_content_macro_*`, `recipe_templates_*`, `compatibility_requires_*`, `messages_image_hints_*`) failed locally because fetching `meta-models/Muse-Spark-Open-816B-A42B-NVFP4` returns HTTP 403. - Non-Linux (`pread`) and Windows paths were not exercised on this Linux host. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b Signed-off-by: Luke Alonso --- docs/cli-design.md | 2 +- docs/runtime-core-design.md | 41 +- helios/manifest.md | 27 +- helios/src/async_transfer/io_backend.rs | 267 +++++- helios/src/async_transfer/kani_proofs.rs | 20 + helios/src/async_transfer/lifecycle_tests.rs | 194 +++- helios/src/async_transfer/ring.rs | 73 ++ helios/src/async_transfer/scheduler.rs | 276 +++++- helios/src/async_transfer/worker.rs | 841 +++++++++++++++--- helios/src/runtime_core/driver.rs | 4 + helios/src/runtime_core/memory.rs | 117 ++- helios/src/runtime_core/model.rs | 30 +- selene/src/offload.rs | 8 +- .../helios-lifecycle/AsyncTransfer.cfg | 1 + .../helios-lifecycle/AsyncTransfer.tla | 88 +- verification/helios-lifecycle/check.py | 48 +- 16 files changed, 1769 insertions(+), 268 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 73808feb7..d07791b9b 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -758,7 +758,7 @@ Help exits with status 0; usage errors go to stderr with status 2. Its options a | `--kv-cache-limit concurrency\|context\|memory` | Bound shared KV history by prepared context times selected concurrency, one prepared context, or available memory | `memory` | | `--memory-limit LIMIT` | Per-GPU occupied size (`30G`), free-memory reserve (`-30G`, including `-0G`), or fraction of total memory (`0.8`) | `[memory] reserve`, otherwise core serving reserve | | `--pool-vram-memory LIMIT` | Per-GPU ceiling for runtime-sized `Capacity::DEVICE_POOL` allocations on cores declaring async transfer pools: nonnegative size (`0`, `12G`), free-memory reserve (`-8G`), or fraction of total GPU memory (`0.25`); ignored on cores without `DEVICE_POOL` allocations | `[memory] pool_vram`, otherwise available VRAM above minimum KV reserve | -| `--pool-ram-memory LIMIT` | Per-rank ceiling for runtime-sized pinned `AsyncTransfer` host pools on cores declaring `Execution.async_transfers`: nonnegative size (`0`, `32G`), free-memory reserve (`-16G`), or fraction of total host RAM (`0.5`); ignored on cores without async transfer channels | `[memory] pool_ram`, otherwise available host RAM | +| `--pool-ram-memory LIMIT` | Per-host ceiling for runtime-sized pinned `AsyncTransfer` host pools on cores declaring `Execution.async_transfers` (divided evenly across local discrete ranks): nonnegative size (`0`, `32G`), free-memory reserve (`-16G`), or fraction of total host RAM (`0.5`); ignored on cores without async transfer channels | `[memory] pool_ram`, otherwise available host RAM | | `--mtp-draft-tokens N` | Reduce the maximum draft count; zero selects ordinary execution without draft generation, absorption, or draft-state maintenance | Core default | | `--mtp-adaptive-verification` / `--no-mtp-adaptive-verification` | Adaptive or fixed selection among captured widths | Core default | | `--mtp-adaptive-verification-alpha ALPHA` | Positive finite exponent on completed prefix-survival scheduling scores; below 1 favors longer verification prefixes | `1.0` | diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index c59a626d6..763c7d522 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -729,13 +729,17 @@ When a core declares `Capacity::DEVICE_POOL` allocations and `Execution.async_transfers` channels, `NativeModel` rejects cores whose graphs also contain Copy Engine `Memory::Peer` copy nodes at load time, preventing unbounded Copy Engine deadlocks when in-graph demand transfers cannot yield to -`CopyEngineGate`. During `allocate_caches`, discrete-GPU ranks reserve host RAM +`CopyEngineGate`. During `allocate_caches`, discrete-GPU ranks read host RAM after subtracting planned prefix-cache offload and vision input windows -(`host_future`), reserve `pinned_bytes.div_ceil(512) + 256 MiB` of VRAM per -rank for `cuMemHostRegister_v2` GPU MMU page tables and worker streams -(covering each channel's planned pinned `HOST_POOL` and bounded internal bounce -pool, which is disabled when channel alignment exceeds 32 MiB), and deduct the -pinned host reservation from prefix-cache capture growth. On integrated +(`host_future`, omitting Selene's implicit host reserve when `--pool-ram-memory` +is explicitly configured), apply `--pool-ram-memory` host-wide before dividing +across local discrete ranks, reserve +`pinned_bytes.saturating_mul(discrete_ranks).div_ceil(512) + 256 MiB` of VRAM +per rank for aggregate multi-rank UVA `cuMemHostRegister_v2` GPU MMU page tables +and worker streams (covering each channel's planned pinned `HOST_POOL` and +bounded internal bounce pool, which is disabled when channel alignment exceeds +32 MiB), and deduct the pinned host reservation from prefix-cache capture +growth. On integrated unified-DRAM GPUs (such as GB10 and Jetson), `HOST_POOL`, `bounce_pool`, `DEVICE_POOL`, and KV caches draw from the same physical DRAM: `HOST_POOL` defaults to zero unless `--pool-ram-memory` is explicitly configured, explicit @@ -753,16 +757,21 @@ and opens the 4 KiB-aligned `RankBody.external_extents` payload segments directly (`O_DIRECT` on Linux), allocates each channel's runtime-sized pinned `HOST_POOL` (clamped to the planned per-rank host ceiling from `allocate_caches`, with an internal pinned bounce pool when enabled), writes -immutable startup geometry into the mapped-host `ControlHeader`, and blocks in -`start()` until each channel worker binds its CUDA context, allocates its event -pool, and publishes `ControlHeader.worker_state = Running` before executing -`Execution.tuning_graphs`. All device completion writes serialize on the -channel's single Copy Engine stream, host completion mirrors advance -monotonically via `fetch_max`, and storage or CUDA transfer failures publish -the bit-63 fault sentinel (`COMPLETION_ERROR_BIT | error_code`) rather than the -caller's requested success cookie. Partial DMA submission failures after -`cuMemcpyHtoDAsync_v2` retain their in-flight and bounce-slot ownership until -hardware stream drain is confirmed. Shutdown stops and drains all async +immutable startup geometry into the mapped-host `ControlHeader`, and starts all +rank workers concurrently, blocking in `start()` until each channel worker binds +its CUDA context, initializes its worker-owned `io_uring` ring (`SINGLE_ISSUER` +and `DEFER_TASKRUN` with fixed-buffer `ReadFixed` registration on Linux when +supported), creates its high-priority demand H2D, normal-priority background +H2D, and normal-priority D2H Copy Engine streams plus event pool, and publishes +`ControlHeader.worker_state = Running` before executing +`Execution.tuning_graphs`. Demand H2D, background H2D, and D2H transfers +execute on separate non-blocking Copy Engine streams (with `cuStreamWaitEvent` +serializing cross-stream reuse of the same completion slot), host completion +mirrors advance monotonically via `fetch_max`, and storage or CUDA transfer +failures publish the bit-63 fault sentinel (`COMPLETION_ERROR_BIT | error_code`) +rather than the caller's requested success cookie. Partial DMA submission +failures after `cuMemcpyHtoDAsync_v2` or `cuMemcpyDtoHAsync_v2` retain their +in-flight and bounce-slot ownership until hardware stream drain is confirmed. Shutdown stops and drains all async transfer channels after compute streams drain (bounding Linux `io_uring` waits with a kernel timespec), invalidates mapped-host control telemetry before unmapping device or mapped-host storage, and on unconfirmed drain transitions diff --git a/helios/manifest.md b/helios/manifest.md index db630fb97..9c6826d14 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -170,8 +170,8 @@ runtime-sized `Capacity::DEVICE_POOL` allocations and authenticated graphs to a stateless, domain-agnostic host transfer worker that copies 4 KiB-aligned read-only extents from core storage (`O_DIRECT` + `io_uring` on Linux, `pread` elsewhere) through an optional runtime-sized pinned host byte -pool (`HOST_POOL`) and a dedicated non-blocking CUDA Copy Engine stream into a -`Capacity::DEVICE_POOL` device byte pool (`DEVICE_POOL`). +pool (`HOST_POOL`) and dedicated non-blocking CUDA Copy Engine streams into and +out of a `Capacity::DEVICE_POOL` device byte pool (`DEVICE_POOL`). Each `AsyncTransfer` entry declares: @@ -187,27 +187,34 @@ Each `AsyncTransfer` entry declares: completion words. - `device_completions` (optional): 8-byte-aligned `Reference` inside a fixed `Memory::Device` allocation holding `completion_slots` 64-bit completion - words written in stream order on the channel's single Copy Engine stream by + words written in stream order on the transfer's CUDA Copy Engine stream by `cuStreamWriteValue64_v2` (when device attribute `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is supported) after - Copy Engine DMA completes, with monotonic `fetch_max` host completion mirrors - so deferred DMA mirrors cannot regress reused completion slots. + Copy Engine DMA completes (using `cuStreamWaitEvent` whenever different Copy + Engine streams reuse the same completion slot), with monotonic `fetch_max` + host completion mirrors so deferred DMA mirrors cannot regress reused + completion slots. - `max_host_pool_bytes`: optional ceiling on the channel's pinned host pool (`0` disables the host pool). - `alignment`: power-of-two direct-I/O and offset alignment (`>= 4096`). Supported command opcodes are `DISK_TO_HOST` (`1`), `HOST_TO_DEV` (`2`), `DISK_TO_DEV` (`3`, supporting either a caller host offset or sentinel -`u64::MAX` for internal pinned bounce staging when `host_pool_bytes == 0`), and -`CANCEL_EPOCH` (`4`). Priorities `DEMAND` (`0`), `PREFETCH` (`1`), and `WARM` -(`2`) feed a preemptible host queue with bounded background I/O and DMA depth; +`u64::MAX` for internal pinned bounce staging when `host_pool_bytes == 0`), +`CANCEL_EPOCH` (`4`), and `DEV_TO_HOST` (`5`, copying a byte range from +`DEVICE_POOL` back to `HOST_POOL` on a dedicated device-to-host Copy Engine +stream). Priorities `DEMAND` (`0`), `PREFETCH` (`1`), and `WARM` +(`2`) feed a preemptible host queue with bounded background I/O and DMA depth +(with demand H2D copies dispatched on a high-priority Copy Engine stream and +background H2D copies dispatched on a normal-priority Copy Engine stream); `CANCEL_EPOCH` and `ControlHeader.active_epoch` drop queued non-demand commands from older epochs while preserving `DEMAND`. Caller-supplied `signal_value` cookies occupy the lower 63 bits (`(signal_value & (1 << 63)) == 0`); bit 63 (`COMPLETION_ERROR_BIT`) is reserved for fault sentinels (`COMPLETION_ERROR_BIT | error_code`) emitted on `IoFailure` or `CudaFailure` instead of the requested success value. Helios waits for each channel worker to -bind its CUDA context, create its event pool, and publish +bind its CUDA context, initialize its worker-owned I/O backend, create its Copy +Engine streams and event pool, and publish `ControlHeader.worker_state = Running` before launching `Execution.tuning_graphs` so startup tuning kernels read populated `device_pool_bytes` and `host_pool_bytes` from `ControlHeader` and observe a @@ -216,7 +223,7 @@ containing Copy Engine `Memory::Peer` copy nodes are rejected at load time, because in-graph demand waits cannot serialize behind `CopyEngineGate` without deadlocking the Copy Engine. Teardown drains serving streams, cancels queued background transfers, drains in-flight storage I/O (bounded by a kernel timespec -on `io_uring`) and the Copy Engine stream within a bounded timeout, invalidates +on `io_uring`) and all Copy Engine streams within a bounded timeout, invalidates mapped-host control telemetry before unmapping allocations, and retains pinned host memory, storage handles, and CUDA handles until process exit if drain is not confirmed. diff --git a/helios/src/async_transfer/io_backend.rs b/helios/src/async_transfer/io_backend.rs index 65f0ca39a..40cff22c5 100644 --- a/helios/src/async_transfer/io_backend.rs +++ b/helios/src/async_transfer/io_backend.rs @@ -24,6 +24,24 @@ pub struct IoCompletion { /// Non-blocking direct-I/O reader driving storage transfers into pinned host memory. pub trait IoBackend: Send { + /// Bind the backend to the dedicated worker thread before any reads are submitted. + /// + /// On Linux this recreates the `io_uring` instance on the worker thread with single-issuer + /// deferred task-work flags (`IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN`) so + /// completions avoid inter-processor interrupts. + fn bind_worker_thread(&mut self) -> io::Result<()> { + Ok(()) + } + + /// Optionally register fixed host buffer regions (e.g. pinned host and bounce pools) so + /// direct-I/O reads avoid per-read kernel page-pinning (`pin_user_pages`). + /// + /// # Safety + /// Every `(ptr, len)` slice must remain mapped and live until this backend is dropped. + unsafe fn register_buffers(&mut self, _regions: &[(*mut u8, usize)]) -> io::Result<()> { + Ok(()) + } + /// Enqueue one aligned read of `nbytes` bytes from `file_index` at `file_offset` into `dst`. /// /// # Safety @@ -65,15 +83,19 @@ pub mod linux_uring { use std::{collections::HashMap, os::fd::AsRawFd}; const RING_ENTRIES: u32 = 128; + const FIXED_BUF_CHUNK_BYTES: usize = 1 << 30; + const IORING_ENTER_GETEVENTS: u32 = 1; - /// Linux `io_uring` direct-I/O reader with registered fixed file descriptors. + /// Linux `io_uring` direct-I/O reader with registered fixed file descriptors and fixed buffers. pub struct IoUringBackend { ring: IoUring, _files: Vec, registered_files: bool, raw_fds: Vec, + fixed_bufs: Vec<(usize, usize)>, expected: HashMap, queued_sqes: usize, + empty_polls: u32, } // SAFETY: One worker thread exclusively owns `IoUringBackend`, its file handles, and its ring. @@ -94,11 +116,56 @@ pub mod linux_uring { _files: files, registered_files, raw_fds, + fixed_bufs: Vec::new(), expected: HashMap::new(), queued_sqes: 0, + empty_polls: 0, }) } + fn build_worker_ring() -> Option { + // Prefer single-issuer deferred taskrun (Linux >= 6.1) to eliminate NVMe completion + // IPIs on busy worker threads; fall back gracefully on older kernels. + if let Ok(ring) = IoUring::builder() + .setup_single_issuer() + .setup_defer_taskrun() + .setup_taskrun_flag() + .setup_no_sqarray() + .build(RING_ENTRIES) + { + return Some(ring); + } + if let Ok(ring) = IoUring::builder() + .setup_single_issuer() + .setup_defer_taskrun() + .setup_taskrun_flag() + .build(RING_ENTRIES) + { + return Some(ring); + } + if let Ok(ring) = IoUring::builder() + .setup_single_issuer() + .setup_coop_taskrun() + .setup_taskrun_flag() + .build(RING_ENTRIES) + { + return Some(ring); + } + None + } + + #[inline] + fn find_fixed_buf(&self, dst: *mut u8, nbytes: usize) -> Option { + let start = dst as usize; + let end = start.checked_add(nbytes)?; + for (idx, &(b_start, b_end)) in self.fixed_bufs.iter().enumerate() { + if start >= b_start && end <= b_end { + return u16::try_from(idx).ok(); + } + } + None + } + fn push_read_sqe( &mut self, op_id: OpId, @@ -107,20 +174,38 @@ pub mod linux_uring { dst: *mut u8, nbytes: u32, ) -> io::Result<()> { - let entry = if self.registered_files { - opcode::Read::new(types::Fixed(file_index), dst, nbytes) - .offset(file_offset) - .build() - .user_data(op_id) - } else { - let fd = *self - .raw_fds - .get(file_index as usize) - .ok_or(io::ErrorKind::InvalidInput)?; - opcode::Read::new(types::Fd(fd), dst, nbytes) + let fixed_buf = self.find_fixed_buf(dst, nbytes as usize); + let entry = match (self.registered_files, fixed_buf) { + (true, Some(buf_index)) => { + opcode::ReadFixed::new(types::Fixed(file_index), dst, nbytes, buf_index) + .offset(file_offset) + .build() + .user_data(op_id) + } + (true, None) => opcode::Read::new(types::Fixed(file_index), dst, nbytes) .offset(file_offset) .build() - .user_data(op_id) + .user_data(op_id), + (false, Some(buf_index)) => { + let fd = *self + .raw_fds + .get(file_index as usize) + .ok_or(io::ErrorKind::InvalidInput)?; + opcode::ReadFixed::new(types::Fd(fd), dst, nbytes, buf_index) + .offset(file_offset) + .build() + .user_data(op_id) + } + (false, None) => { + let fd = *self + .raw_fds + .get(file_index as usize) + .ok_or(io::ErrorKind::InvalidInput)?; + opcode::Read::new(types::Fd(fd), dst, nbytes) + .offset(file_offset) + .build() + .user_data(op_id) + } }; // Flush once if the submission queue is momentarily full. if self.ring.submission().is_full() { @@ -170,6 +255,73 @@ pub mod linux_uring { } impl IoBackend for IoUringBackend { + fn bind_worker_thread(&mut self) -> io::Result<()> { + if !self.expected.is_empty() || !self.fixed_bufs.is_empty() { + return Ok(()); + } + if let Some(ring) = Self::build_worker_ring() { + let registered_files = if self.raw_fds.is_empty() { + false + } else { + ring.submitter().register_files(&self.raw_fds).is_ok() + }; + self.ring = ring; + self.registered_files = registered_files; + } + Ok(()) + } + + unsafe fn register_buffers(&mut self, regions: &[(*mut u8, usize)]) -> io::Result<()> { + let mut iovecs: Vec = Vec::new(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for &(ptr, len) in regions { + if ptr.is_null() || len == 0 { + continue; + } + let mut off = 0usize; + while off < len && iovecs.len() < (u16::MAX as usize) { + let chunk = (len - off).min(FIXED_BUF_CHUNK_BYTES); + let base = unsafe { ptr.add(off) }; + iovecs.push(libc::iovec { + iov_base: base.cast(), + iov_len: chunk, + }); + spans.push((base as usize, (base as usize).saturating_add(chunk))); + off += chunk; + } + } + if iovecs.is_empty() { + return Ok(()); + } + // Best-effort fixed-buffer registration: if RLIMIT_MEMLOCK refuses pinning the full + // pool, retry smaller regions (e.g. bounce pool) and fall back cleanly to Read. + match unsafe { self.ring.submitter().register_buffers(&iovecs) } { + Ok(()) => { + self.fixed_bufs = spans; + Ok(()) + } + Err(_) => { + let mut small_iovecs = Vec::new(); + let mut small_spans = Vec::new(); + for &(ptr, len) in regions { + if !ptr.is_null() && len > 0 && len <= FIXED_BUF_CHUNK_BYTES { + small_iovecs.push(libc::iovec { + iov_base: ptr.cast(), + iov_len: len, + }); + small_spans.push((ptr as usize, (ptr as usize).saturating_add(len))); + } + } + if !small_iovecs.is_empty() + && unsafe { self.ring.submitter().register_buffers(&small_iovecs) }.is_ok() + { + self.fixed_bufs = small_spans; + } + Ok(()) + } + } + } + unsafe fn submit_read( &mut self, op_id: OpId, @@ -197,8 +349,44 @@ pub mod linux_uring { } fn poll_completions(&mut self, out: &mut Vec) -> io::Result<()> { + // Under DEFER_TASKRUN / COOP_TASKRUN+TASKRUN_FLAG, checking `taskrun()` is a single + // userspace load on the shared SQ flags; only enter the kernel when work is pending + // and no staged SQEs await explicit `flush()` (so `pending_submissions()` stays exact). + if self.queued_sqes == 0 && !self.expected.is_empty() { + let needs_enter = { + let sq = self.ring.submission(); + sq.taskrun() || sq.cq_overflow() + }; + if needs_enter { + self.empty_polls = 0; + for _ in 0..MAX_EINTR_RETRIES { + match self.ring.submit() { + Ok(_) => break, + Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue, + Err(_) => break, + } + } + } else { + self.empty_polls = self.empty_polls.wrapping_add(1); + if (self.empty_polls & 0x3fff) == 0 { + // SAFETY: `enter(0, 0, IORING_ENTER_GETEVENTS, None)` passes no pointer + // arguments and safely drains any deferred task work without blocking. + let _ = unsafe { + self.ring.submitter().enter::( + 0, + 0, + IORING_ENTER_GETEVENTS, + None, + ) + }; + } + } + } else { + self.empty_polls = 0; + } let mut cq = self.ring.completion(); for cqe in &mut cq { + self.empty_polls = 0; let op_id = cqe.user_data(); if op_id == 0 { // Internal cancel SQE completion. @@ -470,4 +658,57 @@ mod tests { assert_eq!(eintr_calls, 16); assert_eq!(queued, 2); } + + #[test] + fn io_uring_bind_worker_thread_and_register_buffers_read_fixed() { + use std::io::Write; + let path = std::env::temp_dir().join(format!( + "flare-uring-defer-taskrun-test-{}.bin", + std::process::id() + )); + let payload: Vec = (0..8192u32) + .map(|i| (i.wrapping_mul(37).wrapping_add(11) & 0xff) as u8) + .collect(); + { + let mut f = File::create(&path).expect("create test file"); + f.write_all(&payload).expect("write test payload"); + f.sync_all().expect("sync test file"); + } + let f = File::open(&path).expect("open test file"); + let mut backend = IoUringBackend::new(vec![f]).expect("create io_uring backend"); + let handle = std::thread::spawn(move || { + backend + .bind_worker_thread() + .expect("bind worker thread ring"); + let mut buf = vec![0u8; 8192]; + unsafe { + backend + .register_buffers(&[(buf.as_mut_ptr(), buf.len())]) + .expect("register fixed buffer"); + backend + .submit_read(42, 0, 0, buf.as_mut_ptr(), 4096) + .expect("submit first read"); + backend + .submit_read(43, 0, 4096, buf.as_mut_ptr().add(4096), 4096) + .expect("submit second read"); + } + backend.flush().expect("flush reads"); + let mut done: Vec = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + while done.len() < 2 && Instant::now() < deadline { + backend + .poll_completions(&mut done) + .expect("poll completions"); + if done.len() < 2 { + std::thread::yield_now(); + } + } + (done, buf) + }); + let (done, buf) = handle.join().expect("worker thread join"); + let _ = std::fs::remove_file(&path); + assert_eq!(done.len(), 2); + assert!(done.iter().all(|c| c.ok)); + assert_eq!(buf, payload); + } } diff --git a/helios/src/async_transfer/kani_proofs.rs b/helios/src/async_transfer/kani_proofs.rs index dfeb008da..928219bdd 100644 --- a/helios/src/async_transfer/kani_proofs.rs +++ b/helios/src/async_transfer/kani_proofs.rs @@ -196,6 +196,26 @@ fn validate_command_guarantees_bounds_and_alignment_for_all_inputs() { assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); } } + Ok(ValidatedCommand::DevToHost { + priority, + host_offset, + device_offset, + nbytes, + completion_slot, + signal_value, + .. + }) => { + assert_eq!(cmd.opcode, Opcode::DevToHost as u32); + assert!(Priority::from_u32(cmd.priority) == Some(priority)); + assert!(alignment >= MIN_ALIGNMENT && alignment.is_power_of_two()); + assert!(nbytes > 0); + assert!((host_offset as u128) + (nbytes as u128) <= (host_pool_bytes as u128)); + assert!((device_offset as u128) + (nbytes as u128) <= (device_pool_bytes as u128)); + if let Some(slot) = completion_slot { + assert!(slot < completion_slots); + assert_eq!(signal_value & COMPLETION_ERROR_BIT, 0); + } + } Ok(ValidatedCommand::DiskToDev { priority, extent, diff --git a/helios/src/async_transfer/lifecycle_tests.rs b/helios/src/async_transfer/lifecycle_tests.rs index a65a36d16..e300158d0 100644 --- a/helios/src/async_transfer/lifecycle_tests.rs +++ b/helios/src/async_transfer/lifecycle_tests.rs @@ -6,7 +6,11 @@ //! Bounded trace conformance against `verification/helios-lifecycle/AsyncTransfer.tla`. -use std::{collections::BTreeSet, fs, path::Path}; +use std::{ + collections::{BTreeSet, VecDeque}, + fs, + path::Path, +}; use super::{ ring::{ @@ -16,12 +20,12 @@ use super::{ scheduler::TransferScheduler, }; -/// Compact 16-integer projection shared with `AsyncTransfer.tla`. +/// Compact 20-integer projection shared with `AsyncTransfer.tla`. /// /// `[phase, active_epoch, q_io, q_dma, in_dem_io, in_bg_io, in_dem_dma, in_bg_dma, /// b_in_io, b_q_dma, b_in_dma, free_bounce, can_release, faulted_dma, unflushed_io, -/// hw_signaled_faulted]` -type Projection = [i64; 16]; +/// hw_signaled_faulted, q_d2h, in_d2h, faulted_d2h, hw_signaled_faulted_d2h]` +type Projection = [i64; 20]; fn project(sched: &TransferScheduler) -> Projection { let in_bg_io = sched.bg_io_inflight(); @@ -45,6 +49,10 @@ fn project(sched: &TransferScheduler) -> Projection { sched.faulted_dma_count() as i64, sched.unflushed_io_count() as i64, sched.hw_signaled_faulted_dma_count() as i64, + sched.queued_d2h_count() as i64, + sched.inflight_d2h_count() as i64, + sched.faulted_d2h_count() as i64, + sched.hw_signaled_faulted_d2h_count() as i64, ] } @@ -71,6 +79,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { let max_bg_io = 1usize; let max_total_dma = 2usize; let max_bg_dma = 1usize; + let max_d2h = 1usize; let bounce_slots = 1usize; let initial = TransferScheduler::new( @@ -79,14 +88,16 @@ fn async_transfer_scheduler_matches_lifecycle_model() { max_total_dma, max_bg_dma, bounce_slots, - ); + ) + .with_max_d2h(max_d2h); let mut edges: BTreeSet<(Projection, i64, Projection)> = BTreeSet::new(); - let mut visited: BTreeSet<(Projection, usize, usize)> = BTreeSet::new(); - let mut frontier: Vec<(TransferScheduler, Vec, Vec, usize)> = - vec![(initial, Vec::new(), Vec::new(), 0)]; + let mut visited: BTreeSet<(Projection, (usize, usize, usize, usize), usize, usize, usize)> = + BTreeSet::new(); + let mut frontier: VecDeque<(TransferScheduler, Vec, Vec, Vec, usize)> = + VecDeque::from([(initial, Vec::new(), Vec::new(), Vec::new(), 0)]); - while let Some((sched, io_ids, dma_ids, depth)) = frontier.pop() { + while let Some((sched, io_ids, dma_ids, d2h_ids, depth)) = frontier.pop_front() { let before = project(&sched); // Core safety assertions on every reachable Rust state. assert!( @@ -99,19 +110,31 @@ fn async_transfer_scheduler_matches_lifecycle_model() { ); assert!(sched.inflight_io_count() <= max_total_io); assert!(sched.inflight_dma_count() <= max_total_dma); + assert!(sched.inflight_d2h_count() <= max_d2h); assert!( sched.faulted_dma_count() <= sched.inflight_dma_count(), "faulted DMA count exceeded inflight DMA count" ); + assert!( + sched.faulted_d2h_count() <= sched.inflight_d2h_count(), + "faulted D2H count exceeded inflight D2H count" + ); assert!( sched.hw_signaled_faulted_dma_count() <= sched.faulted_dma_count(), "hw-signaled faulted DMA count exceeded faulted DMA count" ); + assert!( + sched.hw_signaled_faulted_d2h_count() <= sched.faulted_d2h_count(), + "hw-signaled faulted D2H count exceeded faulted D2H count" + ); assert!( sched.unflushed_io_count() <= sched.inflight_io_count(), "unflushed IO count exceeded inflight IO count" ); - if sched.faulted_dma_count() > 0 || sched.unflushed_io_count() > 0 { + if sched.faulted_dma_count() > 0 + || sched.faulted_d2h_count() > 0 + || sched.unflushed_io_count() > 0 + { assert!( !sched.can_release_memory(), "faulted DMA and unflushed IO must retain inflight and bounce ownership" @@ -125,7 +148,10 @@ fn async_transfer_scheduler_matches_lifecycle_model() { bounce_slots, "bounce slot conservation violated" ); - if sched.inflight_io_count() > 0 || sched.inflight_dma_count() > 0 { + if sched.inflight_io_count() > 0 + || sched.inflight_dma_count() > 0 + || sched.inflight_d2h_count() > 0 + { assert!( !sched.can_release_memory(), "in-flight work must block memory release" @@ -140,6 +166,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { if sched.state() == ChannelState::Stopped { assert_eq!(sched.inflight_io_count(), 0); assert_eq!(sched.inflight_dma_count(), 0); + assert_eq!(sched.inflight_d2h_count(), 0); assert_eq!( sched.free_bounce_count(), bounce_slots, @@ -151,28 +178,37 @@ fn async_transfer_scheduler_matches_lifecycle_model() { if depth >= 7 { continue; } - let key = (before, io_ids.len(), dma_ids.len()); + let key = ( + before, + sched.queue_shape_key(), + io_ids.len(), + dma_ids.len(), + d2h_ids.len(), + ); if !visited.insert(key) { continue; } - let mut push_next = - |action: i64, next: TransferScheduler, next_io: Vec, next_dma: Vec| { - let after = project(&next); - edges.insert((before, action, after)); - frontier.push((next, next_io, next_dma, depth + 1)); - }; + let mut push_next = |action: i64, + next: TransferScheduler, + next_io: Vec, + next_dma: Vec, + next_d2h: Vec| { + let after = project(&next); + edges.insert((before, action, after)); + frontier.push_back((next, next_io, next_dma, next_d2h, depth + 1)); + }; // 1. Start if sched.state() == ChannelState::Idle { let mut n = sched.clone(); n.start().unwrap(); - push_next(1, n, io_ids.clone(), dma_ids.clone()); + push_next(1, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } // 2. Enqueue commands while Running (bounded queue size for finite exploration). if sched.state() == ChannelState::Running - && sched.queued_io_count() + sched.queued_dma_count() < 2 + && sched.queued_io_count() + sched.queued_dma_count() + sched.queued_d2h_count() < 2 { for (prio, epoch) in [ (Priority::Demand, 0u64), @@ -189,7 +225,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { completion_slot: Some(0), signal_value: 1, }); - push_next(2, n, io_ids.clone(), dma_ids.clone()); + push_next(2, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); // HostToDev let mut n = sched.clone(); @@ -202,7 +238,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { completion_slot: Some(0), signal_value: 2, }); - push_next(2, n, io_ids.clone(), dma_ids.clone()); + push_next(2, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); // Fused DiskToDev (bounce slot) let mut n = sched.clone(); @@ -215,7 +251,20 @@ fn async_transfer_scheduler_matches_lifecycle_model() { completion_slot: Some(0), signal_value: 3, }); - push_next(2, n, io_ids.clone(), dma_ids.clone()); + push_next(2, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); + + // DevToHost + let mut n = sched.clone(); + n.enqueue(ValidatedCommand::DevToHost { + priority: prio, + host_offset: 0, + device_offset: 0, + nbytes: 4096, + epoch, + completion_slot: Some(0), + signal_value: 4, + }); + push_next(2, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } // 3. CancelEpoch (0 -> 1 -> 2) @@ -226,7 +275,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { completion_slot: None, signal_value: 0, }); - push_next(3, n, io_ids.clone(), dma_ids.clone()); + push_next(3, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } } @@ -239,7 +288,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } let mut n_io = io_ids.clone(); n_io.push(op.op_id); - push_next(4, n, n_io, dma_ids.clone()); + push_next(4, n, n_io, dma_ids.clone(), d2h_ids.clone()); } } @@ -252,7 +301,20 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } let mut n_dma = dma_ids.clone(); n_dma.push(op.op_id); - push_next(5, n, io_ids.clone(), n_dma); + push_next(5, n, io_ids.clone(), n_dma, d2h_ids.clone()); + } + } + + // 13. Dispatch D2H + { + let mut n = sched.clone(); + if let Some(op) = n.pop_next_d2h() { + if op.priority.is_background() { + assert!(op.epoch >= sched.active_epoch()); + } + let mut n_d2h = d2h_ids.clone(); + n_d2h.push(op.op_id); + push_next(13, n, io_ids.clone(), dma_ids.clone(), n_d2h); } } @@ -264,7 +326,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { let mut n = sched.clone(); let marked = n.mark_io_flushed(count); assert_eq!(marked, count); - push_next(12, n, io_ids.clone(), dma_ids.clone()); + push_next(12, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } } @@ -294,7 +356,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } let mut n_io = io_ids.clone(); n_io.remove(idx); - push_next(6, n, n_io, dma_ids.clone()); + push_next(6, n, n_io, dma_ids.clone(), d2h_ids.clone()); } } @@ -321,7 +383,34 @@ fn async_transfer_scheduler_matches_lifecycle_model() { } let mut n_dma = dma_ids.clone(); n_dma.remove(idx); - push_next(7, n, io_ids.clone(), n_dma); + push_next(7, n, io_ids.clone(), n_dma, d2h_ids.clone()); + } + } + + // 14. Complete any in-flight D2H + for (idx, &op_id) in d2h_ids.iter().enumerate() { + let was_faulted = sched.is_d2h_faulted(op_id); + for ok in [true, false] { + let mut n = sched.clone(); + let notice = n.complete_d2h(op_id, ok); + if was_faulted { + assert!( + notice.is_none(), + "already-faulted D2H must not emit a duplicate or success notice on drain" + ); + } else if !ok { + let notice = notice.expect("failed D2H must emit an error completion notice"); + assert_eq!(notice.error, ErrorCode::CudaFailure); + assert_eq!( + notice.signal_value, + completion_error_sentinel(ErrorCode::CudaFailure), + "failed transfer must signal error sentinel, not success value" + ); + assert_ne!(notice.signal_value & COMPLETION_ERROR_BIT, 0); + } + let mut n_d2h = d2h_ids.clone(); + n_d2h.remove(idx); + push_next(14, n, io_ids.clone(), dma_ids.clone(), n_d2h); } } @@ -370,7 +459,44 @@ fn async_transfer_scheduler_matches_lifecycle_model() { "faulted DMA must retain inflight and bounce ownership" ); assert!(!n.can_release_memory()); - push_next(11, n, io_ids.clone(), dma_ids.clone()); + push_next(11, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); + } + } + + // 15. Mark an in-flight D2H faulted after partial CUDA submission failure. + for &op_id in &d2h_ids { + if sched.is_d2h_faulted(op_id) { + continue; + } + for hardware_signaled in [false, true] { + let mut n = sched.clone(); + let notice = n + .mark_d2h_faulted(op_id, hardware_signaled) + .expect("unfaulted in-flight D2H must transition to faulted"); + assert_eq!(notice.error, ErrorCode::CudaFailure); + if hardware_signaled { + assert!( + notice.completion_slot.is_none(), + "hardware-signaled faulted D2H must not overwrite live/reused completion slot" + ); + } else { + assert!( + notice.completion_slot.is_some(), + "un-signaled faulted D2H must report its completion slot for error sentinel" + ); + assert_eq!( + notice.signal_value, + completion_error_sentinel(ErrorCode::CudaFailure), + "failed transfer must signal error sentinel, not success value" + ); + } + assert_eq!( + n.inflight_d2h_count(), + sched.inflight_d2h_count(), + "faulted D2H must retain inflight ownership" + ); + assert!(!n.can_release_memory()); + push_next(15, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } } } @@ -379,7 +505,7 @@ fn async_transfer_scheduler_matches_lifecycle_model() { if matches!(sched.state(), ChannelState::Idle | ChannelState::Running) { let mut n = sched.clone(); n.begin_drain().unwrap(); - push_next(8, n, io_ids.clone(), dma_ids.clone()); + push_next(8, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } // 9 / 10. FinishDrain (confirmed and unconfirmed) @@ -387,17 +513,17 @@ fn async_transfer_scheduler_matches_lifecycle_model() { for stream_drained in [true, false] { let mut n = sched.clone(); let res = n.finish_drain(stream_drained); - if stream_drained && io_ids.is_empty() && dma_ids.is_empty() { + if stream_drained && io_ids.is_empty() && dma_ids.is_empty() && d2h_ids.is_empty() { assert!(res.is_ok()); assert_eq!(n.state(), ChannelState::Stopped); - push_next(9, n, io_ids.clone(), dma_ids.clone()); + push_next(9, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } else { assert!( res.is_err(), "unconfirmed drain must not complete into Stopped" ); assert_eq!(n.state(), ChannelState::FailedDrain); - push_next(10, n, io_ids.clone(), dma_ids.clone()); + push_next(10, n, io_ids.clone(), dma_ids.clone(), d2h_ids.clone()); } } } diff --git a/helios/src/async_transfer/ring.rs b/helios/src/async_transfer/ring.rs index b2e94ab38..9010b4ffb 100644 --- a/helios/src/async_transfer/ring.rs +++ b/helios/src/async_transfer/ring.rs @@ -60,6 +60,8 @@ pub enum Opcode { DiskToDev = 3, /// Raise the active cancellation epoch, dropping queued non-demand commands from older epochs. CancelEpoch = 4, + /// Copy a byte range from the device pool to the runtime-sized host pool via Copy Engine DMA. + DevToHost = 5, } impl Opcode { @@ -70,6 +72,7 @@ impl Opcode { 2 => Some(Self::HostToDev), 3 => Some(Self::DiskToDev), 4 => Some(Self::CancelEpoch), + 5 => Some(Self::DevToHost), _ => None, } } @@ -253,6 +256,15 @@ pub enum ValidatedCommand { completion_slot: Option, signal_value: u64, }, + DevToHost { + priority: Priority, + host_offset: u64, + device_offset: u64, + nbytes: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, } /// Byte offset of the host completion-slot array inside the mapped-host control allocation. @@ -482,6 +494,27 @@ pub fn validate_command( signal_value: cmd.signal_value, }) } + Opcode::DevToHost => { + let (priority, _) = validate_transfer_header(cmd.priority, alignment)?; + if cmd.nbytes == 0 { + return Err(ErrorCode::LengthMismatch); + } + if !fits_range(cmd.host_offset, cmd.nbytes, host_pool_bytes) { + return Err(ErrorCode::HostRangeOutOfBounds); + } + if !fits_range(cmd.device_offset, cmd.nbytes, device_pool_bytes) { + return Err(ErrorCode::DeviceRangeOutOfBounds); + } + Ok(ValidatedCommand::DevToHost { + priority, + host_offset: cmd.host_offset, + device_offset: cmd.device_offset, + nbytes: cmd.nbytes, + epoch: cmd.epoch, + completion_slot, + signal_value: cmd.signal_value, + }) + } } } @@ -636,6 +669,46 @@ mod tests { completion_error_sentinel(ErrorCode::CudaFailure), COMPLETION_ERROR_BIT | (ErrorCode::CudaFailure as u64) ); + // DevToHost enforces nonzero length, host bounds, device bounds, and signal_value bit 63. + let mut d2h = TransferCommand { + opcode: Opcode::DevToHost as u32, + priority: Priority::Warm as u32, + extent_id: 0, + completion_slot: 2, + host_offset: 4096, + device_offset: 8192, + nbytes: 4096, + epoch: 3, + signal_value: 77, + _reserved: 0, + }; + assert!(matches!( + validate_command(&d2h, &extents, 16384, 16384, 8, 4096, 8192), + Ok(ValidatedCommand::DevToHost { + priority: Priority::Warm, + host_offset: 4096, + device_offset: 8192, + nbytes: 4096, + .. + }) + )); + d2h.nbytes = 0; + assert_eq!( + validate_command(&d2h, &extents, 16384, 16384, 8, 4096, 8192), + Err(ErrorCode::LengthMismatch) + ); + d2h.nbytes = 4096; + d2h.host_offset = 16384; + assert_eq!( + validate_command(&d2h, &extents, 16384, 16384, 8, 4096, 8192), + Err(ErrorCode::HostRangeOutOfBounds) + ); + d2h.host_offset = 4096; + d2h.device_offset = 16384; + assert_eq!( + validate_command(&d2h, &extents, 16384, 16384, 8, 4096, 8192), + Err(ErrorCode::DeviceRangeOutOfBounds) + ); } #[test] diff --git a/helios/src/async_transfer/scheduler.rs b/helios/src/async_transfer/scheduler.rs index c2e4da807..bc9562288 100644 --- a/helios/src/async_transfer/scheduler.rs +++ b/helios/src/async_transfer/scheduler.rs @@ -55,6 +55,16 @@ pub enum QueuedOp { completion_slot: Option, signal_value: u64, }, + DevToHost { + op_id: OpId, + priority: Priority, + host_offset: u64, + device_offset: u64, + nbytes: u64, + epoch: u64, + completion_slot: Option, + signal_value: u64, + }, } impl QueuedOp { @@ -63,7 +73,8 @@ impl QueuedOp { match *self { Self::DiskToHost { priority, .. } | Self::HostToDev { priority, .. } - | Self::DiskToDevIo { priority, .. } => priority, + | Self::DiskToDevIo { priority, .. } + | Self::DevToHost { priority, .. } => priority, } } @@ -72,7 +83,8 @@ impl QueuedOp { match *self { Self::DiskToHost { epoch, .. } | Self::HostToDev { epoch, .. } - | Self::DiskToDevIo { epoch, .. } => epoch, + | Self::DiskToDevIo { epoch, .. } + | Self::DevToHost { epoch, .. } => epoch, } } @@ -80,7 +92,7 @@ impl QueuedOp { pub const fn bounce_slot(&self) -> Option { match *self { Self::HostToDev { bounce_slot, .. } => bounce_slot, - Self::DiskToHost { .. } | Self::DiskToDevIo { .. } => None, + Self::DiskToHost { .. } | Self::DiskToDevIo { .. } | Self::DevToHost { .. } => None, } } } @@ -117,12 +129,29 @@ pub struct InflightDma { /// True once a post-enqueue CUDA failure (`cuEventRecord`/`cuEventQuery`) has been recorded /// while hardware drain of `copy_stream` has not yet been confirmed. pub faulted: bool, - /// True when `cuStreamWriteValue64_v2` was already enqueued on `copy_stream` with the + /// True when `cuStreamWriteValue64_v2` was already enqueued on the copy stream with the /// caller's success cookie before the post-enqueue fault occurred, so writing an error /// sentinel later could clobber a completed or reused completion slot. pub hardware_signaled: bool, } +/// An active D2H DMA operation submitted to the dedicated full-duplex D2H Copy Engine stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InflightD2h { + pub op_id: OpId, + pub priority: Priority, + pub host_offset: u64, + pub device_offset: u64, + pub nbytes: u64, + pub epoch: u64, + pub completion_slot: Option, + pub signal_value: u64, + /// True once a post-enqueue CUDA failure has been recorded while `d2h_stream` drain is pending. + pub faulted: bool, + /// True when `cuStreamWriteValue64_v2` already executed with the success cookie before faulting. + pub hardware_signaled: bool, +} + /// Completion notification emitted by the scheduler when an operation finishes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct CompletionNotice { @@ -145,10 +174,13 @@ pub struct TransferScheduler { max_bg_io: usize, max_total_dma: usize, max_bg_dma: usize, + max_d2h: usize, io_queues: [VecDeque; 3], dma_queues: [VecDeque; 3], + d2h_queues: [VecDeque; 3], inflight_io: Vec, inflight_dma: Vec, + inflight_d2h: Vec, free_bounce_slots: Vec, total_bounce_slots: usize, pub submitted_cmds: u64, @@ -176,10 +208,13 @@ impl TransferScheduler { max_bg_io: max_bg_io.min(max_total_io), max_total_dma, max_bg_dma: max_bg_dma.min(max_total_dma), + max_d2h: 2, io_queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()], dma_queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()], + d2h_queues: [VecDeque::new(), VecDeque::new(), VecDeque::new()], inflight_io: Vec::new(), inflight_dma: Vec::new(), + inflight_d2h: Vec::new(), free_bounce_slots: (0..bounce_slots).rev().collect(), total_bounce_slots: bounce_slots, submitted_cmds: 0, @@ -189,6 +224,13 @@ impl TransferScheduler { } } + /// Override the maximum concurrent D2H transfers allowed on the D2H stream. + #[inline] + pub fn with_max_d2h(mut self, max_d2h: usize) -> Self { + self.max_d2h = max_d2h.max(1); + self + } + #[inline] pub const fn state(&self) -> ChannelState { self.state @@ -209,11 +251,21 @@ impl TransferScheduler { self.inflight_dma.len() } + #[inline] + pub fn inflight_d2h_count(&self) -> usize { + self.inflight_d2h.len() + } + #[inline] pub fn faulted_dma_count(&self) -> usize { self.inflight_dma.iter().filter(|op| op.faulted).count() } + #[inline] + pub fn faulted_d2h_count(&self) -> usize { + self.inflight_d2h.iter().filter(|op| op.faulted).count() + } + #[inline] pub fn hw_signaled_faulted_dma_count(&self) -> usize { self.inflight_dma @@ -222,6 +274,14 @@ impl TransferScheduler { .count() } + #[inline] + pub fn hw_signaled_faulted_d2h_count(&self) -> usize { + self.inflight_d2h + .iter() + .filter(|op| op.faulted && op.hardware_signaled) + .count() + } + #[inline] pub fn unflushed_io_count(&self) -> usize { self.inflight_io.iter().filter(|op| !op.flushed).count() @@ -256,6 +316,13 @@ impl TransferScheduler { .any(|op| op.op_id == op_id && op.faulted) } + #[inline] + pub fn is_d2h_faulted(&self, op_id: OpId) -> bool { + self.inflight_d2h + .iter() + .any(|op| op.op_id == op_id && op.faulted) + } + #[inline] pub fn bg_io_inflight(&self) -> usize { self.inflight_io @@ -264,6 +331,14 @@ impl TransferScheduler { .count() } + #[inline] + pub fn dem_io_inflight(&self) -> usize { + self.inflight_io + .iter() + .filter(|op| !op.priority.is_background()) + .count() + } + #[inline] pub fn bg_dma_inflight(&self) -> usize { self.inflight_dma @@ -272,6 +347,14 @@ impl TransferScheduler { .count() } + #[inline] + pub fn dem_dma_inflight(&self) -> usize { + self.inflight_dma + .iter() + .filter(|op| !op.priority.is_background()) + .count() + } + #[inline] pub fn queued_io_count(&self) -> usize { self.io_queues.iter().map(VecDeque::len).sum() @@ -282,6 +365,11 @@ impl TransferScheduler { self.dma_queues.iter().map(VecDeque::len).sum() } + #[inline] + pub fn queued_d2h_count(&self) -> usize { + self.d2h_queues.iter().map(VecDeque::len).sum() + } + #[inline] pub fn free_bounce_count(&self) -> usize { self.free_bounce_slots.len() @@ -323,6 +411,26 @@ impl TransferScheduler { matches!(self.state, ChannelState::Idle | ChannelState::Stopped) && self.inflight_io.is_empty() && self.inflight_dma.is_empty() + && self.inflight_d2h.is_empty() + } + + /// Distinguishes queued priority classes and fused bounce ops during bounded model exploration + /// without widening the TLA+ state projection. + #[cfg(test)] + pub(crate) fn queue_shape_key(&self) -> (usize, usize, usize, usize) { + let q_bg_io = self.io_queues[Priority::Prefetch.index()].len() + + self.io_queues[Priority::Warm.index()].len(); + let q_fused_io = self + .io_queues + .iter() + .flatten() + .filter(|op| matches!(op, QueuedOp::DiskToDevIo { .. })) + .count(); + let q_bg_dma = self.dma_queues[Priority::Prefetch.index()].len() + + self.dma_queues[Priority::Warm.index()].len(); + let q_bg_d2h = self.d2h_queues[Priority::Prefetch.index()].len() + + self.d2h_queues[Priority::Warm.index()].len(); + (q_bg_io, q_fused_io, q_bg_dma, q_bg_d2h) } /// Transition `Idle -> Running` (idempotent when already `Running`). @@ -369,6 +477,10 @@ impl TransferScheduler { } } self.dma_queues[prio] = kept; + + let before_d2h = self.d2h_queues[prio].len(); + self.d2h_queues[prio].retain(|op| op.epoch() >= min_epoch); + dropped += (before_d2h - self.d2h_queues[prio].len()) as u64; } self.canceled_cmds = self.canceled_cmds.saturating_add(dropped); dropped @@ -483,6 +595,33 @@ impl TransferScheduler { }); None } + ValidatedCommand::DevToHost { + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + } => { + if priority.is_background() && epoch < self.active_epoch { + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + return None; + } + let op_id = self.next_op_id; + self.next_op_id = self.next_op_id.wrapping_add(1).max(1); + self.d2h_queues[priority.index()].push_back(QueuedOp::DevToHost { + op_id, + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + }); + None + } } } @@ -492,8 +631,9 @@ impl TransferScheduler { return None; } let bg_used = self.bg_io_inflight(); + let dem_active = self.dem_io_inflight() > 0; for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] { - if prio.is_background() && bg_used >= self.max_bg_io { + if prio.is_background() && (dem_active || bg_used >= self.max_bg_io) { continue; } let queue = &mut self.io_queues[prio.index()]; @@ -561,7 +701,7 @@ impl TransferScheduler { signal_value, flushed: false, }, - QueuedOp::HostToDev { .. } => unreachable!(), + QueuedOp::HostToDev { .. } | QueuedOp::DevToHost { .. } => unreachable!(), }; self.inflight_io.push(inflight); return Some(inflight); @@ -646,8 +786,9 @@ impl TransferScheduler { return None; } let bg_used = self.bg_dma_inflight(); + let dem_active = self.dem_dma_inflight() > 0; for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] { - if prio.is_background() && bg_used >= self.max_bg_dma { + if prio.is_background() && (dem_active || bg_used >= self.max_bg_dma) { continue; } let queue = &mut self.dma_queues[prio.index()]; @@ -772,6 +913,117 @@ impl TransferScheduler { }) } + /// Pop the highest-priority eligible D2H DMA allowed by the D2H concurrency cap. + /// + /// Background D2H transfers yield while any `Demand` H2D DMA is active so eviction copies + /// never compete with latency-critical H2D demand loads. + pub fn pop_next_d2h(&mut self) -> Option { + if self.state != ChannelState::Running || self.inflight_d2h.len() >= self.max_d2h { + return None; + } + let dem_dma_active = self.dem_dma_inflight() > 0; + for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] { + if prio.is_background() && dem_dma_active { + continue; + } + let queue = &mut self.d2h_queues[prio.index()]; + while let Some(op) = queue.pop_front() { + if prio.is_background() && op.epoch() < self.active_epoch { + self.canceled_cmds = self.canceled_cmds.saturating_add(1); + continue; + } + let QueuedOp::DevToHost { + op_id, + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + } = op + else { + unreachable!(); + }; + let inflight = InflightD2h { + op_id, + priority, + host_offset, + device_offset, + nbytes, + epoch, + completion_slot, + signal_value, + faulted: false, + hardware_signaled: false, + }; + self.inflight_d2h.push(inflight); + return Some(inflight); + } + } + None + } + + /// Record a post-enqueue CUDA failure on an in-flight D2H DMA while retaining its + /// in-flight reservation until `d2h_stream` confirms drain. + pub fn mark_d2h_faulted( + &mut self, + op_id: OpId, + hardware_signaled: bool, + ) -> Option { + if !matches!(self.state, ChannelState::Running | ChannelState::Draining) { + return None; + } + let op = self.inflight_d2h.iter_mut().find(|op| op.op_id == op_id)?; + if op.faulted { + return None; + } + op.faulted = true; + op.hardware_signaled = hardware_signaled; + let completion_slot = if hardware_signaled { + None + } else { + op.completion_slot + }; + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id, + completion_slot, + signal_value: completion_error_sentinel(ErrorCode::CudaFailure), + error: ErrorCode::CudaFailure, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }) + } + + /// Record completion of an in-flight D2H Copy Engine transfer. + pub fn complete_d2h(&mut self, op_id: OpId, ok: bool) -> Option { + let pos = self.inflight_d2h.iter().position(|op| op.op_id == op_id)?; + let op = self.inflight_d2h.swap_remove(pos); + if op.faulted { + return None; + } + self.completed_cmds = self.completed_cmds.saturating_add(1); + Some(CompletionNotice { + op_id: op.op_id, + completion_slot: op.completion_slot, + signal_value: if ok { + op.signal_value + } else { + completion_error_sentinel(ErrorCode::CudaFailure) + }, + error: if ok { + ErrorCode::Ok + } else { + ErrorCode::CudaFailure + }, + bytes_disk_to_host: 0, + bytes_host_to_dev: 0, + bytes_disk_to_dev: 0, + }) + } + /// Begin shutdown drain: transition `Running -> Draining` and drop all unstarted queued ops. /// /// Transitions `Idle -> Stopped` immediately. Returns `Err` if already `FailedDrain`. @@ -796,6 +1048,10 @@ impl TransferScheduler { dropped += 1; } } + for q in &mut self.d2h_queues { + dropped += q.len() as u64; + q.clear(); + } self.canceled_cmds = self.canceled_cmds.saturating_add(dropped); Ok(self.state) } @@ -813,7 +1069,11 @@ impl TransferScheduler { match self.state { ChannelState::Stopped => Ok(()), ChannelState::Draining => { - if stream_drained && self.inflight_io.is_empty() && self.inflight_dma.is_empty() { + if stream_drained + && self.inflight_io.is_empty() + && self.inflight_dma.is_empty() + && self.inflight_d2h.is_empty() + { self.state = ChannelState::Stopped; Ok(()) } else { diff --git a/helios/src/async_transfer/worker.rs b/helios/src/async_transfer/worker.rs index c83e896bc..346b660b5 100644 --- a/helios/src/async_transfer/worker.rs +++ b/helios/src/async_transfer/worker.rs @@ -12,7 +12,7 @@ use std::{ ptr::null_mut, sync::{ Arc, Mutex, RwLock, - atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}, mpsc, }, thread::{self, JoinHandle}, @@ -32,26 +32,32 @@ use super::{ io_backend::{IoBackend, IoCompletion}, ring::{ ABI_VERSION, ChannelState, ControlHeader, ErrorCode, ExtentEntry, - FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, TransferCommand, - completion_error_sentinel, host_completions_offset, validate_command, + FLAG_DEVICE_COMPLETIONS, FLAG_STREAM_WRITE_VALUE64, HEADER_BYTES, Priority, + TransferCommand, ValidatedCommand, completion_error_sentinel, host_completions_offset, + validate_command, }, scheduler::{CompletionNotice, OpId, TransferScheduler}, }; const DRAIN_TIMEOUT: Duration = Duration::from_secs(5); +const ACTIVE_SPIN_WINDOW: Duration = Duration::from_millis(50); const BUSY_SPIN_LIMIT: u32 = 512; const IDLE_SPIN_LIMIT: u32 = 4096; const BUSY_PARK_INTERVAL: Duration = Duration::from_micros(50); const IDLE_PARK_INTERVAL: Duration = Duration::from_micros(200); -const DEFAULT_MAX_TOTAL_IO: usize = 32; -const DEFAULT_MAX_BG_IO: usize = 8; +const DEFAULT_MAX_TOTAL_IO: usize = 16; +const DEFAULT_MAX_BG_IO: usize = 4; const DEFAULT_MAX_TOTAL_DMA: usize = 16; const DEFAULT_MAX_BG_DMA: usize = 4; +const DEFAULT_MAX_D2H: usize = 2; const DEFAULT_BOUNCE_SLOTS: usize = 16; +const MAX_BOUNCE_SLOTS: usize = 32; pub(crate) const MAX_BOUNCE_SLOT_BYTES: u64 = 32 << 20; /// Maximum pinned host bounce buffer registered by one channel (`DEFAULT_BOUNCE_SLOTS * MAX_BOUNCE_SLOT_BYTES`). pub(crate) const MAX_BOUNCE_POOL_BYTES: u64 = (DEFAULT_BOUNCE_SLOTS as u64) * MAX_BOUNCE_SLOT_BYTES; +static NEXT_WORKER_ORDINAL: AtomicUsize = AtomicUsize::new(0); + /// Upper bound on pinned bounce bytes registered by one channel with the given direct-I/O /// alignment. Returns `0` when `alignment` itself exceeds [`MAX_BOUNCE_SLOT_BYTES`] (or is not a /// positive power of two), because bounce staging is disabled in that configuration. @@ -84,7 +90,9 @@ pub(crate) fn bounce_pool_geometry(max_extent_bytes: u64, alignment: u32) -> (us if slot_bytes > MAX_BOUNCE_SLOT_BYTES { return (0, 0); } - (DEFAULT_BOUNCE_SLOTS, slot_bytes) + let slots = (MAX_BOUNCE_POOL_BYTES / slot_bytes) + .clamp(DEFAULT_BOUNCE_SLOTS as u64, MAX_BOUNCE_SLOTS as u64) as usize; + (slots, slot_bytes) } /// Immutable configuration passed to [`AsyncTransferRuntime::new`]. @@ -321,9 +329,17 @@ impl EventCompletionAction { } } +#[derive(Clone, Copy, PartialEq, Eq)] +enum FaultedStreamKind { + DemandH2d, + BgH2d, + D2h, +} + struct PendingEventDma { op_id: OpId, event: Handle, + completion_slot: Option, failed: bool, hardware_signaled: bool, completion_action: EventCompletionAction, @@ -331,6 +347,7 @@ struct PendingEventDma { struct UntrackedFaultedDma { op_id: OpId, + kind: FaultedStreamKind, pending_notice: Option, hardware_signaled: bool, host_mirror_on_drain: Option<(u32, u64)>, @@ -347,6 +364,8 @@ struct WorkerStateInner { join_handle: Option>, io_backend: Option>, copy_stream: Handle, + bg_copy_stream: Handle, + d2h_stream: Handle, host_pool: PinnedHostRegion, bounce_pool: PinnedHostRegion, bounce_slot_bytes: u64, @@ -416,20 +435,41 @@ impl AsyncTransferRuntime { }; let mut copy_stream = null_mut(); + let mut bg_copy_stream = null_mut(); + let mut d2h_stream = null_mut(); let stream_result = unsafe { let mut prev = null_mut(); let had_prev = (driver.context_get)(&mut prev) == 0; let res = driver .check("cuCtxSetCurrent", (driver.context_set)(context)) .and_then(|()| { - driver.check( - "cuStreamCreate(async_transfer)", - (driver.stream_create)(&mut copy_stream, CU_STREAM_NON_BLOCKING), - ) + let mut least_prio: std::ffi::c_int = 0; + let mut greatest_prio: std::ffi::c_int = 0; + let has_prio = (driver.ctx_get_stream_priority_range)( + &mut least_prio, + &mut greatest_prio, + ) == 0 + && greatest_prio < least_prio; + let make_stream = |out: &mut Handle, high: bool| -> Result<()> { + let status = if has_prio { + let prio = if high { greatest_prio } else { least_prio }; + (driver.stream_create_with_priority)(out, CU_STREAM_NON_BLOCKING, prio) + } else { + (driver.stream_create)(out, CU_STREAM_NON_BLOCKING) + }; + driver.check("cuStreamCreate(async_transfer)", status) + }; + make_stream(&mut copy_stream, true)?; + make_stream(&mut bg_copy_stream, false)?; + make_stream(&mut d2h_stream, false) }); - if res.is_err() && !copy_stream.is_null() { - let _ = (driver.stream_destroy)(copy_stream); - copy_stream = null_mut(); + if res.is_err() { + for s in [&mut copy_stream, &mut bg_copy_stream, &mut d2h_stream] { + if !s.is_null() { + let _ = (driver.stream_destroy)(*s); + *s = null_mut(); + } + } } if had_prev && prev != context { let _ = (driver.context_set)(prev); @@ -485,6 +525,8 @@ impl AsyncTransferRuntime { join_handle: None, io_backend: Some(io_backend), copy_stream, + bg_copy_stream, + d2h_stream, host_pool, bounce_pool, bounce_slot_bytes, @@ -570,8 +612,12 @@ impl AsyncTransferRuntime { driver: self.driver.clone(), context: self.context as usize, copy_stream: inner.copy_stream as usize, + bg_copy_stream: inner.bg_copy_stream as usize, + d2h_stream: inner.d2h_stream as usize, host_pool_ptr: inner.host_pool.ptr as usize, + host_pool_len: inner.host_pool.nbytes, bounce_pool_ptr: inner.bounce_pool.ptr as usize, + bounce_pool_len: inner.bounce_pool.nbytes, bounce_slot_bytes: inner.bounce_slot_bytes, bounce_slots: inner.bounce_slots, use_write_value64: inner.use_write_value64, @@ -701,9 +747,15 @@ impl AsyncTransferRuntime { let mut prev = null_mut(); let had_prev = (self.driver.context_get)(&mut prev) == 0; if (self.driver.context_set)(self.context) == 0 { - if !inner.copy_stream.is_null() { - let _ = (self.driver.stream_destroy)(inner.copy_stream); - inner.copy_stream = null_mut(); + for s in [ + &mut inner.copy_stream, + &mut inner.bg_copy_stream, + &mut inner.d2h_stream, + ] { + if !s.is_null() { + let _ = (self.driver.stream_destroy)(*s); + *s = null_mut(); + } } } if had_prev && prev != self.context { @@ -748,8 +800,12 @@ struct WorkerThreadArgs { driver: Arc, context: usize, copy_stream: usize, + bg_copy_stream: usize, + d2h_stream: usize, host_pool_ptr: usize, + host_pool_len: usize, bounce_pool_ptr: usize, + bounce_pool_len: usize, bounce_slot_bytes: u64, bounce_slots: usize, use_write_value64: bool, @@ -759,9 +815,44 @@ struct WorkerThreadArgs { ready_tx: mpsc::SyncSender>, } +#[inline] +fn storage_io_priority(cmd: &ValidatedCommand) -> Option { + match *cmd { + ValidatedCommand::DiskToHost { priority, .. } + | ValidatedCommand::DiskToDev { priority, .. } => Some(priority), + ValidatedCommand::HostToDev { .. } + | ValidatedCommand::DevToHost { .. } + | ValidatedCommand::CancelEpoch { .. } => None, + } +} + +/// Stagger contiguous same-priority storage reads by `worker_ordinal` before scheduler admission +/// so concurrent rank workers spread access across striped drives while keeping scheduler FIFO +/// order strictly aligned with the kernel `io_uring` SQ ring. +fn rotate_storage_runs(cmds: &mut [ValidatedCommand], worker_ordinal: usize) { + let mut start = 0usize; + while start < cmds.len() { + let Some(prio) = storage_io_priority(&cmds[start]) else { + start += 1; + continue; + }; + let mut end = start + 1; + while end < cmds.len() && storage_io_priority(&cmds[end]) == Some(prio) { + end += 1; + } + let len = end - start; + if len > 1 { + cmds[start..end].rotate_left(worker_ordinal % len); + } + start = end; + } +} + fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let context = args.context as Handle; let copy_stream = args.copy_stream as Handle; + let bg_copy_stream = args.bg_copy_stream as Handle; + let d2h_stream = args.d2h_stream as Handle; let driver = &args.driver; // SAFETY: The worker binds the channel's CUDA context once for its entire lifetime. if let Err(err) = driver.check( @@ -782,8 +873,9 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { // Pre-create a bounded pool of CUDA events (CU_EVENT_DISABLE_TIMING = 0x2) before signaling // readiness so DMA dispatch cannot silently stall with an empty event pool. - let mut free_events: Vec = Vec::with_capacity(DEFAULT_MAX_TOTAL_DMA); - for _ in 0..DEFAULT_MAX_TOTAL_DMA { + let event_pool_cap = DEFAULT_MAX_TOTAL_DMA + DEFAULT_MAX_D2H; + let mut free_events: Vec = Vec::with_capacity(event_pool_cap); + for _ in 0..event_pool_cap { let mut ev = null_mut(); let status = unsafe { (driver.event_create)(&mut ev, 0x2) }; if let Err(err) = driver.check("cuEventCreate(async_transfer)", status) { @@ -798,6 +890,20 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { free_events.push(ev); } + // Bind the I/O backend to this dedicated worker thread (enabling single-issuer deferred + // taskrun on Linux) and register pinned pools as fixed io_uring buffers before signaling ready. + let _ = args.io_backend.bind_worker_thread(); + let mut reg_regions: Vec<(*mut u8, usize)> = Vec::with_capacity(2); + if args.bounce_pool_ptr != 0 && args.bounce_pool_len > 0 { + reg_regions.push((args.bounce_pool_ptr as *mut u8, args.bounce_pool_len)); + } + if args.host_pool_ptr != 0 && args.host_pool_len > 0 { + reg_regions.push((args.host_pool_ptr as *mut u8, args.host_pool_len)); + } + if !reg_regions.is_empty() { + let _ = unsafe { args.io_backend.register_buffers(®_regions) }; + } + let header = unsafe { &*(args.config.control_address as *const ControlHeader) }; let ring_base = (args.config.control_address + HEADER_BYTES) as *const TransferCommand; let ring_mask = (args.config.ring_capacity as u64) - 1; @@ -819,7 +925,8 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { DEFAULT_MAX_TOTAL_DMA, DEFAULT_MAX_BG_DMA, args.bounce_slots, - ); + ) + .with_max_d2h(DEFAULT_MAX_D2H); let _ = scheduler.start(); header .worker_state @@ -828,14 +935,21 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { .store(ChannelState::Running as u32, Ordering::Release); let _ = args.ready_tx.send(Ok(())); - let mut pending_dma_events: VecDeque = + let mut pending_dem_dma_events: VecDeque = VecDeque::with_capacity(DEFAULT_MAX_TOTAL_DMA); + let mut pending_bg_dma_events: VecDeque = + VecDeque::with_capacity(DEFAULT_MAX_BG_DMA + 2); + let mut pending_d2h_events: VecDeque = + VecDeque::with_capacity(DEFAULT_MAX_D2H); let mut untracked_faulted_dmas: Vec = Vec::new(); let mut leaked_events: Vec = Vec::new(); let mut io_completions: Vec = Vec::with_capacity(32); + let mut drained_cmds: Vec = Vec::with_capacity(64); + let worker_ordinal = NEXT_WORKER_ORDINAL.fetch_add(1, Ordering::Relaxed); let mut head = header.cmd_head.load(Ordering::Relaxed); let mut idle_spins: u32 = 0; + let mut last_active = Instant::now(); let update_host_comp = |slot: u32, value: u64| { // SAFETY: `slot < completion_slots` was validated before enqueue; `host_comp_base` stays @@ -845,11 +959,48 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } }; - let signal_completion_slot = |slot: u32, value: u64| { - // All device completion writes serialize on `copy_stream` so DMA writes and host-initiated - // completions (`DiskToHost`, `CancelEpoch`, errors) never race across streams. + // Enforce cross-stream causal ordering whenever a newly submitted command reuses a completion + // slot that still has an in-flight write on another CUDA stream (zero overhead on distinct slots). + let wait_other_streams_on_slot = |target_stream: Handle, + slot: u32, + other_a: &VecDeque, + other_b: &VecDeque| { + for q in [other_a, other_b] { + for pending in q { + if pending.completion_slot == Some(slot) { + let _ = unsafe { (driver.stream_wait_event)(target_stream, pending.event, 0) }; + } + } + } + }; + + // Track the highest completion value already queued per slot across all CUDA streams so + // priority preemption (for example, a Demand transfer jumping ahead of a queued Prefetch + // transfer reusing the same slot) cannot regress `device_completions[slot]` backwards. + let stream_comp_max: Vec> = + vec![std::cell::Cell::new(0); args.config.completion_slots as usize]; + let should_write_stream_comp = |slot: u32, value: u64| -> bool { + value >= stream_comp_max[slot as usize].get() + }; + let record_stream_comp = |slot: u32, value: u64| { + let cell = &stream_comp_max[slot as usize]; + if value > cell.get() { + cell.set(value); + } + }; + + let signal_completion_slot = |slot: u32, + value: u64, + bg_q: &VecDeque, + d2h_q: &VecDeque| { + // Serialize host-initiated completions (`DiskToHost`, `CancelEpoch`, errors) on + // `copy_stream`, waiting on any in-flight `bg_copy_stream`/`d2h_stream` op using `slot`. if args.config.device_completions_base != 0 { update_host_comp(slot, value); + if !should_write_stream_comp(slot, value) { + return; + } + wait_other_streams_on_slot(copy_stream, slot, bg_q, d2h_q); let dev_addr = args.config.device_completions_base + u64::from(slot) * 8; let status = if args.use_write_value64 { let write_fn = driver.stream_write_value64.unwrap(); @@ -858,7 +1009,9 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let host_ptr = unsafe { host_comp_base.add(slot as usize) } as *const std::ffi::c_void; unsafe { (driver.upload_async)(dev_addr, host_ptr, 8, copy_stream) } }; - if status != 0 { + if status == 0 { + record_stream_comp(slot, value); + } else { header .last_error .store(ErrorCode::CudaFailure as u32, Ordering::Release); @@ -868,11 +1021,17 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { // When `device_completions_base == 0` with `cuStreamWriteValue64_v2`, route all // writes to `host_comp` through `copy_stream` so DMA writes and host-side completions // execute in strict FIFO order without CPU/Copy-Engine races. + if !should_write_stream_comp(slot, value) { + return; + } + wait_other_streams_on_slot(copy_stream, slot, bg_q, d2h_q); let write_fn = driver.stream_write_value64.unwrap(); let target_addr = host_comp_gpu_base + u64::from(slot) * 8; let status = unsafe { write_fn(copy_stream, target_addr, value, CU_STREAM_WRITE_VALUE_DEFAULT) }; - if status != 0 { + if status == 0 { + record_stream_comp(slot, value); + } else { header .last_error .store(ErrorCode::CudaFailure as u32, Ordering::Release); @@ -883,7 +1042,10 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } }; - let publish_notice = |notice: CompletionNotice, write_slot: bool| { + let publish_notice = |notice: CompletionNotice, + write_slot: bool, + bg_q: &VecDeque, + d2h_q: &VecDeque| { if notice.error != ErrorCode::Ok { header .last_error @@ -911,7 +1073,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } else { completion_error_sentinel(notice.error) }; - signal_completion_slot(slot, value); + signal_completion_slot(slot, value, bg_q, d2h_q); } } }; @@ -932,8 +1094,10 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { header.active_inflight.store( (sched.inflight_io_count() + sched.inflight_dma_count() + + sched.inflight_d2h_count() + sched.queued_io_count() - + sched.queued_dma_count()) as u64, + + sched.queued_dma_count() + + sched.queued_d2h_count()) as u64, Ordering::Relaxed, ); }; @@ -963,6 +1127,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { head = tail; did_work = true; } else { + drained_cmds.clear(); while head < tail { let slot_idx = (head & ring_mask) as usize; // SAFETY: Producer wrote command before Release-storing `cmd_tail > head`. @@ -978,17 +1143,26 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { args.config.alignment, args.bounce_slot_bytes, ) { - Ok(validated) => { - if let Some(immediate) = scheduler.enqueue(validated) { - publish_notice(immediate, true); - } - } + Ok(validated) => drained_cmds.push(validated), Err(code) => { scheduler.record_rejected(); header.last_error.store(code as u32, Ordering::Release); } } } + if !drained_cmds.is_empty() { + rotate_storage_runs(&mut drained_cmds, worker_ordinal); + for validated in drained_cmds.drain(..) { + if let Some(immediate) = scheduler.enqueue(validated) { + publish_notice( + immediate, + true, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } + } + } } if did_work { header.cmd_head.store(head, Ordering::Release); @@ -1001,18 +1175,107 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { did_work = true; for c in io_completions.drain(..) { if let Some(notice) = scheduler.complete_io(c.op_id, c.ok) { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } } } - // 4. Harvest completed Copy Engine DMA events (in FIFO stream order). - while let Some(front) = pending_dma_events.front() { - let status = unsafe { (driver.event_query)(front.event) }; + // 4. Harvest completed Copy Engine DMA events separately per stream so slow background + // prefetches and D2H demotions never head-of-line block demand completions. + for is_dem in [true, false] { + loop { + let status = { + let q = if is_dem { + &pending_dem_dma_events + } else { + &pending_bg_dma_events + }; + let Some(front) = q.front() else { + break; + }; + unsafe { (driver.event_query)(front.event) } + }; + if status == CUDA_ERROR_NOT_READY { + break; + } + let done = if is_dem { + pending_dem_dma_events.pop_front().unwrap() + } else { + pending_bg_dma_events.pop_front().unwrap() + }; + did_work = true; + if status == 0 { + free_events.push(done.event); + if !done.failed { + match done.completion_action { + EventCompletionAction::None => {} + EventCompletionAction::HostOnly(slot, val) => { + update_host_comp(slot, val); + } + EventCompletionAction::HostAndDevice(slot, val) => { + signal_completion_slot( + slot, + val, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } + } + if let Some(notice) = scheduler.complete_dma(done.op_id, true) { + publish_notice( + notice, + false, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } + } else if let Some(notice) = scheduler.complete_dma(done.op_id, false) { + publish_notice( + notice, + true, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } + } else { + leaked_events.push(done.event); + if let Some(notice) = + scheduler.mark_dma_faulted(done.op_id, done.hardware_signaled) + { + publish_notice( + notice, + !done.hardware_signaled, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } + untracked_faulted_dmas.push(UntrackedFaultedDma { + op_id: done.op_id, + kind: if is_dem { + FaultedStreamKind::DemandH2d + } else { + FaultedStreamKind::BgH2d + }, + pending_notice: None, + hardware_signaled: done.hardware_signaled, + host_mirror_on_drain: done + .completion_action + .host_mirror_on_drain(done.hardware_signaled), + }); + } + } + } + loop { + let status = { + let Some(front) = pending_d2h_events.front() else { + break; + }; + unsafe { (driver.event_query)(front.event) } + }; if status == CUDA_ERROR_NOT_READY { break; } - let done = pending_dma_events.pop_front().unwrap(); + let done = pending_d2h_events.pop_front().unwrap(); did_work = true; if status == 0 { free_events.push(done.event); @@ -1020,33 +1283,37 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { match done.completion_action { EventCompletionAction::None => {} EventCompletionAction::HostOnly(slot, val) => { - // Device word was already written in-order via cuStreamWriteValue64_v2; - // advance the host mirror monotonically so slot reuse cannot regress it. update_host_comp(slot, val); } EventCompletionAction::HostAndDevice(slot, val) => { - signal_completion_slot(slot, val); + signal_completion_slot( + slot, + val, + &pending_bg_dma_events, + &pending_d2h_events, + ); } } - if let Some(notice) = scheduler.complete_dma(done.op_id, true) { - publish_notice(notice, false); + if let Some(notice) = scheduler.complete_d2h(done.op_id, true) { + publish_notice(notice, false, &pending_bg_dma_events, &pending_d2h_events); } - } else if let Some(notice) = scheduler.complete_dma(done.op_id, false) { - // `cuStreamWriteValue64_v2` failed after `cuMemcpyHtoDAsync_v2` succeeded; - // now that `ev` confirmed DMA completion, release the bounce slot and publish - // the explicit error sentinel. - publish_notice(notice, true); + } else if let Some(notice) = scheduler.complete_d2h(done.op_id, false) { + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } } else { - // Sticky CUDA error on `cuEventQuery`: retain event and bounce slot inside - // `scheduler.inflight_dma` until `copy_stream` confirms drain (or `FailedDrain`). leaked_events.push(done.event); - if let Some(notice) = scheduler.mark_dma_faulted(done.op_id, done.hardware_signaled) + if let Some(notice) = scheduler.mark_d2h_faulted(done.op_id, done.hardware_signaled) { - publish_notice(notice, !done.hardware_signaled); + publish_notice( + notice, + !done.hardware_signaled, + &pending_bg_dma_events, + &pending_d2h_events, + ); } untracked_faulted_dmas.push(UntrackedFaultedDma { op_id: done.op_id, + kind: FaultedStreamKind::D2h, pending_notice: None, hardware_signaled: done.hardware_signaled, host_mirror_on_drain: done @@ -1056,48 +1323,71 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } } if !untracked_faulted_dmas.is_empty() { - let stream_status = unsafe { (driver.stream_query)(copy_stream) }; - if stream_status == 0 { - did_work = true; - for mut item in untracked_faulted_dmas.drain(..) { - let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); + let mut still_pending: Vec = Vec::new(); + for mut item in untracked_faulted_dmas.drain(..) { + let target_stream = match item.kind { + FaultedStreamKind::DemandH2d => copy_stream, + FaultedStreamKind::BgH2d => bg_copy_stream, + FaultedStreamKind::D2h => d2h_stream, + }; + let stream_status = unsafe { (driver.stream_query)(target_stream) }; + if stream_status == 0 { + did_work = true; + match item.kind { + FaultedStreamKind::DemandH2d | FaultedStreamKind::BgH2d => { + let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); + } + FaultedStreamKind::D2h => { + let _ = scheduler.complete_d2h(item.op_id, item.hardware_signaled); + } + } if item.hardware_signaled { - // Hardware already executed `cuStreamWriteValue64_v2` with the success - // cookie on `copy_stream` before drain; advance the host mirror if - // applicable and record `last_error` without overwriting the slot. if let Some((slot, val)) = item.host_mirror_on_drain { update_host_comp(slot, val); } if let Some(notice) = item.pending_notice.take() { - publish_notice(notice, false); + publish_notice( + notice, + false, + &pending_bg_dma_events, + &pending_d2h_events, + ); } } else if let Some(notice) = item.pending_notice.take() { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } - } - } else if stream_status != CUDA_ERROR_NOT_READY { - // Stream entered a sticky CUDA error: signal any unsent fault notices for - // non-hardware-signaled ops while keeping `untracked_faulted_dmas` pinned in - // `scheduler.inflight_dma` so bounce slots and host memory are never reclaimed. - header - .last_error - .store(ErrorCode::CudaFailure as u32, Ordering::Release); - for item in &mut untracked_faulted_dmas { - if let Some(notice) = item.pending_notice.take() { - did_work = true; - publish_notice(notice, !item.hardware_signaled); + } else { + if stream_status != CUDA_ERROR_NOT_READY { + header + .last_error + .store(ErrorCode::CudaFailure as u32, Ordering::Release); + if let Some(notice) = item.pending_notice.take() { + did_work = true; + publish_notice( + notice, + !item.hardware_signaled, + &pending_bg_dma_events, + &pending_d2h_events, + ); + } } + still_pending.push(item); } } + untracked_faulted_dmas = still_pending; } - // 5. Submit highest-priority eligible Copy Engine DMAs (DEMAND jumps ahead of background). - // Pause new DMA submissions while any untracked partial-DMA failure awaits `copy_stream` drain. - while untracked_faulted_dmas.is_empty() && !free_events.is_empty() { + // 5. Submit highest-priority eligible H2D DMAs onto priority-separated streams. + let has_faulted_h2d = untracked_faulted_dmas + .iter() + .any(|f| f.kind != FaultedStreamKind::D2h); + while !has_faulted_h2d && !free_events.is_empty() { let Some(dma) = scheduler.pop_next_dma() else { break; }; did_work = true; + let is_dem = !dma.priority.is_background(); + let target_stream = if is_dem { copy_stream } else { bg_copy_stream }; let ev = free_events.pop().unwrap(); let src_ptr = match (dma.host_offset, dma.bounce_slot) { (Some(off), _) => (args.host_pool_ptr + off as usize) as *const std::ffi::c_void, @@ -1108,21 +1398,19 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { (None, None) => { free_events.push(ev); if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } continue; } }; let dst_addr = args.config.device_pool_base + dma.device_offset; let copy_status = unsafe { - (driver.upload_async)(dst_addr, src_ptr, dma.nbytes as usize, copy_stream) + (driver.upload_async)(dst_addr, src_ptr, dma.nbytes as usize, target_stream) }; if copy_status != 0 { - // `cuMemcpyHtoDAsync_v2` rejected submission; no Copy Engine DMA reads `src_ptr`, - // so recycling `ev` and the bounce slot immediately is safe. free_events.push(ev); if let Some(notice) = scheduler.complete_dma(dma.op_id, false) { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } continue; } @@ -1131,50 +1419,67 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let mut signal_status = 0; let mut hardware_signaled = false; if let Some(slot) = dma.completion_slot { - if args.use_write_value64 { - let writes_device_word = args.config.device_completions_base != 0; - let target_addr = if writes_device_word { - args.config.device_completions_base + u64::from(slot) * 8 + if should_write_stream_comp(slot, dma.signal_value) { + if is_dem { + wait_other_streams_on_slot( + target_stream, + slot, + &pending_bg_dma_events, + &pending_d2h_events, + ); } else { - host_comp_gpu_base - .checked_add(u64::from(slot) * 8) - .filter(|_| host_comp_gpu_base != 0) - .unwrap_or(0) - }; - if target_addr != 0 { - let write_fn = driver.stream_write_value64.unwrap(); - signal_status = unsafe { - write_fn( - copy_stream, - target_addr, - dma.signal_value, - CU_STREAM_WRITE_VALUE_DEFAULT, - ) + wait_other_streams_on_slot( + target_stream, + slot, + &pending_dem_dma_events, + &pending_d2h_events, + ); + } + if args.use_write_value64 { + let writes_device_word = args.config.device_completions_base != 0; + let target_addr = if writes_device_word { + args.config.device_completions_base + u64::from(slot) * 8 + } else { + host_comp_gpu_base + .checked_add(u64::from(slot) * 8) + .filter(|_| host_comp_gpu_base != 0) + .unwrap_or(0) }; - if signal_status == 0 { - hardware_signaled = true; - if writes_device_word { - completion_action = - EventCompletionAction::HostOnly(slot, dma.signal_value); + if target_addr != 0 { + let write_fn = driver.stream_write_value64.unwrap(); + signal_status = unsafe { + write_fn( + target_stream, + target_addr, + dma.signal_value, + CU_STREAM_WRITE_VALUE_DEFAULT, + ) + }; + if signal_status == 0 { + record_stream_comp(slot, dma.signal_value); + hardware_signaled = true; + if writes_device_word { + completion_action = + EventCompletionAction::HostOnly(slot, dma.signal_value); + } } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, dma.signal_value); } } else { completion_action = EventCompletionAction::HostAndDevice(slot, dma.signal_value); } - } else { - completion_action = - EventCompletionAction::HostAndDevice(slot, dma.signal_value); } } - // Always record `ev` on `copy_stream` after a successful `cuMemcpyHtoDAsync_v2` even - // when `signal_status != 0` so bounce-slot reclamation waits for hardware DMA finish. - let rec_status = unsafe { (driver.event_record)(ev, copy_stream) }; + let rec_status = unsafe { (driver.event_record)(ev, target_stream) }; if rec_status == 0 { - pending_dma_events.push_back(PendingEventDma { + let entry = PendingEventDma { op_id: dma.op_id, event: ev, + completion_slot: dma.completion_slot, failed: signal_status != 0, hardware_signaled, completion_action: if signal_status == 0 { @@ -1182,17 +1487,127 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } else { EventCompletionAction::None }, - }); + }; + if is_dem { + pending_dem_dma_events.push_back(entry); + } else { + pending_bg_dma_events.push_back(entry); + } } else { - // `cuEventRecord` failed while Copy Engine DMA is still in flight on `copy_stream`. - // Retain `dma` and its bounce slot in `scheduler.inflight_dma` until `copy_stream` - // confirms drain (or permanently into `FailedDrain`). free_events.push(ev); let host_mirror_on_drain = completion_action.host_mirror_on_drain(hardware_signaled); let pending_notice = scheduler.mark_dma_faulted(dma.op_id, hardware_signaled); untracked_faulted_dmas.push(UntrackedFaultedDma { op_id: dma.op_id, + kind: if is_dem { + FaultedStreamKind::DemandH2d + } else { + FaultedStreamKind::BgH2d + }, + pending_notice, + hardware_signaled, + host_mirror_on_drain, + }); + break; + } + } + + // 5b. Submit full-duplex D2H transfers onto dedicated `d2h_stream`. + let has_faulted_d2h = untracked_faulted_dmas + .iter() + .any(|f| f.kind == FaultedStreamKind::D2h); + while !has_faulted_d2h && !free_events.is_empty() { + let Some(d2h) = scheduler.pop_next_d2h() else { + break; + }; + did_work = true; + let ev = free_events.pop().unwrap(); + let dst_ptr = (args.host_pool_ptr + d2h.host_offset as usize) as *mut std::ffi::c_void; + let src_addr = args.config.device_pool_base + d2h.device_offset; + let copy_status = unsafe { + (driver.download_async)(dst_ptr, src_addr, d2h.nbytes as usize, d2h_stream) + }; + if copy_status != 0 { + free_events.push(ev); + if let Some(notice) = scheduler.complete_d2h(d2h.op_id, false) { + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); + } + continue; + } + + let mut completion_action = EventCompletionAction::None; + let mut signal_status = 0; + let mut hardware_signaled = false; + if let Some(slot) = d2h.completion_slot { + if should_write_stream_comp(slot, d2h.signal_value) { + wait_other_streams_on_slot( + d2h_stream, + slot, + &pending_dem_dma_events, + &pending_bg_dma_events, + ); + if args.use_write_value64 { + let writes_device_word = args.config.device_completions_base != 0; + let target_addr = if writes_device_word { + args.config.device_completions_base + u64::from(slot) * 8 + } else { + host_comp_gpu_base + .checked_add(u64::from(slot) * 8) + .filter(|_| host_comp_gpu_base != 0) + .unwrap_or(0) + }; + if target_addr != 0 { + let write_fn = driver.stream_write_value64.unwrap(); + signal_status = unsafe { + write_fn( + d2h_stream, + target_addr, + d2h.signal_value, + CU_STREAM_WRITE_VALUE_DEFAULT, + ) + }; + if signal_status == 0 { + record_stream_comp(slot, d2h.signal_value); + hardware_signaled = true; + if writes_device_word { + completion_action = + EventCompletionAction::HostOnly(slot, d2h.signal_value); + } + } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, d2h.signal_value); + } + } else { + completion_action = + EventCompletionAction::HostAndDevice(slot, d2h.signal_value); + } + } + } + + let rec_status = unsafe { (driver.event_record)(ev, d2h_stream) }; + if rec_status == 0 { + pending_d2h_events.push_back(PendingEventDma { + op_id: d2h.op_id, + event: ev, + completion_slot: d2h.completion_slot, + failed: signal_status != 0, + hardware_signaled, + completion_action: if signal_status == 0 { + completion_action + } else { + EventCompletionAction::None + }, + }); + } else { + free_events.push(ev); + let host_mirror_on_drain = + completion_action.host_mirror_on_drain(hardware_signaled); + let pending_notice = scheduler.mark_d2h_faulted(d2h.op_id, hardware_signaled); + untracked_faulted_dmas.push(UntrackedFaultedDma { + op_id: d2h.op_id, + kind: FaultedStreamKind::D2h, pending_notice, hardware_signaled, host_mirror_on_drain, @@ -1212,7 +1627,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } (None, None) => { if let Some(notice) = scheduler.complete_io(io_op.op_id, false) { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } continue; } @@ -1235,7 +1650,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { scheduler.mark_io_flushed(flushed_now); } } else if let Some(notice) = scheduler.complete_io(io_op.op_id, false) { - publish_notice(notice, true); + publish_notice(notice, true, &pending_bg_dma_events, &pending_d2h_events); } } // Flush unconditionally whenever new reads were staged or earlier SQEs remain queued @@ -1259,12 +1674,16 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { if did_work { sync_telemetry(&scheduler); idle_spins = 0; + last_active = Instant::now(); } else { idle_spins = idle_spins.saturating_add(1); - let has_inflight = - scheduler.inflight_io_count() > 0 || scheduler.inflight_dma_count() > 0; - if has_inflight { - if idle_spins < BUSY_SPIN_LIMIT { + let has_inflight = scheduler.inflight_io_count() > 0 + || scheduler.inflight_dma_count() > 0 + || scheduler.inflight_d2h_count() > 0; + // Active-spin during serving bursts so per-layer demand doorbells avoid OS sleep + // latency, then back off cleanly when idle between requests. + if has_inflight || last_active.elapsed() < ACTIVE_SPIN_WINDOW { + if idle_spins < BUSY_SPIN_LIMIT || last_active.elapsed() < ACTIVE_SPIN_WINDOW { std::hint::spin_loop(); } else if idle_spins < IDLE_SPIN_LIMIT { thread::yield_now(); @@ -1279,7 +1698,7 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { } } - // Shutdown drain sequence: drop queued work, cancel/drain storage I/O, drain Copy Engine stream. + // Shutdown drain sequence: drop queued work, cancel/drain storage I/O, drain all Copy Engine streams. let _ = scheduler.begin_drain(); header .worker_state @@ -1306,22 +1725,40 @@ fn worker_main(mut args: WorkerThreadArgs) -> WorkerExit { let mut stream_drained = false; loop { let copy_status = unsafe { (driver.stream_query)(copy_stream) }; - if copy_status == 0 { + let bg_status = unsafe { (driver.stream_query)(bg_copy_stream) }; + let d2h_status = unsafe { (driver.stream_query)(d2h_stream) }; + if copy_status == 0 && bg_status == 0 && d2h_status == 0 { stream_drained = true; break; } - if copy_status != CUDA_ERROR_NOT_READY || Instant::now() >= deadline { + let all_ok = [copy_status, bg_status, d2h_status] + .into_iter() + .all(|s| s == 0 || s == CUDA_ERROR_NOT_READY); + if !all_ok || Instant::now() >= deadline { break; } thread::sleep(Duration::from_millis(1)); } if stream_drained { - while let Some(done) = pending_dma_events.pop_front() { - let _ = scheduler.complete_dma(done.op_id, !done.failed); + for q in [&mut pending_dem_dma_events, &mut pending_bg_dma_events] { + while let Some(done) = q.pop_front() { + let _ = scheduler.complete_dma(done.op_id, !done.failed); + free_events.push(done.event); + } + } + while let Some(done) = pending_d2h_events.pop_front() { + let _ = scheduler.complete_d2h(done.op_id, !done.failed); free_events.push(done.event); } for item in untracked_faulted_dmas.drain(..) { - let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); + match item.kind { + FaultedStreamKind::DemandH2d | FaultedStreamKind::BgH2d => { + let _ = scheduler.complete_dma(item.op_id, item.hardware_signaled); + } + FaultedStreamKind::D2h => { + let _ = scheduler.complete_d2h(item.op_id, item.hardware_signaled); + } + } } for ev in free_events.drain(..).chain(leaked_events.drain(..)) { unsafe { @@ -1653,6 +2090,144 @@ mod cuda_tests { } assert_eq!(readback, patterns[2]); + // Exercise Opcode::DevToHost round-trip (dev slot 1 -> host slot 3) followed by + // Prefetch H2D on `bg_copy_stream`, cross-stream same-slot reuse by Demand H2D on + // `copy_stream` (slot 6: 7007 -> 7008), and simultaneous Prefetch+Demand preemption + // on slot 7 (7009 + 7010) verifying monotonic non-regression of `device_completions`. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::DevToHost as u32, + priority: Priority::Warm as u32, + extent_id: 1, + completion_slot: 5, + host_offset: 3 * extent_bytes as u64, + device_offset: extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 6006, + _reserved: 0, + }, + ); + wait_dev_comp(5, 6006); + wait_host_comp(ctrl_ptr as usize, 5, 6006); + + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Prefetch as u32, + extent_id: 1, + completion_slot: 6, + host_offset: 3 * extent_bytes as u64, + device_offset: 4 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 7007, + _reserved: 0, + }, + ); + wait_dev_comp(6, 7007); + wait_host_comp(ctrl_ptr as usize, 6, 7007); + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Demand as u32, + extent_id: 2, + completion_slot: 6, + host_offset: extent_bytes as u64, + device_offset: 5 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 7008, + _reserved: 0, + }, + ); + wait_dev_comp(6, 7008); + wait_host_comp(ctrl_ptr as usize, 6, 7008); + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(d2h_roundtrip)", + (driver.download)( + readback.as_mut_ptr().cast(), + dev_pool + 4 * extent_bytes as u64, + extent_bytes, + ), + ) + .unwrap(); + } + assert_eq!(readback, patterns[1]); + unsafe { + driver + .check( + "cuMemcpyDtoH_v2(dual_stream_dem)", + (driver.download)( + readback.as_mut_ptr().cast(), + dev_pool + 5 * extent_bytes as u64, + extent_bytes, + ), + ) + .unwrap(); + } + assert_eq!(readback, patterns[2]); + + // Enqueue Prefetch (7009) and Demand (7010) simultaneously on slot 7 followed by a + // trailing Prefetch barrier on slot 8 (7011). Even when Demand preempts Prefetch in + // the priority queue, slot 7 must remain at 7010 and never regress to 7009. + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Prefetch as u32, + extent_id: 1, + completion_slot: 7, + host_offset: 3 * extent_bytes as u64, + device_offset: 4 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 7009, + _reserved: 0, + }, + ); + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Demand as u32, + extent_id: 2, + completion_slot: 7, + host_offset: extent_bytes as u64, + device_offset: 5 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 7010, + _reserved: 0, + }, + ); + push_cmd( + ctrl_ptr as usize, + TransferCommand { + opcode: Opcode::HostToDev as u32, + priority: Priority::Prefetch as u32, + extent_id: 1, + completion_slot: 8, + host_offset: 3 * extent_bytes as u64, + device_offset: 4 * extent_bytes as u64, + nbytes: extent_bytes as u64, + epoch: 2, + signal_value: 7011, + _reserved: 0, + }, + ); + wait_dev_comp(7, 7010); + wait_dev_comp(8, 7011); + wait_host_comp(ctrl_ptr as usize, 7, 7010); + wait_host_comp(ctrl_ptr as usize, 8, 7011); + // Confirm slot 7 did not regress after bg_copy_stream finished 7009 and 7011. + wait_dev_comp(7, 7010); + // Out-of-range extent is rejected cleanly without harming the channel. push_cmd( ctrl_ptr as usize, @@ -1712,7 +2287,7 @@ mod cuda_tests { assert_eq!(snap.rejected_cmds, 1); assert_eq!(snap.last_error, ErrorCode::ExtentOutOfRange as u32); assert_eq!(snap.bytes_disk_to_host, 2 * extent_bytes as u64); - assert_eq!(snap.bytes_host_to_dev, extent_bytes as u64); + assert_eq!(snap.bytes_host_to_dev, 6 * extent_bytes as u64); assert_eq!(snap.bytes_disk_to_dev, extent_bytes as u64); rt.stop().unwrap(); @@ -1853,10 +2428,14 @@ mod unit_tests { #[test] fn bounce_pool_geometry_rounds_before_capping_and_never_exceeds_reserve() { - // Normal 4 KiB alignment with 16 MiB extent stays bounded below 512 MiB. + // Normal 4 KiB alignment with 16 MiB extent fits 32 bounce slots within 512 MiB. assert_eq!( bounce_pool_geometry(16 << 20, 4096), - (DEFAULT_BOUNCE_SLOTS, 16 << 20) + (MAX_BOUNCE_SLOTS, 16 << 20) + ); + assert_eq!( + bounce_pool_geometry(32 << 20, 4096), + (DEFAULT_BOUNCE_SLOTS, 32 << 20) ); assert_eq!(max_bounce_pool_bytes(4096), MAX_BOUNCE_POOL_BYTES); diff --git a/helios/src/runtime_core/driver.rs b/helios/src/runtime_core/driver.rs index cff4e4c68..0fad3ba7b 100644 --- a/helios/src/runtime_core/driver.rs +++ b/helios/src/runtime_core/driver.rs @@ -298,6 +298,7 @@ driver! { context_get: "cuCtxGetCurrent"(*mut Handle); context_sync: "cuCtxSynchronize"(); context_destroy: "cuCtxDestroy_v2"(Handle); + ctx_get_stream_priority_range: "cuCtxGetStreamPriorityRange"(*mut c_int, *mut c_int); context_limit: "cuCtxSetLimit"(c_int, usize); context_get_limit: "cuCtxGetLimit"(*mut usize, c_int); context_cache: "cuCtxSetCacheConfig"(c_int); @@ -321,6 +322,8 @@ driver! { upload: "cuMemcpyHtoD_v2"(u64, *const c_void, usize); upload_async: "cuMemcpyHtoDAsync_v2"(u64, *const c_void, usize, Handle); stream_create: "cuStreamCreate"(*mut Handle, c_uint); + stream_create_with_priority: "cuStreamCreateWithPriority"(*mut Handle, c_uint, c_int); + stream_wait_event: "cuStreamWaitEvent"(Handle, Handle, c_uint); stream_query: "cuStreamQuery"(Handle); stream_sync: "cuStreamSynchronize"(Handle); stream_destroy: "cuStreamDestroy_v2"(Handle); @@ -332,6 +335,7 @@ driver! { event_sync: "cuEventSynchronize"(Handle); event_destroy: "cuEventDestroy_v2"(Handle); download: "cuMemcpyDtoH_v2"(*mut c_void, u64, usize); + download_async: "cuMemcpyDtoHAsync_v2"(*mut c_void, u64, usize, Handle); zero: "cuMemsetD8_v2"(u64, u8, usize); memset_d8_async: "cuMemsetD8Async"(u64, u8, usize, Handle); memset_d16_async: "cuMemsetD16Async"(u64, u16, usize, Handle); diff --git a/helios/src/runtime_core/memory.rs b/helios/src/runtime_core/memory.rs index c629f4b29..78131b1ec 100644 --- a/helios/src/runtime_core/memory.rs +++ b/helios/src/runtime_core/memory.rs @@ -34,13 +34,13 @@ pub(super) struct PlannedHostBudgets { pub async_transfer_host_caps: Vec, } -/// Per-rank `(available, total)` host RAM for sizing discrete-GPU pinned `AsyncTransfer` host +/// Per-host `(available, total)` host RAM for sizing discrete-GPU pinned `AsyncTransfer` host /// pools after reserving `host_future` bytes for prefix-cache offload and vision input windows. -fn async_transfer_host_ram(discrete_ranks: usize, host_future: u64) -> (u64, u64) { - let discrete_ranks = discrete_ranks.max(1) as u64; - let (host_available, host_total) = - flare_selene::offload::host_pool_budget_and_total(host_future).unwrap_or((0, 0)); - (host_available / discrete_ranks, host_total / discrete_ranks) +/// When `apply_reserve` is false (explicit `--pool-ram-memory`), Selene's implicit service and +/// system reserves are omitted so the caller's reserve or byte ceiling is not double-subtracted. +fn async_transfer_host_ram(host_future: u64, apply_reserve: bool) -> (u64, u64) { + flare_selene::offload::host_pool_budget_and_total_with_reserve(host_future, apply_reserve) + .unwrap_or((0, 0)) } /// Per-rank memory reservations planned for declared `Execution.async_transfers` channels. @@ -60,18 +60,23 @@ struct AsyncTransferBudget { /// channels. /// /// Registering pinned host memory with `cuMemHostRegister_v2` consumes 2 MiB of device VRAM per -/// GiB (`bytes / 512`) for GPU MMU page tables. On discrete GPUs, `device_reserve` accounts for -/// those page tables plus [`ASYNC_TRANSFER_DEVICE_MARGIN_BYTES`], while `host_reserve` accounts -/// for `HOST_POOL + bounce_pool` in host RAM (coordinated against `host_future`). On integrated -/// (unified-DRAM) GPUs such as GB10 and Jetson, `HOST_POOL`, `bounce_pool`, `DEVICE_POOL`, and KV -/// caches share one physical DRAM pool: `HOST_POOL` defaults to 0 unless `--pool-ram-memory` is -/// explicitly specified, explicit requests are bounded so `host_pool + bounce + page_tables + -/// margin <= host_ram_available`, and `device_reserve` deducts the full `host_pool + bounce_pool -/// + page_tables + margin` from the unified DRAM budget. +/// GiB (`bytes / 512`) for GPU MMU page tables. On discrete GPUs, `host_ram_available` and +/// `host_ram_total` are host-wide totals shared across `local_ranks` discrete ranks: any +/// `--pool-ram-memory` limit applies host-wide before dividing across `local_ranks`, +/// `device_reserve` charges GPU MMU page tables for the aggregate host-pinned footprint across +/// peer UVA contexts (`pinned * local_ranks / 512`) plus [`ASYNC_TRANSFER_DEVICE_MARGIN_BYTES`], +/// and `host_reserve` accounts for this rank's `HOST_POOL + bounce_pool` in host RAM (coordinated +/// against `host_future`). On integrated (unified-DRAM) GPUs such as GB10 and Jetson, +/// `HOST_POOL`, `bounce_pool`, `DEVICE_POOL`, and KV caches share one physical DRAM pool: +/// `HOST_POOL` defaults to 0 unless `--pool-ram-memory` is explicitly specified, explicit requests +/// are bounded so `host_pool + bounce + page_tables + margin <= host_ram_available`, and +/// `device_reserve` deducts the full `host_pool + bounce_pool + page_tables + margin` from the +/// unified DRAM budget. fn async_transfer_device_reserve( core: &Core, host_ram_available: u64, host_ram_total: u64, + local_ranks: usize, pool_ram_limit: Option, integrated: bool, ) -> AsyncTransferBudget { @@ -92,6 +97,7 @@ fn async_transfer_device_reserve( channel.alignment, )) }); + let ranks = local_ranks.max(1) as u64; let cap = if integrated { match pool_ram_limit { None => 0, @@ -107,11 +113,18 @@ fn async_transfer_device_reserve( } } } else { - let max_host_pool = host_ram_available.saturating_sub(total_bounce); + let host_bounce = total_bounce.saturating_mul(ranks); + let max_host_pool = (host_ram_available / ranks).saturating_sub(total_bounce); match pool_ram_limit { - Some(limit) => limit - .cap_bytes(host_ram_available, host_ram_total) - .min(max_host_pool), + Some(limit) => { + let host_cap = match limit.0 { + MemoryLimit::Reserve(reserve) => host_ram_available + .saturating_sub(host_bounce) + .saturating_sub(reserve), + _ => limit.cap_bytes(host_ram_available, host_ram_total), + }; + (host_cap / ranks).min(max_host_pool) + } None => max_host_pool, } }; @@ -128,7 +141,13 @@ fn async_transfer_device_reserve( host_pools = host_pools.saturating_add(host_pool); } let pinned = host_pools.saturating_add(total_bounce); - let page_tables = pinned.div_ceil(512); + // On multi-GPU UVA processes with peer access enabled, pinning host memory creates GPU MMU + // page-table entries across peer contexts; charge the aggregate host-pinned footprint. + let page_tables = if integrated { + pinned.div_ceil(512) + } else { + pinned.saturating_mul(ranks).div_ceil(512) + }; let device_reserve = if integrated { pinned .saturating_add(page_tables) @@ -1338,7 +1357,7 @@ impl NativeModel { let async_transfer_host_caps = if has_async_transfers { let discrete_ranks = self.ranks.iter().filter(|r| !r.integrated).count(); let (discrete_avail, discrete_total) = if discrete_ranks > 0 { - async_transfer_host_ram(discrete_ranks, host_future) + async_transfer_host_ram(host_future, options.pool_ram_limit.is_none()) } else { (0, 0) }; @@ -1349,18 +1368,20 @@ impl NativeModel { .zip(cores.iter()) .enumerate() { - let (ram_avail, ram_total) = if rank.integrated { + let (ram_avail, ram_total, local_ranks) = if rank.integrated { ( avail.saturating_sub(min_kv_reserve[idx]), observations[idx].total, + 1, ) } else { - (discrete_avail, discrete_total) + (discrete_avail, discrete_total, discrete_ranks) }; let planned = async_transfer_device_reserve( core, ram_avail, ram_total, + local_ranks, options.pool_ram_limit, rank.integrated, ); @@ -2662,7 +2683,7 @@ mod tests { // No async transfer channels -> zero device reserve and zero host cap. assert_eq!( - async_transfer_device_reserve(&p, 256 * gib, 512 * gib, None, false), + async_transfer_device_reserve(&p, 256 * gib, 512 * gib, 1, None, false), AsyncTransferBudget { device_reserve: 0, host_reserve: 0, @@ -2689,6 +2710,7 @@ mod tests { &p, 200 * gib, 256 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Bytes(160 * gib))), false, ); @@ -2705,6 +2727,7 @@ mod tests { &p, 200 * gib, 256 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), false, ); @@ -2715,18 +2738,51 @@ mod tests { bounce.div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); - // Negative RAM reserve reduces the planned host cap without double-subtracting. + // Negative RAM reserve leaves the full reserve free after accounting for bounce staging. let bres = async_transfer_device_reserve( &p, 100 * gib, 256 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Reserve(20 * gib))), false, ); - assert_eq!(bres.host_cap, 80 * gib); + assert_eq!(bres.host_cap, 80 * gib - bounce); + assert_eq!(bres.host_reserve, 80 * gib); assert_eq!( bres.device_reserve, - (80 * gib + bounce).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + (80 * gib).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + + // Per-host limits divide across local discrete ranks after applying the host-wide limit + // or reserve, and multi-rank UVA charges page tables for the aggregate host-pinned bytes. + let b_tp8_res = async_transfer_device_reserve( + &p, + 224 * gib, + 256 * gib, + 8, + Some(PoolMemoryLimit(MemoryLimit::Reserve(8 * gib))), + false, + ); + assert_eq!(b_tp8_res.host_cap, (224 * gib - 8 * bounce - 8 * gib) / 8); + assert_eq!(b_tp8_res.host_reserve * 8, 216 * gib); + assert_eq!( + b_tp8_res.device_reserve, + (216 * gib).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES + ); + let b_tp8_abs = async_transfer_device_reserve( + &p, + 224 * gib, + 256 * gib, + 8, + Some(PoolMemoryLimit(MemoryLimit::Bytes(64 * gib))), + false, + ); + assert_eq!(b_tp8_abs.host_cap, 8 * gib); + assert_eq!(b_tp8_abs.host_reserve, 8 * gib + bounce); + assert_eq!( + b_tp8_abs.device_reserve, + ((8 * gib + bounce) * 8).div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES ); // Large alignment (> 32 MiB) disables bounce staging, so reserve charges zero bounce bytes. @@ -2735,6 +2791,7 @@ mod tests { &p, 200 * gib, 256 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Bytes(0))), false, ); @@ -2745,7 +2802,7 @@ mod tests { // and leaves bounce-pool headroom in host RAM. p.execution.as_mut().unwrap().async_transfers[0].alignment = 4096; p.execution.as_mut().unwrap().async_transfers[0].max_host_pool_bytes = 512 * gib; - let b512 = async_transfer_device_reserve(&p, 700 * gib, 1024 * gib, None, false); + let b512 = async_transfer_device_reserve(&p, 700 * gib, 1024 * gib, 1, None, false); assert_eq!(b512.host_cap, 700 * gib - bounce); assert_eq!(b512.host_reserve, 512 * gib + bounce); assert_eq!( @@ -2754,7 +2811,7 @@ mod tests { ); // Discrete GPU with tight host RAM reserves bounce pool first so host_pool + bounce <= avail. - let b_tight = async_transfer_device_reserve(&p, 2 * gib, 64 * gib, None, false); + let b_tight = async_transfer_device_reserve(&p, 2 * gib, 64 * gib, 1, None, false); assert!(b_tight.host_reserve <= 2 * gib); assert_eq!(b_tight.host_cap, 2 * gib - bounce); } @@ -2787,7 +2844,7 @@ mod tests { // pool + page tables + stream margin is deducted from unified DRAM. let avail_above_kv = 76 * gib; let default_gb10 = - async_transfer_device_reserve(&p, avail_above_kv, 128 * gib, None, true); + async_transfer_device_reserve(&p, avail_above_kv, 128 * gib, 1, None, true); assert_eq!(default_gb10.host_cap, 0); let expected_bounce_only = bounce + bounce.div_ceil(512) + ASYNC_TRANSFER_DEVICE_MARGIN_BYTES; @@ -2800,6 +2857,7 @@ mod tests { &p, avail_above_kv, 128 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Bytes(16 * gib))), true, ); @@ -2818,6 +2876,7 @@ mod tests { &p, avail_above_kv, 128 * gib, + 1, Some(PoolMemoryLimit(MemoryLimit::Bytes(100 * gib))), true, ); diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index 6dcffc45c..5660d8b7d 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -1080,7 +1080,35 @@ impl NativeModel { unsafe { rank.prepare_async_transfers(files, core, planned_cap, global_rank)?; } - rank.start_async_transfers()?; + } + // Start all rank workers concurrently so per-rank fixed I/O buffer registration runs in + // parallel while guaranteeing every worker reaches `Running` before tuning graphs launch. + let handles = self.async_transfer_handles(); + let mut first_err: Option = None; + std::thread::scope(|scope| { + let joins: Vec<_> = handles + .iter() + .map(|ch| scope.spawn(move || ch.start())) + .collect(); + for j in joins { + match j.join() { + Ok(Ok(())) => {} + Ok(Err(err)) => { + first_err.get_or_insert(err); + } + Err(_) => { + first_err.get_or_insert_with(|| { + crate::Error::execution( + crate::ExecutionError::Manifest, + "async transfer startup thread panicked", + ) + }); + } + } + } + }); + if let Some(err) = first_err { + return Err(err); } let (dev_total_mapped, host_total_mapped) = self .ranks diff --git a/selene/src/offload.rs b/selene/src/offload.rs index 835ab9563..8a5982b75 100644 --- a/selene/src/offload.rs +++ b/selene/src/offload.rs @@ -976,8 +976,14 @@ pub fn host_pool_budget(future: u64) -> Result { /// Like [`host_pool_budget`], returning `(budget_bytes, total_host_ram_bytes)`. pub fn host_pool_budget_and_total(future: u64) -> Result<(u64, u64)> { + host_pool_budget_and_total_with_reserve(future, true) +} + +/// Like [`host_pool_budget_and_total`], allowing callers with an explicit host pool limit +/// to omit the implicit service and system reserves. +pub fn host_pool_budget_and_total_with_reserve(future: u64, apply_reserve: bool) -> Result<(u64, u64)> { let (available, total) = host_memory_bytes()?; - Ok((host_pool_budget_from(available, total, future, true), total)) + Ok((host_pool_budget_from(available, total, future, apply_reserve), total)) } /// Like [`host_pool_budget`], allowing callers with an explicit unified-memory limit diff --git a/verification/helios-lifecycle/AsyncTransfer.cfg b/verification/helios-lifecycle/AsyncTransfer.cfg index 5b25bc364..a33e21b30 100644 --- a/verification/helios-lifecycle/AsyncTransfer.cfg +++ b/verification/helios-lifecycle/AsyncTransfer.cfg @@ -3,6 +3,7 @@ CONSTANTS MaxBgIo = 1 MaxTotalDma = 2 MaxBgDma = 1 + MaxD2h = 1 BounceSlots = 1 MaxEpoch = 2 MaxQueue = 2 diff --git a/verification/helios-lifecycle/AsyncTransfer.tla b/verification/helios-lifecycle/AsyncTransfer.tla index 6b87d0e35..aa36a7b36 100644 --- a/verification/helios-lifecycle/AsyncTransfer.tla +++ b/verification/helios-lifecycle/AsyncTransfer.tla @@ -1,7 +1,7 @@ ------------------------ MODULE AsyncTransfer ------------------------ EXTENDS Naturals, Sequences, TLC -CONSTANTS MaxTotalIo, MaxBgIo, MaxTotalDma, MaxBgDma, BounceSlots, MaxEpoch, MaxQueue +CONSTANTS MaxTotalIo, MaxBgIo, MaxTotalDma, MaxBgDma, MaxD2h, BounceSlots, MaxEpoch, MaxQueue VARIABLE state Phases == 0..4 @@ -27,7 +27,11 @@ Initial == canRelease |-> 1, faultedDma |-> 0, unflushedIo |-> 0, - hwSignaledFaulted |-> 0] + hwSignaledFaulted |-> 0, + qD2h |-> 0, + inD2h |-> 0, + faultedD2h |-> 0, + hwSignaledFaultedD2h |-> 0] Init == state = Initial @@ -35,6 +39,7 @@ CanReleaseFor(st) == IF st.phase \in {IDLE, STOPPED} /\ st.inDemIo = 0 /\ st.inBgIo = 0 /\ st.inDemDma = 0 /\ st.inBgDma = 0 + /\ st.inD2h = 0 THEN 1 ELSE 0 WithRelease(st) == [st EXCEPT !.canRelease = CanReleaseFor(st)] @@ -45,16 +50,18 @@ Start(before, after) == Enqueue(before, after) == /\ before.phase = RUNNING - /\ before.qIo + before.qDma < MaxQueue + /\ before.qIo + before.qDma + before.qD2h < MaxQueue /\ \/ after = WithRelease([before EXCEPT !.qIo = @ + 1]) \/ after = WithRelease([before EXCEPT !.qDma = @ + 1]) + \/ after = WithRelease([before EXCEPT !.qD2h = @ + 1]) \/ after = before CancelEpoch(before, after) == /\ before.phase = RUNNING /\ \E nextEp \in (before.activeEpoch + 1)..MaxEpoch, dropIo \in 0..before.qIo, - dropDma \in 0..before.qDma : + dropDma \in 0..before.qDma, + dropD2h \in 0..before.qD2h : \E retBounce \in 0..before.bQDma : /\ retBounce <= dropDma /\ (before.bQDma - retBounce) <= (before.qDma - dropDma) @@ -62,6 +69,7 @@ CancelEpoch(before, after) == !.activeEpoch = nextEp, !.qIo = @ - dropIo, !.qDma = @ - dropDma, + !.qD2h = @ - dropD2h, !.bQDma = @ - retBounce, !.freeBounce = @ + retBounce]) @@ -147,6 +155,36 @@ MarkDmaFaulted(before, after) == !.faultedDma = @ + 1, !.hwSignaledFaulted = @ + hwSignaled]) +DispatchD2h(before, after) == + /\ before.phase = RUNNING + /\ before.qD2h > 0 + /\ before.inD2h < MaxD2h + /\ after = WithRelease([before EXCEPT + !.qD2h = @ - 1, + !.inD2h = @ + 1]) + +CompleteD2h(before, after) == + /\ before.phase \in {RUNNING, DRAINING, FAILED_DRAIN} + /\ before.inD2h > 0 + /\ \E wasFaulted \in 0..1, wasHwSignaled \in 0..1 : + /\ wasFaulted <= before.faultedD2h + /\ (before.faultedD2h - wasFaulted) <= (before.inD2h - 1) + /\ wasHwSignaled <= wasFaulted + /\ wasHwSignaled <= before.hwSignaledFaultedD2h + /\ (before.hwSignaledFaultedD2h - wasHwSignaled) <= (before.faultedD2h - wasFaulted) + /\ after = WithRelease([before EXCEPT + !.inD2h = @ - 1, + !.faultedD2h = @ - wasFaulted, + !.hwSignaledFaultedD2h = @ - wasHwSignaled]) + +MarkD2hFaulted(before, after) == + /\ before.phase \in {RUNNING, DRAINING} + /\ before.faultedD2h < before.inD2h + /\ \E hwSignaled \in 0..1 : + after = WithRelease([before EXCEPT + !.faultedD2h = @ + 1, + !.hwSignaledFaultedD2h = @ + hwSignaled]) + BeginDrain(before, after) == \/ /\ before.phase = IDLE /\ after = WithRelease([before EXCEPT !.phase = STOPPED]) @@ -155,6 +193,7 @@ BeginDrain(before, after) == !.phase = DRAINING, !.qIo = 0, !.qDma = 0, + !.qD2h = 0, !.bQDma = 0, !.freeBounce = @ + before.bQDma]) @@ -162,8 +201,10 @@ FinishDrainOk(before, after) == /\ before.phase = DRAINING /\ before.inDemIo = 0 /\ before.inBgIo = 0 /\ before.inDemDma = 0 /\ before.inBgDma = 0 + /\ before.inD2h = 0 /\ before.unflushedIo = 0 /\ before.faultedDma = 0 /\ before.hwSignaledFaulted = 0 + /\ before.faultedD2h = 0 /\ before.hwSignaledFaultedD2h = 0 /\ before.freeBounce = BounceSlots /\ after = WithRelease([before EXCEPT !.phase = STOPPED]) @@ -184,6 +225,9 @@ Step(before, after) == \/ FinishDrainFail(before, after) \/ MarkDmaFaulted(before, after) \/ FlushIo(before, after) + \/ DispatchD2h(before, after) + \/ CompleteD2h(before, after) + \/ MarkD2hFaulted(before, after) Next == Step(state, state') \/ UNCHANGED state @@ -204,9 +248,13 @@ WellTyped(st) == /\ st.faultedDma \in 0..MaxTotalDma /\ st.unflushedIo \in 0..MaxTotalIo /\ st.hwSignaledFaulted \in 0..MaxTotalDma + /\ st.qD2h \in 0..MaxQueue + /\ st.inD2h \in 0..MaxD2h + /\ st.faultedD2h \in 0..MaxD2h + /\ st.hwSignaledFaultedD2h \in 0..MaxD2h NoUnmapWhileInflightAt(st) == - (st.inDemIo + st.inBgIo + st.inDemDma + st.inBgDma > 0) => st.canRelease = 0 + (st.inDemIo + st.inBgIo + st.inDemDma + st.inBgDma + st.inD2h > 0) => st.canRelease = 0 FailedDrainRetainsResourcesAt(st) == st.phase = FAILED_DRAIN => st.canRelease = 0 @@ -215,10 +263,13 @@ StoppedHasZeroInflightAt(st) == st.phase = STOPPED => /\ st.inDemIo = 0 /\ st.inBgIo = 0 /\ st.inDemDma = 0 /\ st.inBgDma = 0 + /\ st.inD2h = 0 /\ st.unflushedIo = 0 /\ st.faultedDma = 0 /\ st.hwSignaledFaulted = 0 - /\ st.qIo = 0 /\ st.qDma = 0 + /\ st.faultedD2h = 0 + /\ st.hwSignaledFaultedD2h = 0 + /\ st.qIo = 0 /\ st.qDma = 0 /\ st.qD2h = 0 /\ st.freeBounce = BounceSlots BoundedHardwareDepthAt(st) == @@ -226,6 +277,7 @@ BoundedHardwareDepthAt(st) == /\ st.inBgDma <= MaxBgDma /\ st.inDemIo + st.inBgIo <= MaxTotalIo /\ st.inDemDma + st.inBgDma <= MaxTotalDma + /\ st.inD2h <= MaxD2h BounceSlotConservationAt(st) == /\ st.freeBounce + st.bInIo + st.bQDma + st.bInDma = BounceSlots @@ -234,15 +286,16 @@ BounceSlotConservationAt(st) == /\ st.bInDma <= st.inDemDma + st.inBgDma DrainingHasEmptyQueuesAt(st) == - st.phase = DRAINING => (st.qIo = 0 /\ st.qDma = 0 /\ st.bQDma = 0) + st.phase = DRAINING => (st.qIo = 0 /\ st.qDma = 0 /\ st.qD2h = 0 /\ st.bQDma = 0) CanReleaseExactAt(st) == st.canRelease = CanReleaseFor(st) FaultedDmaRetainsOwnershipAt(st) == /\ st.faultedDma <= st.inDemDma + st.inBgDma - /\ st.faultedDma > 0 => st.canRelease = 0 - /\ st.phase = STOPPED => st.faultedDma = 0 + /\ st.faultedD2h <= st.inD2h + /\ (st.faultedDma > 0 \/ st.faultedD2h > 0) => st.canRelease = 0 + /\ st.phase = STOPPED => (st.faultedDma = 0 /\ st.faultedD2h = 0) UnflushedIoBoundedAt(st) == /\ st.unflushedIo <= st.inDemIo + st.inBgIo @@ -251,8 +304,9 @@ UnflushedIoBoundedAt(st) == HwSignaledFaultedSafeAt(st) == /\ st.hwSignaledFaulted <= st.faultedDma - /\ st.hwSignaledFaulted > 0 => st.canRelease = 0 - /\ st.phase = STOPPED => st.hwSignaledFaulted = 0 + /\ st.hwSignaledFaultedD2h <= st.faultedD2h + /\ (st.hwSignaledFaulted > 0 \/ st.hwSignaledFaultedD2h > 0) => st.canRelease = 0 + /\ st.phase = STOPPED => (st.hwSignaledFaulted = 0 /\ st.hwSignaledFaultedD2h = 0) ObservedSafe(st) == /\ WellTyped(st) @@ -283,7 +337,8 @@ Projection(st) == <> + st.faultedDma, st.unflushedIo, st.hwSignaledFaulted, + st.qD2h, st.inD2h, st.faultedD2h, st.hwSignaledFaultedD2h>> Decode(v) == [phase |-> v[1], @@ -301,7 +356,11 @@ Decode(v) == canRelease |-> v[13], faultedDma |-> v[14], unflushedIo |-> v[15], - hwSignaledFaulted |-> v[16]] + hwSignaledFaulted |-> v[16], + qD2h |-> v[17], + inD2h |-> v[18], + faultedD2h |-> v[19], + hwSignaledFaultedD2h |-> v[20]] ObservedState(v) == Decode(v) @@ -318,6 +377,9 @@ ActionMatches(before, kind, after) == \/ /\ kind = 10 /\ FinishDrainFail(before, after) \/ /\ kind = 11 /\ MarkDmaFaulted(before, after) \/ /\ kind = 12 /\ FlushIo(before, after) + \/ /\ kind = 13 /\ DispatchD2h(before, after) + \/ /\ kind = 14 /\ CompleteD2h(before, after) + \/ /\ kind = 15 /\ MarkD2hFaulted(before, after) AllowedEdge(edge) == LET before == ObservedState(edge[1]) diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index fab1ad648..f9810ed8f 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -33,7 +33,7 @@ ("CheckpointReservation", "scheduler::checkpoint_lifecycle_tests::", "CHECKPOINT_RESERVATION_EDGE ", 16), ("AsyncTransfer", "async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model", - "ASYNC_TRANSFER_EDGE ", 16)] + "ASYNC_TRANSFER_EDGE ", 20)] MODELS = [check[0] for check in CHECKS] + ["RankDispatch"] @@ -402,7 +402,8 @@ def run_aux(test): "FinishDrainOk(before, after) ==\n" " /\\ before.phase = DRAINING\n" " /\\ before.inDemIo = 0 /\\ before.inBgIo = 0\n" - " /\\ before.inDemDma = 0 /\\ before.inBgDma = 0", + " /\\ before.inDemDma = 0 /\\ before.inBgDma = 0\n" + " /\\ before.inD2h = 0", "FinishDrainOk(before, after) ==\n" " /\\ before.phase = DRAINING", "StoppedHasZeroInflight"), @@ -452,6 +453,23 @@ def run_aux(test): " !.faultedDma = @ - wasFaulted,\n" " !.hwSignaledFaulted = @])", "HwSignaledFaultedSafe"), + ("AsyncTransfer", + "MarkD2hFaulted(before, after) ==\n" + " /\\ before.phase \\in {RUNNING, DRAINING}\n" + " /\\ before.faultedD2h < before.inD2h\n" + " /\\ \\E hwSignaled \\in 0..1 :\n" + " after = WithRelease([before EXCEPT\n" + " !.faultedD2h = @ + 1,\n" + " !.hwSignaledFaultedD2h = @ + hwSignaled])", + "MarkD2hFaulted(before, after) ==\n" + " /\\ before.phase \\in {RUNNING, DRAINING}\n" + " /\\ before.faultedD2h < before.inD2h\n" + " /\\ \\E hwSignaled \\in 0..1 :\n" + " after = WithRelease([before EXCEPT\n" + " !.faultedD2h = @ + 1,\n" + " !.hwSignaledFaultedD2h = @ + hwSignaled,\n" + " !.inD2h = 0])", + "FaultedDmaRetainsOwnership"), ] with ThreadPoolExecutor(max_workers=min(args.jobs, len(model_mutations))) as pool: futures = [ @@ -791,11 +809,11 @@ def run_aux(test): ]) check_mutations(cargo, ROOT / "helios/src/async_transfer/scheduler.rs", CHECKS[8][1], [ ("unconfirmed async transfer drain", - "if stream_drained && self.inflight_io.is_empty() && self.inflight_dma.is_empty() {", - "if true {", + "if stream_drained\n && self.inflight_io.is_empty()\n && self.inflight_dma.is_empty()\n && self.inflight_d2h.is_empty()", + "if true", "unconfirmed drain must not complete into Stopped"), ("exceeded background DMA cap", - "if prio.is_background() && bg_used >= self.max_bg_dma {", + "if prio.is_background() && (dem_active || bg_used >= self.max_bg_dma) {", "if false {", "background DMA depth exceeded cap"), ("leaked bounce slot on drain", @@ -811,21 +829,29 @@ def run_aux(test): " signal_value: op.signal_value,", "failed transfer must signal error sentinel, not success value"), ("failed dma signaled success cookie", - " completion_error_sentinel(ErrorCode::CudaFailure)\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },", - " op.signal_value\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },", + " completion_error_sentinel(ErrorCode::CudaFailure)\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },\n bytes_disk_to_host: 0,\n bytes_host_to_dev: if ok && !op.from_disk { op.nbytes } else { 0 },", + " op.signal_value\n },\n error: if ok {\n ErrorCode::Ok\n } else {\n ErrorCode::CudaFailure\n },\n bytes_disk_to_host: 0,\n bytes_host_to_dev: if ok && !op.from_disk { op.nbytes } else { 0 },", "failed transfer must signal error sentinel, not success value"), ("faulted dma freed bounce slot early", - " op.faulted = true;\n op.hardware_signaled = hardware_signaled;", - " op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n if let Some(slot) = op.bounce_slot.take() { self.free_bounce_slots.push(slot); }", + " let op = self.inflight_dma.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;", + " let op = self.inflight_dma.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n if let Some(slot) = op.bounce_slot.take() { self.free_bounce_slots.push(slot); }", "faulted DMA must retain inflight and bounce ownership"), ("unflushed io completed ok before flush", " if ok && !self.inflight_io[pos].flushed {\n return None;\n }", " if false && ok && !self.inflight_io[pos].flushed {\n return None;\n }", "unflushed IO must not complete with ok=true before kernel submission"), ("hardware-signaled faulted dma clobbered completion slot", - " let completion_slot = if hardware_signaled {\n None\n } else {\n op.completion_slot\n };", - " let completion_slot = op.completion_slot;", + " let op = self.inflight_dma.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n let completion_slot = if hardware_signaled {\n None\n } else {\n op.completion_slot\n };", + " let op = self.inflight_dma.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n let completion_slot = op.completion_slot;", "hardware-signaled faulted DMA must not overwrite live/reused completion slot"), + ("inflight d2h allowed stopped drain", + " if stream_drained\n && self.inflight_io.is_empty()\n && self.inflight_dma.is_empty()\n && self.inflight_d2h.is_empty()", + " if stream_drained\n && self.inflight_io.is_empty()\n && self.inflight_dma.is_empty()", + "unconfirmed drain must not complete into Stopped"), + ("hardware-signaled faulted d2h clobbered completion slot", + " let op = self.inflight_d2h.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n let completion_slot = if hardware_signaled {\n None\n } else {\n op.completion_slot\n };", + " let op = self.inflight_d2h.iter_mut().find(|op| op.op_id == op_id)?;\n if op.faulted {\n return None;\n }\n op.faulted = true;\n op.hardware_signaled = hardware_signaled;\n let completion_slot = op.completion_slot;", + "hardware-signaled faulted D2H must not overwrite live/reused completion slot"), ]) restored_bin = build_test_binary(cargo) run_observed_checks(restored_bin, directory, args.java, jar, args.jobs) From b2f10deda51e390896017e97555975b174d69a92 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Sat, 5 Dec 2026 04:35:03 -0800 Subject: [PATCH 2/2] docs: align AsyncTransfer CLI, completion monotonicity, and lifecycle docs Three documentation discrepancies remained between the AsyncTransfer runtime changes and the repository specifications: the sample `flare.toml` in `docs/cli-design.md` still described `pool_ram` as per-rank while the CLI flag table documented per-host budgeting divided across local discrete ranks; `helios/manifest.md` and `docs/runtime-core-design.md` documented per-slot monotonic non-regression only for host completion mirrors and omitted `device_completions` monotonic non-regression and sticky bit-63 fault sentinels; and `verification/helios-lifecycle/README.md` still described the 16-integer `AsyncTransfer` model without `MaxD2h = 1`, D2H transitions, or D2H projection fields. Before this change: - `docs/cli-design.md` described `[memory] pool_ram` as a per-rank ceiling. - `helios/manifest.md` and `docs/runtime-core-design.md` stated monotonic `fetch_max` only for host completion mirrors. - `verification/helios-lifecycle/README.md` listed 16 projection integers and omitted `MaxD2h = 1`, `dispatch_d2h`, `complete_d2h`, and `mark_d2h_faulted`. After this change: - `docs/cli-design.md` describes `[memory] pool_ram` as a per-host ceiling divided across local discrete ranks, matching `--pool-ram-memory`. - `helios/manifest.md` and `docs/runtime-core-design.md` specify per-slot lifetime monotonic non-regression and sticky bit-63 fault sentinels on both `device_completions` and host completion mirrors. - `verification/helios-lifecycle/README.md` documents `MaxD2h = 1`, the three D2H transitions, D2H fault and drain invariants, and all 20 projection fields matching `AsyncTransfer.cfg` and `helios/src/async_transfer/lifecycle_tests.rs`. Expected result: operators, recipe authors, and verification maintainers have specifications that match the implemented `--pool-ram-memory` budgeting, multi-stream `device_completions` contract, and 20-integer `AsyncTransfer` formal lifecycle model. Validation: inspected `git diff --cached` against `docs/cli-design.md`, `helios/src/async_transfer/worker.rs`, `verification/helios-lifecycle/AsyncTransfer.cfg`, and `helios/src/async_transfer/lifecycle_tests.rs`. Documentation-only change; no tests were rerun per request. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: Luke Alonso --- docs/cli-design.md | 2 +- docs/runtime-core-design.md | 12 ++++--- helios/manifest.md | 9 +++-- verification/helios-lifecycle/README.md | 45 ++++++++++++++----------- 4 files changed, 40 insertions(+), 28 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index d07791b9b..c633f8222 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1415,7 +1415,7 @@ max_concurrency = 4 [memory] reserve = "0" # GPU memory left for processes started later. # pool_vram = "" # Per-GPU ceiling for Capacity::DEVICE_POOL allocations (0, 12G, -8G, 0.25). -# pool_ram = "" # Per-rank ceiling for pinned AsyncTransfer host pools (0, 32G, -16G, 0.5). +# pool_ram = "" # Per-host ceiling for pinned AsyncTransfer host pools, divided across local discrete ranks (0, 32G, -16G, 0.5). [prefix_cache] memory = "" # Warm checkpoints and CPU inputs; empty or 0: no warm tier. Intake is additional. diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 763c7d522..b281dcdb2 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -766,10 +766,14 @@ H2D, and normal-priority D2H Copy Engine streams plus event pool, and publishes `ControlHeader.worker_state = Running` before executing `Execution.tuning_graphs`. Demand H2D, background H2D, and D2H transfers execute on separate non-blocking Copy Engine streams (with `cuStreamWaitEvent` -serializing cross-stream reuse of the same completion slot), host completion -mirrors advance monotonically via `fetch_max`, and storage or CUDA transfer -failures publish the bit-63 fault sentinel (`COMPLETION_ERROR_BIT | error_code`) -rather than the caller's requested success cookie. Partial DMA submission +serializing cross-stream reuse of the same completion slot). Both +`device_completions` and host completion mirrors enforce per-slot lifetime +monotonic non-regression (host mirrors via atomic `fetch_max`; +`device_completions` by skipping writes smaller than the highest value already +queued for that slot), so priority-preempted transfers cannot regress a slot +and bit-63 fault sentinels (`COMPLETION_ERROR_BIT | error_code`, published on +storage or CUDA transfer failures instead of the caller's requested success +cookie) remain sticky on both host and device completion slots. Partial DMA submission failures after `cuMemcpyHtoDAsync_v2` or `cuMemcpyDtoHAsync_v2` retain their in-flight and bounce-slot ownership until hardware stream drain is confirmed. Shutdown stops and drains all async transfer channels after compute streams drain (bounding Linux `io_uring` waits diff --git a/helios/manifest.md b/helios/manifest.md index 9c6826d14..c3cee749e 100644 --- a/helios/manifest.md +++ b/helios/manifest.md @@ -191,9 +191,12 @@ Each `AsyncTransfer` entry declares: `cuStreamWriteValue64_v2` (when device attribute `CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 122` is supported) after Copy Engine DMA completes (using `cuStreamWaitEvent` whenever different Copy - Engine streams reuse the same completion slot), with monotonic `fetch_max` - host completion mirrors so deferred DMA mirrors cannot regress reused - completion slots. + Engine streams reuse the same completion slot). Both `device_completions` and + host completion mirrors enforce per-slot lifetime monotonic non-regression + (host mirrors via atomic `fetch_max`; `device_completions` by skipping any + write smaller than the highest value already queued for that slot), so + priority-preempted transfers and deferred DMA mirrors cannot regress reused + completion slots and bit-63 fault sentinels are sticky once published. - `max_host_pool_bytes`: optional ceiling on the channel's pinned host pool (`0` disables the host pool). - `alignment`: power-of-two direct-I/O and offset alignment (`>= 4096`). diff --git a/verification/helios-lifecycle/README.md b/verification/helios-lifecycle/README.md index 30e57924c..87928fc2c 100644 --- a/verification/helios-lifecycle/README.md +++ b/verification/helios-lifecycle/README.md @@ -355,33 +355,38 @@ and scheduler cancellation require their separate contracts and execution tests. `AsyncTransfer.tla` checks bounded asynchronous extent-transfer scheduling and drain ownership across five phases (`IDLE`, `RUNNING`, `DRAINING`, `STOPPED`, `FAILED_DRAIN`) with `MaxTotalIo = 2`, `MaxBgIo = 1`, `MaxTotalDma = 2`, -`MaxBgDma = 1`, `BounceSlots = 1`, `MaxEpoch = 2`, and `MaxQueue = 2`. -Invariants enforce no memory release while any storage I/O or Copy Engine DMA is -in flight (`NoUnmapWhileInflight`), permanent retention after failed drain +`MaxBgDma = 1`, `MaxD2h = 1`, `BounceSlots = 1`, `MaxEpoch = 2`, and +`MaxQueue = 2`. +Invariants enforce no memory release while any storage I/O, H2D DMA, or D2H DMA +is in flight (`NoUnmapWhileInflight`), permanent retention after failed drain (`FailedDrainRetainsResources`), zero in-flight work when stopped -(`StoppedHasZeroInflight`), bounded total and background hardware concurrency -(`BoundedHardwareDepth`), exact conservation of internal bounce slots across -in-flight I/O, queued follow-on DMA, and in-flight DMA (`BounceSlotConservation`), -drained queues once shutdown begins (`DrainingHasEmptyQueues`), retained -in-flight and bounce ownership after partial CUDA DMA submission faults until -confirmed hardware drain (`FaultedDmaRetainsOwnership`), bounded unflushed -storage SQE counts (`UnflushedIoBounded`), and suppression of host error-sentinel -writes for faulted DMAs whose completion slot was already signaled by hardware +(`StoppedHasZeroInflight`), bounded total, background, and D2H hardware +concurrency (`BoundedHardwareDepth`), exact conservation of internal bounce +slots across in-flight I/O, queued follow-on DMA, and in-flight DMA +(`BounceSlotConservation`), drained queues once shutdown begins +(`DrainingHasEmptyQueues`), retained in-flight and bounce ownership after +partial CUDA H2D or D2H submission faults until confirmed hardware drain +(`FaultedDmaRetainsOwnership`), bounded unflushed storage SQE counts +(`UnflushedIoBounded`), and suppression of host error-sentinel writes for +faulted H2D or D2H DMAs whose completion slot was already signaled by hardware (`HwSignaledFaultedSafe`). `async_transfer::lifecycle_tests::async_transfer_scheduler_matches_lifecycle_model` drives production `TransferScheduler` transitions (`start`, `enqueue`, `cancel_epoch`, `dispatch_io`, `mark_io_flushed`, `complete_io`, `dispatch_dma`, -`complete_dma`, `mark_dma_faulted`, `begin_drain`, `finish_drain`, `fail_drain`) +`complete_dma`, `mark_dma_faulted`, `dispatch_d2h`, `complete_d2h`, +`mark_d2h_faulted`, `begin_drain`, `finish_drain`, `fail_drain`) across priority preemption, epoch cancellation, partial and full SQE flushes, -unflushed-completion rejection, fused bounce-staged transfers, partial-DMA fault -retention, hardware-signaled vs. host-signaled faulted DMA notices, and confirmed -vs. failed drain. Its 16-integer projection carries the phase, active epoch, -queued I/O and DMA counts, demand/background in-flight I/O and DMA counts, -bounce-slot partition, release predicate, faulted in-flight DMA count, unflushed -I/O count, and hardware-signaled faulted DMA count. Linux `io_uring` submission, -CUDA Copy Engine ordering, `cuStreamWriteValue64` completion signaling, and -pinned host memory registration require their separate CUDA integration tests. +unflushed-completion rejection, fused bounce-staged transfers, partial-DMA and +D2H fault retention, hardware-signaled vs. host-signaled faulted DMA notices, +and confirmed vs. failed drain. Its 20-integer projection carries the phase, +active epoch, queued I/O and DMA counts, demand/background in-flight I/O and +DMA counts, bounce-slot partition, release predicate, faulted in-flight DMA +count, unflushed I/O count, hardware-signaled faulted DMA count, and queued, +in-flight, faulted, and hardware-signaled faulted D2H counts. Linux `io_uring` +submission, CUDA Copy Engine ordering, `cuStreamWriteValue64` completion +signaling, and pinned host memory registration require their separate CUDA +integration tests. ## Assumptions and limits