From 1870a27304567f082011317783eac71a2c2779b0 Mon Sep 17 00:00:00 2001 From: yatesdr <6937857+yatesdr@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:40:04 -0500 Subject: [PATCH 1/2] helios: gate offload Copy Engine batches during peer-copy graphs On discrete PCIe GPUs (observed on SM120 RTX PRO 6000 under CUDA driver 595.99.02), tensor-parallel CUDA graphs whose collectives drive peer-to-peer transfers through in-graph Copy Engine nodes (`Node::Copy` with a `Memory::Peer` endpoint, such as `b12x` `PCIeDmaAllReduce`) deadlock when prefix-cache offload workers issue concurrent host-device Copy Engine batches on the same devices. Even a single concurrent device-to-host copy from an unrelated allocation on the offload stream stalls both ranks inside the graph's peer-copy collectives. Coordinating host offload batches against peer-copy graph execution directly in Helios eliminates the deadlock for already-exported model packages without changing the package format, scheduling policy, or per-model behavior. Detect peer-copy graphs structurally during CUDA graph reconstruction in `NativeResources`: record `peer_copy_graphs[i] = true` whenever any `Node::Copy` node in graph `i` has a `Memory::Peer` source or destination, carry that vector on `ExecutionManifest`, and union it across local `RankPeers::Threads` manifests in `RankExecutor`. Share one `offload::CopyEngineGate` per `NativeModel` across `RankExecutor`, local `offload::Binding` / `offload::open_with_gate`, and `NativeModel::attach_offload` (for Selene pool workers). When submitting a graph flagged with peer copies, `RankExecutor` acquires a `PeerGraphGuard` (blocking until in-flight offload batches drain and giving waiting peer-copy graphs priority over new batches) and releases it on `poll` completion or after `close` drains. Offload workers acquire an `OffloadBatchGuard` per `BATCH_BYTES` batch in uncompressed `RankWorker::run`, CPU-codec `copy_spans_batch`, and all five GPU-codec capture/restore entry points (preserving strict `gpu.codec` before `CopyEngineGate` lock order and draining the CUDA stream before releasing the guard on error). Graphs without peer-copy nodes incur no gate locking. Eliminates the TP2 prefill deadlock under concurrent prefix-cache offload while preserving multi-rank offload concurrency outside peer-copy graphs and maintaining warm/restore correctness and burst latency. Validation: - `RUSTFLAGS="-D warnings" cargo check --locked --all-targets` passed for `helios --features runtime-core,server`, `flare`, `flare-cli`, and `heliopause --lib` (0 warnings). - Unit tests passed: `helios` `offload::copy_gate` and `execution::ranks` (5/5), `helios` `server::runtime` and `execution::threaded` (162/162), `flare` (245/245), and `flare-cli` (200/201 under root and 200/201 under non-root, with all 201 distinct tests passing across the two permission contexts). - SM120 4-GPU CUDA `helios` `offload::` tests passed: 19/19 default tests plus 6/6 ignored `offload::transfer::` GPU/CPU codec and multi-GPU split pool tests (`FLARE_RUN_CUDA_TESTS=1`). - Live SM120 TP2 (`--gpus 0,1`, `--prefix-cache-memory 4G`, 16 GiB disk tier) on `Qwen3.8-Flash-Next` (`--lossless-kv-compression off`): cold, warm (0/6 pos0 mismatches, 5.08x speedup), restart + disk restore (0/6 pos0 mismatches, 2.45x speedup), 8-way burst with 2 aborts (8/8, 4.15s), and 5x 8-way uncached 6578-token bursts (40/40 HTTP 200, 4.68-4.83s/burst; unpatched `main` deadlocked during the first burst). - Live SM120 TP2 on `GLM-5.3-Flash` (`--lossless-kv-compression gpu`): cold, warm (0/96 token mismatches, 3.50x speedup), restart + restore (0/96 token mismatches, 1.55x speedup), and 8-way burst with 2 aborts (8/8, 5.88s). Limitations: - Tested on single-host threaded TP2 on SM120 (RTX PRO 6000) with local DRAM and disk tiers (uncompressed and GPU KV codec). Multi-host TP, live Selene pool serving, CPU KV codec live serving, and non-SM120 GPUs were not exercised live (though pool and CPU codec paths share the same `CopyEngineGate` wiring and unit/CUDA codec tests). Fixes #627 Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b --- heliopause/src/python.rs | 1 + helios/src/execution/manifest.rs | 9 + helios/src/execution/ranks.rs | 163 +++++++++++++---- helios/src/execution/tests.rs | 1 + helios/src/model/contract.rs | 2 +- helios/src/model/testing.rs | 1 + helios/src/offload/copy_gate.rs | 263 +++++++++++++++++++++++++++ helios/src/offload/mod.rs | 25 ++- helios/src/offload/transfer.rs | 60 +++++- helios/src/offload/transfer/codec.rs | 74 ++++++-- helios/src/runtime_core/mod.rs | 12 ++ helios/src/runtime_core/model.rs | 19 +- helios/src/runtime_core/serving.rs | 3 + helios/src/server/runtime.rs | 11 +- 14 files changed, 572 insertions(+), 72 deletions(-) create mode 100644 helios/src/offload/copy_gate.rs diff --git a/heliopause/src/python.rs b/heliopause/src/python.rs index 4b6bff73c..1edaf617b 100644 --- a/heliopause/src/python.rs +++ b/heliopause/src/python.rs @@ -328,6 +328,7 @@ pub(crate) fn execution_manifest(value: &Bound<'_, PyAny>) -> PyResult, pub graphs: Vec, + /// True for each graph index whose reconstructed CUDA graph contains at least + /// one `Node::Copy` endpoint in peer memory (`Memory::Peer`). Empty when not + /// populated (e.g. non-core manifests); absent entries default to `false`. + pub peer_copy_graphs: Vec, pub tuning_graphs: Vec, /// Optional dedicated persistent worker graphs launched once after startup tuning. pub persistent_workers: Vec, } impl ExecutionManifest { + /// Whether graph `index` executes in-graph peer-to-peer Copy Engine nodes. + pub fn has_peer_copies(&self, index: usize) -> bool { + self.peer_copy_graphs.get(index).copied().unwrap_or(false) + } + fn validate_persistent_workers(&self) -> Result<()> { if self.persistent_workers.len() > 1 { return Err(Error::execution( diff --git a/helios/src/execution/ranks.rs b/helios/src/execution/ranks.rs index e5d193a7c..5624a65f7 100644 --- a/helios/src/execution/ranks.rs +++ b/helios/src/execution/ranks.rs @@ -6,22 +6,51 @@ //! Direct scheduler execution on one CUDA rank or a coordinated rank group. +use std::collections::VecDeque; +use std::sync::Arc; + use super::{ ExecutionManifest, FrameCompletion, GraphExecutor, RankStream, TensorParallelExecutor, Upload, }; -use crate::{Result, Shutdown, cache::Fence}; +use crate::{ + Result, Shutdown, + cache::Fence, + offload::{CopyEngineGate, PeerGraphGuard}, +}; pub enum RankPeers { Processes(Vec), Threads(Vec), } -pub(crate) enum RankExecutor { +enum RankExecutorInner { Threaded(Box), Local(Box), Parallel(Box), } +pub(crate) struct RankExecutor { + inner: RankExecutorInner, + copy_gate: Option>, + peer_copy_graphs: Vec, + peer_guards: VecDeque<(Fence, PeerGraphGuard)>, +} + +fn merge_peer_copy_graphs(manifest: &ExecutionManifest, peers: Option<&RankPeers>) -> Vec { + let mut merged = manifest.peer_copy_graphs.clone(); + if let Some(RankPeers::Threads(ranks)) = peers { + for peer in ranks { + if peer.peer_copy_graphs.len() > merged.len() { + merged.resize(peer.peer_copy_graphs.len(), false); + } + for (dst, &src) in merged.iter_mut().zip(&peer.peer_copy_graphs) { + *dst |= src; + } + } + } + merged +} + impl RankExecutor { /// # Safety /// Prepared graphs, contexts, buffers, and b12x IPC allocations must remain @@ -30,18 +59,26 @@ impl RankExecutor { manifest: ExecutionManifest, peers: Option, ) -> Result { - match peers { + let copy_gate = manifest.offload.as_ref().map(|b| b.copy_gate()); + let peer_copy_graphs = merge_peer_copy_graphs(&manifest, peers.as_ref()); + let inner = match peers { Some(RankPeers::Threads(ranks)) => { unsafe { super::threaded::ThreadedExecutor::new(manifest, ranks) } - .map(|executor| Self::Threaded(Box::new(executor))) + .map(|executor| RankExecutorInner::Threaded(Box::new(executor)))? } Some(RankPeers::Processes(peers)) => { unsafe { TensorParallelExecutor::new(manifest, peers) } - .map(|executor| Self::Parallel(Box::new(executor))) + .map(|executor| RankExecutorInner::Parallel(Box::new(executor)))? } None => unsafe { GraphExecutor::new(manifest) } - .map(|executor| Self::Local(Box::new(executor))), - } + .map(|executor| RankExecutorInner::Local(Box::new(executor)))?, + }; + Ok(Self { + inner, + copy_gate, + peer_copy_graphs, + peer_guards: VecDeque::new(), + }) } pub(crate) fn submit( @@ -50,70 +87,116 @@ impl RankExecutor { uploads: &[Upload<'_>], grammar: bool, ) -> Result> { - match self { - Self::Local(executor) => executor.submit(graph, uploads, grammar), - Self::Parallel(executor) => executor.submit(graph, uploads, grammar), - Self::Threaded(executor) => executor.submit(graph, uploads, grammar), + let guard = if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) { + self.copy_gate + .as_ref() + .map(CopyEngineGate::enter_peer_graph) + } else { + None + }; + let submitted = match &mut self.inner { + RankExecutorInner::Local(executor) => executor.submit(graph, uploads, grammar), + RankExecutorInner::Parallel(executor) => executor.submit(graph, uploads, grammar), + RankExecutorInner::Threaded(executor) => executor.submit(graph, uploads, grammar), + }?; + if let (Some(fence), Some(guard)) = (submitted, guard) { + self.peer_guards.push_back((fence, guard)); } + Ok(submitted) } pub(crate) fn poll(&mut self) -> Result> { - match self { - Self::Local(executor) => executor.poll(), - Self::Parallel(executor) => executor.poll(), - Self::Threaded(executor) => executor.poll(), + let completion = match &mut self.inner { + RankExecutorInner::Local(executor) => executor.poll(), + RankExecutorInner::Parallel(executor) => executor.poll(), + RankExecutorInner::Threaded(executor) => executor.poll(), + }?; + if let Some(ref frame) = completion { + while self + .peer_guards + .front() + .is_some_and(|(fence, _)| *fence <= frame.fence) + { + self.peer_guards.pop_front(); + } } + Ok(completion) } /// Wait briefly for this rank's running frame; false when the caller should keep polling. pub(crate) fn park(&self) -> bool { - match self { - Self::Local(executor) => executor.park(), - Self::Parallel(executor) => executor.park(), - Self::Threaded(_) => false, + match &self.inner { + RankExecutorInner::Local(executor) => executor.park(), + RankExecutorInner::Parallel(executor) => executor.park(), + RankExecutorInner::Threaded(_) => false, } } pub(crate) fn outstanding(&self) -> usize { - match self { - Self::Local(executor) => executor.outstanding(), - Self::Parallel(executor) => executor.outstanding(), - Self::Threaded(executor) => executor.outstanding(), + match &self.inner { + RankExecutorInner::Local(executor) => executor.outstanding(), + RankExecutorInner::Parallel(executor) => executor.outstanding(), + RankExecutorInner::Threaded(executor) => executor.outstanding(), } } #[cfg(feature = "server")] pub(crate) fn manifest(&self) -> &ExecutionManifest { - match self { - Self::Local(executor) => executor.manifest(), - Self::Parallel(executor) => executor.manifest(), - Self::Threaded(executor) => executor.manifest(), + match &self.inner { + RankExecutorInner::Local(executor) => executor.manifest(), + RankExecutorInner::Parallel(executor) => executor.manifest(), + RankExecutorInner::Threaded(executor) => executor.manifest(), } } #[cfg(feature = "server")] pub(crate) fn can_submit(&self, grammar: bool) -> bool { - match self { - Self::Local(executor) => executor.can_submit(grammar), - Self::Parallel(executor) => executor.can_submit(grammar), - Self::Threaded(executor) => executor.can_submit(grammar), + match &self.inner { + RankExecutorInner::Local(executor) => executor.can_submit(grammar), + RankExecutorInner::Parallel(executor) => executor.can_submit(grammar), + RankExecutorInner::Threaded(executor) => executor.can_submit(grammar), } } #[cfg(feature = "server")] pub(crate) fn next_fence(&self) -> Result { - match self { - Self::Local(executor) => executor.next_fence(), - Self::Parallel(executor) => executor.next_fence(), - Self::Threaded(executor) => executor.next_fence(), + match &self.inner { + RankExecutorInner::Local(executor) => executor.next_fence(), + RankExecutorInner::Parallel(executor) => executor.next_fence(), + RankExecutorInner::Threaded(executor) => executor.next_fence(), } } pub(crate) fn close(&mut self) -> Shutdown { - match self { - Self::Local(executor) => executor.close(), - Self::Parallel(executor) => executor.close(), - Self::Threaded(executor) => executor.close(), - } + let shutdown = match &mut self.inner { + RankExecutorInner::Local(executor) => executor.close(), + RankExecutorInner::Parallel(executor) => executor.close(), + RankExecutorInner::Threaded(executor) => executor.close(), + }; + // Release any uncompleted peer-copy leases after drain (or error teardown) + // so host-store close cannot block waiting on paused offload threads. + self.peer_guards.clear(); + shutdown + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::execution::tests::manifest; + + #[test] + fn merge_peer_copy_graphs_unions_asymmetric_local_ranks() { + let mut root = manifest(); + root.peer_copy_graphs = vec![false, true]; + let mut peer = manifest(); + peer.peer_copy_graphs = vec![true, false, true]; + let peers = RankPeers::Threads(vec![peer]); + + let merged = merge_peer_copy_graphs(&root, Some(&peers)); + assert_eq!(merged, vec![true, true, true]); + assert!(!manifest().has_peer_copies(0)); + assert!(root.has_peer_copies(1)); + assert!(!root.has_peer_copies(99)); } } diff --git a/helios/src/execution/tests.rs b/helios/src/execution/tests.rs index fa0f25b3b..cf9bcb772 100644 --- a/helios/src/execution/tests.rs +++ b/helios/src/execution/tests.rs @@ -203,6 +203,7 @@ pub(super) fn manifest() -> ExecutionManifest { input_frame_bytes: 48, buffers, graphs: vec![graph], + peer_copy_graphs: vec![], } } diff --git a/helios/src/model/contract.rs b/helios/src/model/contract.rs index 24c19155c..2558b41b1 100644 --- a/helios/src/model/contract.rs +++ b/helios/src/model/contract.rs @@ -980,7 +980,7 @@ mod tests { buffers: vec![BufferDescriptor { name: "other".into(), shape: vec![], ..buffer.clone() }, buffer], - graphs: vec![], tuning_graphs: vec![], persistent_workers: vec![], + graphs: vec![], peer_copy_graphs: vec![], tuning_graphs: vec![], persistent_workers: vec![], }; view.validate(&manifest).unwrap(); let mut missing = view.clone(); diff --git a/helios/src/model/testing.rs b/helios/src/model/testing.rs index b82fc3cb7..eb85bf0b0 100644 --- a/helios/src/model/testing.rs +++ b/helios/src/model/testing.rs @@ -393,6 +393,7 @@ pub fn manifest(config: &ModelConfig) -> ExecutionManifest { input_frame_bytes: host, buffers, graphs, + peer_copy_graphs: vec![], cache: None, collectives: None, engram: None, diff --git a/helios/src/offload/copy_gate.rs b/helios/src/offload/copy_gate.rs new file mode 100644 index 000000000..1a929544d --- /dev/null +++ b/helios/src/offload/copy_gate.rs @@ -0,0 +1,263 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +//! Coordinates host prefix-cache Copy Engine transfers against in-graph peer copies. +//! +//! Tensor-parallel graphs that drive peer-to-peer transfers through CUDA Copy Engine +//! nodes (`Node::Copy` targeting `Memory::Peer`, such as `b12x`'s PCIe DMA ring +//! collectives) can deadlock on discrete PCIe GPUs when another stream issues +//! concurrent device-to-host or host-to-device Copy Engine batches on the same +//! devices. This gate lets offload workers issue batches concurrently across ranks +//! while no peer-copy graph is in flight, and pauses new offload batches between +//! `BATCH_BYTES` windows while any peer-copy graph executes. + +use std::sync::{Arc, Condvar, Mutex}; + +#[derive(Default, Debug)] +struct State { + peer_graphs_active: usize, + peer_graphs_waiting: usize, + offload_batches_active: usize, +} + +/// Per-runtime gate serializing offload Copy Engine batches against peer-copy graphs. +/// +/// Offload workers on different ranks may hold [`OffloadBatchGuard`] concurrently. +/// Multiple pipelined peer-copy graphs may hold [`PeerGraphGuard`] concurrently. +/// Peer-copy graphs take priority once waiting so sustained offload traffic cannot +/// starve prefill launch, and every guard releases on drop including panic unwind. +#[derive(Default, Debug)] +pub struct CopyEngineGate { + state: Mutex, + changed: Condvar, +} + +impl CopyEngineGate { + pub fn new() -> Self { + Self::default() + } + + /// Wait for any in-flight offload Copy Engine batches to finish and hold the + /// gate open for a peer-copy graph until the returned guard drops. + pub fn enter_peer_graph(self: &Arc) -> PeerGraphGuard { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + state.peer_graphs_waiting += 1; + while state.offload_batches_active > 0 { + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.peer_graphs_waiting -= 1; + state.peer_graphs_active += 1; + PeerGraphGuard { + gate: Arc::clone(self), + } + } + + /// Wait until no peer-copy graph is waiting or active, then permit one offload + /// Copy Engine batch until the returned guard drops. + pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.peer_graphs_active > 0 || state.peer_graphs_waiting > 0 { + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.offload_batches_active += 1; + OffloadBatchGuard { gate: self } + } +} + +/// Active peer-copy graph lease; dropping resumes paused offload batches once the +/// last active peer-copy graph completes. +#[derive(Debug)] +pub struct PeerGraphGuard { + gate: Arc, +} + +impl Drop for PeerGraphGuard { + fn drop(&mut self) { + let mut state = self.gate.state.lock().unwrap_or_else(|e| e.into_inner()); + state.peer_graphs_active = state.peer_graphs_active.saturating_sub(1); + if state.peer_graphs_active == 0 { + self.gate.changed.notify_all(); + } + } +} + +/// Active offload Copy Engine batch lease; dropping unblocks waiting peer-copy +/// graphs once all active offload batches finish. +#[derive(Debug)] +pub struct OffloadBatchGuard<'a> { + gate: &'a CopyEngineGate, +} + +impl Drop for OffloadBatchGuard<'_> { + fn drop(&mut self) { + let mut state = self.gate.state.lock().unwrap_or_else(|e| e.into_inner()); + state.offload_batches_active = state.offload_batches_active.saturating_sub(1); + if state.offload_batches_active == 0 { + self.gate.changed.notify_all(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Barrier, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + use std::thread; + use std::time::{Duration, Instant}; + + #[test] + fn offload_batches_run_concurrently_across_ranks() { + let gate = Arc::new(CopyEngineGate::new()); + let barrier = Arc::new(Barrier::new(2)); + let workers: Vec<_> = (0..2) + .map(|_| { + let gate = Arc::clone(&gate); + let barrier = Arc::clone(&barrier); + thread::spawn(move || { + let _guard = gate.enter_offload_batch(); + barrier.wait(); + }) + }) + .collect(); + for worker in workers { + worker.join().unwrap(); + } + } + + #[test] + fn peer_graph_waits_for_active_offload_and_blocks_new_batches_until_all_complete() { + let gate = Arc::new(CopyEngineGate::new()); + let offload_started = Arc::new(Barrier::new(2)); + let release_offload = Arc::new(Barrier::new(2)); + let peer_entered = Arc::new(AtomicBool::new(false)); + let second_offload_entered = Arc::new(AtomicBool::new(false)); + + // 1. Start an offload batch and hold it active. + let g1 = Arc::clone(&gate); + let started = Arc::clone(&offload_started); + let release = Arc::clone(&release_offload); + let first_offload = thread::spawn(move || { + let _guard = g1.enter_offload_batch(); + started.wait(); + release.wait(); + }); + offload_started.wait(); + + // 2. Request a peer-copy graph: it must block while first_offload is active. + let g2 = Arc::clone(&gate); + let entered = Arc::clone(&peer_entered); + let peer_ready = Arc::new(Barrier::new(2)); + let peer_release = Arc::new(Barrier::new(2)); + let pr = Arc::clone(&peer_ready); + let pl = Arc::clone(&peer_release); + let peer_thread = thread::spawn(move || { + let _guard1 = g2.enter_peer_graph(); + // Pipelined second peer-copy graph must enter immediately without blocking. + let _guard2 = g2.enter_peer_graph(); + entered.store(true, Ordering::Release); + pr.wait(); + drop(_guard1); + // Still holding _guard2: new offload batches must stay blocked. + thread::sleep(Duration::from_millis(20)); + pl.wait(); + drop(_guard2); + }); + + thread::sleep(Duration::from_millis(15)); + assert!( + !peer_entered.load(Ordering::Acquire), + "peer-copy graph entered while offload batch was active" + ); + + // 3. Release first offload -> peer-copy graph enters. + release_offload.wait(); + first_offload.join().unwrap(); + peer_ready.wait(); + assert!(peer_entered.load(Ordering::Acquire)); + + // 4. Start a second offload batch while _guard2 is still active -> must block. + let g3 = Arc::clone(&gate); + let second_entered = Arc::clone(&second_offload_entered); + let second_offload = thread::spawn(move || { + let _guard = g3.enter_offload_batch(); + second_entered.store(true, Ordering::Release); + }); + + thread::sleep(Duration::from_millis(15)); + assert!( + !second_offload_entered.load(Ordering::Acquire), + "offload batch entered while pipelined peer-copy graph was still active" + ); + + // 5. Release _guard2 -> second offload completes. + peer_release.wait(); + peer_thread.join().unwrap(); + second_offload.join().unwrap(); + assert!(second_offload_entered.load(Ordering::Acquire)); + } + + #[test] + fn peer_graph_takes_priority_over_continuous_offload_stream() { + let gate = Arc::new(CopyEngineGate::new()); + let stop = Arc::new(AtomicBool::new(false)); + let completed = Arc::new(AtomicUsize::new(0)); + let workers: Vec<_> = (0..2) + .map(|_| { + let gate = Arc::clone(&gate); + let stop = Arc::clone(&stop); + let completed = Arc::clone(&completed); + thread::spawn(move || { + while !stop.load(Ordering::Acquire) { + let _guard = gate.enter_offload_batch(); + completed.fetch_add(1, Ordering::Relaxed); + thread::sleep(Duration::from_millis(1)); + } + }) + }) + .collect(); + + while completed.load(Ordering::Relaxed) < 4 { + thread::yield_now(); + } + let started = Instant::now(); + let guard = gate.enter_peer_graph(); + assert!( + started.elapsed() < Duration::from_secs(1), + "peer-copy graph was starved by continuous offload batches" + ); + drop(guard); + stop.store(true, Ordering::Release); + for worker in workers { + worker.join().unwrap(); + } + } + + #[test] + fn panic_unwind_releases_guards_without_stranding_waiters() { + let gate = Arc::new(CopyEngineGate::new()); + let g = Arc::clone(&gate); + let _ = thread::spawn(move || { + let _guard = g.enter_peer_graph(); + panic!("simulated panic holding peer graph guard"); + }) + .join(); + // Subsequent offload batch must acquire immediately. + let _offload = gate.enter_offload_batch(); + drop(_offload); + + let g = Arc::clone(&gate); + let _ = thread::spawn(move || { + let _guard = g.enter_offload_batch(); + panic!("simulated panic holding offload batch guard"); + }) + .join(); + // Subsequent peer-copy graph must acquire immediately. + let _peer = gate.enter_peer_graph(); + } +} diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 6ff75244c..371facdad 100644 --- a/helios/src/offload/mod.rs +++ b/helios/src/offload/mod.rs @@ -16,12 +16,15 @@ //! #[cfg(all(test, feature = "runtime-core"))] mod gpu_tests; +pub mod copy_gate; #[cfg(feature = "runtime-core")] pub(crate) mod pool; mod registrar; pub mod shard; pub mod transfer; +pub use copy_gate::{CopyEngineGate, OffloadBatchGuard, PeerGraphGuard}; + pub use flare_selene::pool::{PoolOptions, parse_pool_address}; use flare_selene::{CacheGeometry, HostStore}; @@ -36,14 +39,24 @@ pub use flare_selene::offload::{ pub struct Binding { inner: flare_selene::offload::Binding, gpu_cubins: Vec>>, + copy_gate: std::sync::Arc, } impl Binding { pub(crate) fn new( inner: flare_selene::offload::Binding, gpu_cubins: Vec>>, + copy_gate: std::sync::Arc, ) -> Self { - Self { inner, gpu_cubins } + Self { + inner, + gpu_cubins, + copy_gate, + } + } + + pub(crate) fn copy_gate(&self) -> std::sync::Arc { + std::sync::Arc::clone(&self.copy_gate) } pub fn inputs(&self) -> Option { @@ -101,10 +114,18 @@ pub fn prepare_with_inputs_budget( pub fn open( prepared: Prepared, gpu_cubins: Vec>>, +) -> Result> { + open_with_gate(prepared, gpu_cubins, None) +} + +pub fn open_with_gate( + prepared: Prepared, + gpu_cubins: Vec>>, + copy_gate: Option>, ) -> Result> { Ok(flare_selene::offload::open( prepared, - &transfer::Copiers::new(gpu_cubins), + &transfer::Copiers::with_gate(gpu_cubins, copy_gate), )?) } diff --git a/helios/src/offload/transfer.rs b/helios/src/offload/transfer.rs index 8c0d54409..2efe566f6 100644 --- a/helios/src/offload/transfer.rs +++ b/helios/src/offload/transfer.rs @@ -290,6 +290,7 @@ struct RankWorker { /// Resolves slab identities to GPU addresses; without it host addresses are /// already GPU-addressable, as for memory registered with identical addresses. part: Option, + copy_gate: Option>, stream: Stream, event: Event, descriptors: Vec, @@ -301,6 +302,7 @@ struct RankWorker { impl RankWorker { /// Bind the rank's context to the calling thread and size the descriptor /// arrays for one window and one batch. + #[allow(clippy::too_many_arguments)] fn open( rank: usize, context: usize, @@ -310,6 +312,7 @@ impl RankWorker { decode: Option, gpu_cubin: Option>>, shared_gpu: Option, + copy_gate: Option>, ) -> Result { let stream = Stream::open_lowest_priority(context, device)?; let event = stream.blocking_event()?; @@ -341,6 +344,7 @@ impl RankWorker { geometry, layout, part: None, + copy_gate, stream, event, descriptors: Vec::with_capacity(window), @@ -363,6 +367,7 @@ impl RankWorker { &self.layout, &self.stream, &self.event, + self.copy_gate.as_deref(), job, window, ); @@ -390,17 +395,43 @@ impl RankWorker { self.sizes.push(descriptor.bytes); bytes += descriptor.bytes as u64; } - // SAFETY: Device ranges lie inside the rank's cache allocations by - // the id checks in `expand`, and the submitting store keeps every - // slab mapped, registered, and unchanged until this job's reply. - unsafe { - self.stream - .copy_batch(&self.destinations, &self.sources, &self.sizes)?; + if let Some(gate) = self.copy_gate.as_deref() { + struct DrainOnDrop<'a>(&'a Stream, &'a Event); + impl Drop for DrainOnDrop<'_> { + fn drop(&mut self) { + if self.0.record(self.1).is_err() || self.1.synchronize().is_err() { + let _ = self.0.synchronize(); + } + } + } + let _ce = gate.enter_offload_batch(); + // Declared after `_ce` so any error drains the stream before releasing the gate. + let drain = DrainOnDrop(&self.stream, &self.event); + // SAFETY: Device ranges lie inside the rank's cache allocations by + // the id checks in `expand`, and the submitting store keeps every + // slab mapped, registered, and unchanged until this job's reply. + unsafe { + self.stream + .copy_batch(&self.destinations, &self.sources, &self.sizes)?; + } + self.stream.record(&self.event)?; + self.event.synchronize()?; + std::mem::forget(drain); + } else { + // SAFETY: Device ranges lie inside the rank's cache allocations by + // the id checks in `expand`, and the submitting store keeps every + // slab mapped, registered, and unchanged until this job's reply. + unsafe { + self.stream + .copy_batch(&self.destinations, &self.sources, &self.sizes)?; + } } start = end; } - self.stream.record(&self.event)?; - self.event.synchronize()?; + if self.copy_gate.is_none() { + self.stream.record(&self.event)?; + self.event.synchronize()?; + } Ok(bytes) } @@ -446,6 +477,7 @@ impl Transfers { parts: Vec>, gpu_cubins: &[std::sync::Arc>], shared_gpu: Option, + copy_gate: Option>, ) -> Result { if contexts.is_empty() || contexts.len() != geometry.len() { return Err(invalid(format!( @@ -505,6 +537,7 @@ impl Transfers { .or_else(|| gpu_cubins.first()) .cloned(); let shared_gpu = shared_gpu.clone(); + let copy_gate = copy_gate.clone(); let replies = reply_sender.clone(); let thread = std::thread::Builder::new() .name(format!("flare-offload-{rank}")) @@ -518,6 +551,7 @@ impl Transfers { decode, gpu_cubin, shared_gpu, + copy_gate, ) { Ok(mut worker) => { worker.part = part; @@ -2036,13 +2070,22 @@ mod tests { pub(crate) struct Copiers { gpu_cubins: Vec>>, shared_gpu: codec::SharedGpuCodecs, + copy_gate: Option>, } impl Copiers { pub(crate) fn new(gpu_cubins: Vec>>) -> Self { + Self::with_gate(gpu_cubins, None) + } + + pub(crate) fn with_gate( + gpu_cubins: Vec>>, + copy_gate: Option>, + ) -> Self { Self { gpu_cubins, shared_gpu: Default::default(), + copy_gate, } } @@ -2064,6 +2107,7 @@ impl Copiers { parts, &self.gpu_cubins, Some(self.shared_gpu.clone()), + self.copy_gate.clone(), ) } } diff --git a/helios/src/offload/transfer/codec.rs b/helios/src/offload/transfer/codec.rs index 927cb941d..5e57eaacd 100644 --- a/helios/src/offload/transfer/codec.rs +++ b/helios/src/offload/transfer/codec.rs @@ -149,6 +149,7 @@ impl RankCodec { }) } + #[allow(clippy::too_many_arguments)] pub(super) fn run( &mut self, rank: usize, @@ -156,17 +157,34 @@ impl RankCodec { layout: &RankLayout, stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, job: &Job, window: &Window, ) -> Result { let mut stats = DecodeStats::default(); let result = match job.direction { - Direction::In => { - self.restore_window(rank, geometry, layout, stream, event, job, window, &mut stats) - } - Direction::Out => { - self.capture_window(rank, geometry, layout, stream, event, job, window, &mut stats) - } + Direction::In => self.restore_window( + rank, + geometry, + layout, + stream, + event, + copy_gate, + job, + window, + &mut stats, + ), + Direction::Out => self.capture_window( + rank, + geometry, + layout, + stream, + event, + copy_gate, + job, + window, + &mut stats, + ), }; { let mut totals = self.counters.lock().unwrap(); @@ -206,6 +224,7 @@ impl RankCodec { layout: &RankLayout, stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, job: &Job, window: &Window, stats: &mut DecodeStats, @@ -268,6 +287,7 @@ impl RankCodec { .collect(); let stored_len = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let res = guard.encode_pages_batches_with( page_plan, &batch_refs, @@ -295,6 +315,7 @@ impl RankCodec { let start = Instant::now(); let stored_len = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let res = guard.encode_from_device_with( page_plan, base_unit, @@ -328,6 +349,7 @@ impl RankCodec { let start = Instant::now(); let stored_len = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let res = guard.encode_from_device_with( &self.cpu.gpu_row, base_unit, @@ -370,6 +392,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::Out, &batch_spans, self.cpu.staging_alias, @@ -440,6 +463,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::Out, &[(0, spans)], self.cpu.staging_alias, @@ -509,6 +533,7 @@ impl RankCodec { batch_spans: &[(usize, Vec)], stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, stats: &mut DecodeStats, ) -> Result<()> { let pool = cpu_pool()?; @@ -542,6 +567,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::In, batch_spans, self.cpu.staging_alias, @@ -556,6 +582,7 @@ impl RankCodec { layout: &RankLayout, stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, job: &Job, window: &Window, stats: &mut DecodeStats, @@ -597,7 +624,7 @@ impl RankCodec { items.push((u, route, chunks)); batch_spans.push((slot_idx * page_bytes, spans)); } - self.decode_pages_cpu_batch(&items, &batch_spans, stream, event, stats)?; + self.decode_pages_cpu_batch(&items, &batch_spans, stream, event, copy_gate, stats)?; transferred += (chunk.len() * page_bytes) as u64; remaining_pages_offset += chunk.len(); } @@ -637,6 +664,8 @@ impl RankCodec { let start = Instant::now(); let gpu_ran = { if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { + let _ce = + copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let packets: Vec<(&[&[u8]], u32, u32)> = run_chunks .iter() .zip(&run_units) @@ -680,6 +709,7 @@ impl RankCodec { &batch_spans, stream, event, + copy_gate, stats, )?; off += take; @@ -719,6 +749,7 @@ impl RankCodec { let start = Instant::now(); let gpu_ran = { if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { + let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); let res = guard.decode_to_device( plan, &chunks, @@ -757,6 +788,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::In, &[(0, spans)], self.cpu.staging_alias, @@ -926,6 +958,7 @@ fn zero_span_gaps(buf: &mut [u8], spans: &[DeviceSpan]) { fn copy_spans_batch( stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, direction: Direction, batch: &[(usize, Vec)], host: u64, @@ -936,16 +969,28 @@ fn copy_spans_batch( let _ = self.0.synchronize(); } } - let fence = Fence(stream); let mut dsts = Vec::new(); let mut srcs = Vec::new(); let mut lens = Vec::new(); let mut queued = 0usize; let flush = |dsts: &mut Vec, srcs: &mut Vec, lens: &mut Vec, queued: &mut usize| -> Result<()> { if !lens.is_empty() { - // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. - unsafe { - stream.copy_batch(dsts, srcs, lens)?; + if let Some(gate) = copy_gate { + let _ce = gate.enter_offload_batch(); + // Declared after `_ce` so any error drains the stream before releasing the gate. + let fence = Fence(stream); + // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. + unsafe { + stream.copy_batch(dsts, srcs, lens)?; + } + stream.record(event)?; + event.synchronize()?; + std::mem::forget(fence); + } else { + // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. + unsafe { + stream.copy_batch(dsts, srcs, lens)?; + } } dsts.clear(); srcs.clear(); @@ -954,6 +999,7 @@ fn copy_spans_batch( } Ok(()) }; + let fence = copy_gate.is_none().then_some(Fence(stream)); for (slot_start, spans) in batch { let base = host + *slot_start as u64; for p in spans { @@ -976,8 +1022,10 @@ fn copy_spans_batch( } } flush(&mut dsts, &mut srcs, &mut lens, &mut queued)?; - stream.record(event)?; - event.synchronize()?; + if copy_gate.is_none() { + stream.record(event)?; + event.synchronize()?; + } std::mem::forget(fence); Ok(()) } diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 1f2f01cf3..e219d4023 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -116,6 +116,7 @@ pub struct NativeResources { templates: Vec, executables: Vec, names: Vec, + peer_copy_graphs: Vec, reservations: Vec<(u64, usize)>, execution: Option, // An integrated GPU (GB10) registers host memory without pinning it. @@ -413,6 +414,7 @@ impl NativeResources { templates: vec![], executables: vec![], names: vec![], + peer_copy_graphs: vec![], reservations: vec![], execution: core.execution.clone(), integrated: integrated != 0, @@ -914,6 +916,7 @@ impl NativeResources { driver.check("cuGraphCreate", (driver.graph_create)(&mut handle, 0))?; self.templates.push(handle); let mut nodes = Vec::with_capacity(graph.node_count); + let mut has_peer_copies = false; let mut records = files.records(core, &graph.resource)?; for _ in 0..graph.node_count { let node = protobuf::node(records.read()?)?; @@ -1143,6 +1146,14 @@ impl NativeResources { destination, nbytes, } => { + let is_peer = |reference: &Reference| { + self.allocations + .get(&reference.allocation) + .is_some_and(|storage| matches!(storage.memory, Memory::Peer)) + }; + if is_peer(source) || is_peer(destination) { + has_peer_copies = true; + } let endpoint = |reference| CopyEndpoint { memory_type: 2, device: self.address(reference), @@ -1224,6 +1235,7 @@ impl NativeResources { )?; self.executables.push(executable); self.names.push(graph.name.clone()); + self.peer_copy_graphs.push(has_peer_copies); driver.check( "cuGraphUpload", (driver.graph_upload)(executable, upload_stream), diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index b9561b074..fd0badf00 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -24,6 +24,7 @@ pub struct NativeModel { pub(super) server_config: serde_json::Value, engram: Vec<(std::sync::Arc, usize)>, pub(super) offload: flare_selene::offload::Startup, + copy_gate: std::sync::Arc, gpu_codec_cubins: Vec>>, cluster: Option, roce: Vec>, @@ -658,6 +659,7 @@ impl NativeModel { server_config, engram: Vec::new(), offload: Default::default(), + copy_gate: std::sync::Arc::new(crate::offload::CopyEngineGate::new()), gpu_codec_cubins, cluster, roce, @@ -981,7 +983,10 @@ impl NativeModel { } fn attach_offload(&mut self, prepared: crate::offload::Preparation) -> Result { - let copiers = crate::offload::transfer::Copiers::new(self.gpu_codec_cubins.clone()); + let copiers = crate::offload::transfer::Copiers::with_gate( + self.gpu_codec_cubins.clone(), + Some(std::sync::Arc::clone(&self.copy_gate)), + ); Ok(self.offload.attach(prepared, &copiers)?) } @@ -1024,10 +1029,13 @@ impl NativeModel { .enumerate() .map(|(index, rank)| { let mut manifest = rank.execution_manifest()?; - manifest.offload = self - .offload - .binding(index) - .map(|b| crate::offload::Binding::new(b, self.gpu_codec_cubins.clone())); + manifest.offload = self.offload.binding(index).map(|b| { + crate::offload::Binding::new( + b, + self.gpu_codec_cubins.clone(), + std::sync::Arc::clone(&self.copy_gate), + ) + }); if let Some((shared, delivery_rank)) = self.engram.get(index) { let events = shared .index @@ -1294,6 +1302,7 @@ mod tests { server_config: serde_json::Value::Null, engram: Vec::new(), offload: Default::default(), + copy_gate: std::sync::Arc::new(crate::offload::CopyEngineGate::new()), cluster: None, roce: Vec::new(), gpu_codec_cubins: Vec::new(), diff --git a/helios/src/runtime_core/serving.rs b/helios/src/runtime_core/serving.rs index cd87cacc7..4f44d6da3 100644 --- a/helios/src/runtime_core/serving.rs +++ b/helios/src/runtime_core/serving.rs @@ -46,6 +46,7 @@ impl NativeResources { }) }) .collect::>>()?; + let mut peer_copy_graphs = Vec::with_capacity(execution.graphs.len()); let graphs = execution .graphs .iter() @@ -55,6 +56,7 @@ impl NativeResources { .iter() .position(|name| *name == g.name) .ok_or_else(|| invalid("execution references an unknown graph"))?; + peer_copy_graphs.push(self.peer_copy_graphs.get(index).copied().unwrap_or(false)); Ok(GraphDescriptor { tuned_bindings: g.tuned_bindings.iter().map(|binding| TunedBinding { buffer: binding.buffer.clone(), tuning_graph: binding.tuning_graph.clone(), @@ -197,6 +199,7 @@ impl NativeResources { input_frame_bytes: size(execution.input_frame_bytes)?, buffers, graphs, + peer_copy_graphs, }; manifest.validate()?; Ok(manifest) diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 6d30bc92a..6fba26864 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -715,15 +715,20 @@ impl ModelRuntime { .manifest() .offload .as_ref() - .and_then(|binding| binding.take()) - .map(|(prepared, gpu_cubins)| { + .and_then(|binding| { + let copy_gate = binding.copy_gate(); + binding + .take() + .map(|(prepared, gpu_cubins)| (prepared, gpu_cubins, copy_gate)) + }) + .map(|(prepared, gpu_cubins, copy_gate)| { if let Some(rank) = prepared.geometry.first() { worker_metrics.codec_placement(rank.placement); } if let Some(warning) = prepared.intake_warning() { if log_to_stderr { eprintln!("warning: {warning}"); } } - crate::offload::open(prepared, gpu_cubins) + crate::offload::open_with_gate(prepared, gpu_cubins, Some(copy_gate)) }) .transpose() { From 76e18130483a209955f6f09d3dd4b60bf526e131 Mon Sep 17 00:00:00 2001 From: yatesdr <6937857+yatesdr@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:54:59 -0500 Subject: [PATCH 2/2] helios: bound CopyEngineGate fairness, scope gating to peer-copy models, and preserve metrics Address starvation, non-peer-copy overhead, timeout, metrics, multi-host coverage, and cleanup gaps in `CopyEngineGate`: - Add bounded fairness to `CopyEngineGate` (`MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING = 4`): when offload batches are waiting under sustained 2-frame pipelined peer-copy decode, `PeerGraphLeases::should_drain_for_offload()` signals `RankExecutor::can_submit()` to pause pipelining for one frame so active peer-copy leases drain to zero, then grants one concurrent wave to all waiting offload ranks before resuming peer-copy graphs. Only arm an offload wave when `peer_graphs_active == 0` so a single-threaded pipelined worker cannot self-deadlock. - Scope `CopyEngineGate` creation in `NativeModel` to models where at least one rank reconstructed a graph with `Node::Copy` referencing `Memory::Peer` (`NativeResources::has_any_peer_copy_graphs()`). Single-GPU and non-peer-copy TP models receive `copy_gate = None` and stay on the ungated single-sync-per-window offload fast path. - Bound `CopyEngineGate::enter_peer_graph` with `PEER_GRAPH_GATE_TIMEOUT` (120 s, aligned with `ThreadedExecutor::TIMEOUT`), returning `ExecutionError::Drain` instead of parking the model worker thread indefinitely if an offload Copy Engine batch fails to drain, and update the invariants in `docs/prefix-cache-offload.md` and `helios/src/offload/transfer.rs`. - Exclude gate-wait pauses from throughput metrics: start the transform timer after acquiring the gate in all five GPU-codec call sites in `codec.rs`, accumulate per-rank `gate_wait` and subtract `max_gate_wait` from `Reply.elapsed` in `Transfers::absorb`, and record `prefill_started` in `Worker::submit` after `executor.submit()` succeeds. - Share `PeerGraphLeases` between `RankExecutor` and multi-host `serve_rank` (`execution/parallel.rs`), and wire `owner.copy_gate()` through `offload::shard::join_peer_with_gate` (`flare-cli/src/cluster.rs`). - Deduplicate gated/ungated `stream.copy_batch` and stream-drain helpers into `transfer::copy_batch_gated` and `transfer::drain_stream`; remove dead `ExecutionManifest::has_peer_copies` and unused `OffloadBatchGuard` re-export; move pure delegation matches onto `RankExecutorInner`; validate `peer_copy_graphs.len() == graphs.len()` (when non-empty) in `ExecutionManifest::validate()`; and add unit and gated CUDA transfer tests. Validation: - `RUSTFLAGS="-D warnings" cargo check --locked --all-targets` passed with 0 warnings on `helios --features runtime-core,server`, `heliopause --lib`, `flare`, and `flare-cli`. - `cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server`: 1,740/1,740 lib tests passed (1,739 with `io_uring` + 1 non-root chmod test) and all integration tests passed (excluding the 9 HF-template fixture tests requiring `FLARE_TEST_TEMPLATE_DIR`). - `cargo test --locked --release --manifest-path flare/Cargo.toml`: 245/245 passed. - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml`: all 201 unit tests (across root and non-root permission contexts) and all 4 integration test suites passed. Limitations: - New gated CUDA transfer tests (`split_pools_cost_each_device_its_part_and_round_trip_units` and `gated_cpu_and_gpu_codec_capture_and_restore_defer_while_peer_graph_holds_gate`) and an A/B peer-copy offload latency comparison have not yet been executed on this commit because the SM120 host GPUs are currently occupied by another job; the earlier SM120 CUDA `offload::` tests and live `Qwen3.8-Flash-Next` TP2 / `GLM-5.3-Flash` TP2 runs passed on `1870a27`. Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b --- docs/prefix-cache-offload.md | 24 +- flare-cli/src/cluster.rs | 3 +- helios/src/execution/manifest.rs | 11 +- helios/src/execution/parallel.rs | 13 +- helios/src/execution/ranks.rs | 181 ++++---- helios/src/offload/copy_gate.rs | 392 ++++++++++++++++-- helios/src/offload/mod.rs | 10 +- helios/src/offload/shard.rs | 13 +- helios/src/offload/transfer.rs | 178 ++++++-- helios/src/offload/transfer/codec.rs | 169 ++++---- .../src/offload/transfer/lifecycle_tests.rs | 2 + helios/src/runtime_core/mod.rs | 4 + helios/src/runtime_core/model.rs | 19 +- helios/src/server/runtime.rs | 44 +- 14 files changed, 787 insertions(+), 276 deletions(-) diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index f4294f83a..5561d49d3 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -130,7 +130,10 @@ retains source windows through the last rank's copy fence. as a checkpoint are never offloaded. - Every model contract is covered through the core's runtime-sized allocation groups. The offload path contains no model-specific code. -- Offload work never blocks the model worker thread or the model stream. +- Offload work never blocks the model stream, and never blocks the model worker + thread except for the bounded Copy Engine drain before launching a graph that + contains in-graph peer-to-peer Copy Engine nodes (`Node::Copy` with a + `Memory::Peer` endpoint). Single-GPU and non-peer-copy models stay ungated. Section 2.10 states the isolation mechanisms and section 4 the measurements that gate derived defaults. @@ -911,8 +914,15 @@ Offload limits interference through bounded work and explicit ownership: offload streams are created at the least stream priority. Every other Helios stream uses the default priority, which CUDA defines as the least priority as well, so stream priority does not separate offload work from model work. - Creating the model and copy streams at a greater priority requires the - section 4 measurements to show a benefit. Measure delays to + When a loaded model contains CUDA graphs with in-graph peer-to-peer Copy Engine + nodes (`Node::Copy` referencing `Memory::Peer`), Helios coordinates offload + batches against those graphs through a per-model `CopyEngineGate`: new offload + batches pause between 16 MiB windows while a peer-copy graph executes, waiting + peer-copy graphs bound their drain wait at 120 seconds, and continuous pipelined + peer-copy execution yields bounded fairness turns to waiting offload workers. + Models without peer-copy graphs omit the gate and keep one synchronization per + transfer window. Creating the model and copy streams at a greater priority + requires the section 4 measurements to show a benefit. Measure delays to input uploads, completion downloads, and Engram row copies on shared copy engines through per-token latency. Batch size and stream priority alone do not bound those delays. @@ -1012,9 +1022,11 @@ Offload limits interference through bounded work and explicit ownership: - In the composite, memory contents are a subset of disk contents, counting writes in flight, and memory evicts only durable records. - Slab allocation never blocks; an unsatisfiable request fails its job. -- The model worker thread never waits for offload work, and the model stream - never waits on an offload stream. A peer connection that stops accepting - frames fails the job; it never delays the worker. +- The model stream never waits on an offload stream, and the model worker + thread waits on offload only for a bounded in-flight 16 MiB batch drain + before launching a graph that contains in-graph peer-to-peer Copy Engine + nodes. A peer connection that stops accepting frames fails the job; it never + delays the worker. - A transfer whose completion can no longer be reported stops the store and the worker, so its ids and pins are neither reused nor released. - Offload copies are bounded per issue, and offload threads run below the diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 083244444..5c5433743 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -251,9 +251,10 @@ pub fn peer( rendezvous::report_connected(&mut stream)?; phase.finish(connected(&transport)); let phase = progress.phase("Join host prefix stores", None); - let records = flare_helios::offload::shard::join_peer( + let records = flare_helios::offload::shard::join_peer_with_gate( owner.offload(), owner.gpu_codec_cubins().to_vec(), + owner.copy_gate(), &mut stream, cluster.rank, cluster.world, diff --git a/helios/src/execution/manifest.rs b/helios/src/execution/manifest.rs index cacff7f08..67d7b1e72 100644 --- a/helios/src/execution/manifest.rs +++ b/helios/src/execution/manifest.rs @@ -443,11 +443,6 @@ pub struct ExecutionManifest { } impl ExecutionManifest { - /// Whether graph `index` executes in-graph peer-to-peer Copy Engine nodes. - pub fn has_peer_copies(&self, index: usize) -> bool { - self.peer_copy_graphs.get(index).copied().unwrap_or(false) - } - fn validate_persistent_workers(&self) -> Result<()> { if self.persistent_workers.len() > 1 { return Err(Error::execution( @@ -840,6 +835,12 @@ impl ExecutionManifest { } } self.validate_tuning()?; + if !self.peer_copy_graphs.is_empty() && self.peer_copy_graphs.len() != self.graphs.len() { + return Err(Error::execution( + ExecutionError::Manifest, + "peer_copy_graphs length must match graphs when populated", + )); + } let mut names = HashSet::new(); let mut host_spans = HashMap::<&str, (usize, usize)>::new(); for graph in &self.graphs { diff --git a/helios/src/execution/parallel.rs b/helios/src/execution/parallel.rs index 807df36c2..dc9f24b6d 100644 --- a/helios/src/execution/parallel.rs +++ b/helios/src/execution/parallel.rs @@ -560,6 +560,10 @@ pub unsafe fn serve_rank( if let Err(error) = manifest.validate().and_then(|_| wire::validate_completion_packet(&manifest)) { return Shutdown { drained: true, error: Some(error) }; } + let mut leases = crate::offload::PeerGraphLeases::new( + manifest.offload.as_ref().and_then(|b| b.copy_gate()), + manifest.peer_copy_graphs.clone(), + ); let mut executor = match unsafe { GraphExecutor::new_unstarted(manifest) } { Ok(executor) => executor, Err(error) => { @@ -645,15 +649,18 @@ pub unsafe fn serve_rank( let uploads: Vec<_> = owned.iter().map(|upload| Upload { buffer: &upload.buffer, offset: upload.offset, bytes: &upload.bytes, }).collect(); + let guard = leases.enter(graph)?; if executor.submit(graph, &uploads, grammar)? != Some(fence) { return Err(invalid("rank lost its prepared submission")); } + leases.track(Some(fence), guard); started.push_back(Instant::now()); } _ => return Err(invalid("unexpected rank command")), } } if let Some(completed) = executor.poll()? { + leases.release_through(completed.fence); started.pop_front(); channel.send(COMPLETE, &completion(&completed))?; } @@ -678,8 +685,10 @@ pub unsafe fn serve_rank( } result })(); - match result { + let shutdown = match result { Ok(()) => executor.close(), Err(error) => executor.abandon(error), - } + }; + leases.clear(); + shutdown } diff --git a/helios/src/execution/ranks.rs b/helios/src/execution/ranks.rs index 5624a65f7..766ce261d 100644 --- a/helios/src/execution/ranks.rs +++ b/helios/src/execution/ranks.rs @@ -6,17 +6,10 @@ //! Direct scheduler execution on one CUDA rank or a coordinated rank group. -use std::collections::VecDeque; -use std::sync::Arc; - use super::{ ExecutionManifest, FrameCompletion, GraphExecutor, RankStream, TensorParallelExecutor, Upload, }; -use crate::{ - Result, Shutdown, - cache::Fence, - offload::{CopyEngineGate, PeerGraphGuard}, -}; +use crate::{Result, Shutdown, cache::Fence, offload::PeerGraphLeases}; pub enum RankPeers { Processes(Vec), @@ -29,11 +22,83 @@ enum RankExecutorInner { Parallel(Box), } +impl RankExecutorInner { + fn submit( + &mut self, + graph: usize, + uploads: &[Upload<'_>], + grammar: bool, + ) -> Result> { + match self { + Self::Local(executor) => executor.submit(graph, uploads, grammar), + Self::Parallel(executor) => executor.submit(graph, uploads, grammar), + Self::Threaded(executor) => executor.submit(graph, uploads, grammar), + } + } + + fn poll(&mut self) -> Result> { + match self { + Self::Local(executor) => executor.poll(), + Self::Parallel(executor) => executor.poll(), + Self::Threaded(executor) => executor.poll(), + } + } + + fn park(&self) -> bool { + match self { + Self::Local(executor) => executor.park(), + Self::Parallel(executor) => executor.park(), + Self::Threaded(_) => false, + } + } + + fn outstanding(&self) -> usize { + match self { + Self::Local(executor) => executor.outstanding(), + Self::Parallel(executor) => executor.outstanding(), + Self::Threaded(executor) => executor.outstanding(), + } + } + + #[cfg(feature = "server")] + fn manifest(&self) -> &ExecutionManifest { + match self { + Self::Local(executor) => executor.manifest(), + Self::Parallel(executor) => executor.manifest(), + Self::Threaded(executor) => executor.manifest(), + } + } + + #[cfg(feature = "server")] + fn can_submit(&self, grammar: bool) -> bool { + match self { + Self::Local(executor) => executor.can_submit(grammar), + Self::Parallel(executor) => executor.can_submit(grammar), + Self::Threaded(executor) => executor.can_submit(grammar), + } + } + + #[cfg(feature = "server")] + fn next_fence(&self) -> Result { + match self { + Self::Local(executor) => executor.next_fence(), + Self::Parallel(executor) => executor.next_fence(), + Self::Threaded(executor) => executor.next_fence(), + } + } + + fn close(&mut self) -> Shutdown { + match self { + Self::Local(executor) => executor.close(), + Self::Parallel(executor) => executor.close(), + Self::Threaded(executor) => executor.close(), + } + } +} + pub(crate) struct RankExecutor { inner: RankExecutorInner, - copy_gate: Option>, - peer_copy_graphs: Vec, - peer_guards: VecDeque<(Fence, PeerGraphGuard)>, + leases: PeerGraphLeases, } fn merge_peer_copy_graphs(manifest: &ExecutionManifest, peers: Option<&RankPeers>) -> Vec { @@ -59,7 +124,7 @@ impl RankExecutor { manifest: ExecutionManifest, peers: Option, ) -> Result { - let copy_gate = manifest.offload.as_ref().map(|b| b.copy_gate()); + let copy_gate = manifest.offload.as_ref().and_then(|b| b.copy_gate()); let peer_copy_graphs = merge_peer_copy_graphs(&manifest, peers.as_ref()); let inner = match peers { Some(RankPeers::Threads(ranks)) => { @@ -75,9 +140,7 @@ impl RankExecutor { }; Ok(Self { inner, - copy_gate, - peer_copy_graphs, - peer_guards: VecDeque::new(), + leases: PeerGraphLeases::new(copy_gate, peer_copy_graphs), }) } @@ -87,95 +150,47 @@ impl RankExecutor { uploads: &[Upload<'_>], grammar: bool, ) -> Result> { - let guard = if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) { - self.copy_gate - .as_ref() - .map(CopyEngineGate::enter_peer_graph) - } else { - None - }; - let submitted = match &mut self.inner { - RankExecutorInner::Local(executor) => executor.submit(graph, uploads, grammar), - RankExecutorInner::Parallel(executor) => executor.submit(graph, uploads, grammar), - RankExecutorInner::Threaded(executor) => executor.submit(graph, uploads, grammar), - }?; - if let (Some(fence), Some(guard)) = (submitted, guard) { - self.peer_guards.push_back((fence, guard)); - } + let guard = self.leases.enter(graph)?; + let submitted = self.inner.submit(graph, uploads, grammar)?; + self.leases.track(submitted, guard); Ok(submitted) } pub(crate) fn poll(&mut self) -> Result> { - let completion = match &mut self.inner { - RankExecutorInner::Local(executor) => executor.poll(), - RankExecutorInner::Parallel(executor) => executor.poll(), - RankExecutorInner::Threaded(executor) => executor.poll(), - }?; + let completion = self.inner.poll()?; if let Some(ref frame) = completion { - while self - .peer_guards - .front() - .is_some_and(|(fence, _)| *fence <= frame.fence) - { - self.peer_guards.pop_front(); - } + self.leases.release_through(frame.fence); } Ok(completion) } /// Wait briefly for this rank's running frame; false when the caller should keep polling. pub(crate) fn park(&self) -> bool { - match &self.inner { - RankExecutorInner::Local(executor) => executor.park(), - RankExecutorInner::Parallel(executor) => executor.park(), - RankExecutorInner::Threaded(_) => false, - } + self.inner.park() } pub(crate) fn outstanding(&self) -> usize { - match &self.inner { - RankExecutorInner::Local(executor) => executor.outstanding(), - RankExecutorInner::Parallel(executor) => executor.outstanding(), - RankExecutorInner::Threaded(executor) => executor.outstanding(), - } + self.inner.outstanding() } #[cfg(feature = "server")] pub(crate) fn manifest(&self) -> &ExecutionManifest { - match &self.inner { - RankExecutorInner::Local(executor) => executor.manifest(), - RankExecutorInner::Parallel(executor) => executor.manifest(), - RankExecutorInner::Threaded(executor) => executor.manifest(), - } + self.inner.manifest() } #[cfg(feature = "server")] pub(crate) fn can_submit(&self, grammar: bool) -> bool { - match &self.inner { - RankExecutorInner::Local(executor) => executor.can_submit(grammar), - RankExecutorInner::Parallel(executor) => executor.can_submit(grammar), - RankExecutorInner::Threaded(executor) => executor.can_submit(grammar), - } + !self.leases.should_drain_for_offload() && self.inner.can_submit(grammar) } #[cfg(feature = "server")] pub(crate) fn next_fence(&self) -> Result { - match &self.inner { - RankExecutorInner::Local(executor) => executor.next_fence(), - RankExecutorInner::Parallel(executor) => executor.next_fence(), - RankExecutorInner::Threaded(executor) => executor.next_fence(), - } + self.inner.next_fence() } pub(crate) fn close(&mut self) -> Shutdown { - let shutdown = match &mut self.inner { - RankExecutorInner::Local(executor) => executor.close(), - RankExecutorInner::Parallel(executor) => executor.close(), - RankExecutorInner::Threaded(executor) => executor.close(), - }; - // Release any uncompleted peer-copy leases after drain (or error teardown) - // so host-store close cannot block waiting on paused offload threads. - self.peer_guards.clear(); + let shutdown = self.inner.close(); + self.leases.clear(); shutdown } } @@ -195,8 +210,18 @@ mod tests { let merged = merge_peer_copy_graphs(&root, Some(&peers)); assert_eq!(merged, vec![true, true, true]); - assert!(!manifest().has_peer_copies(0)); - assert!(root.has_peer_copies(1)); - assert!(!root.has_peer_copies(99)); + } + + #[test] + fn manifest_rejects_mismatched_peer_copy_graphs_length() { + let mut bad = manifest(); + bad.peer_copy_graphs = vec![true, false]; + let err = bad + .validate() + .expect_err("mismatched peer_copy_graphs length must fail validation"); + assert!( + err.to_string().contains("peer_copy_graphs"), + "unexpected validation error: {err}" + ); } } diff --git a/helios/src/offload/copy_gate.rs b/helios/src/offload/copy_gate.rs index 1a929544d..596f381ad 100644 --- a/helios/src/offload/copy_gate.rs +++ b/helios/src/offload/copy_gate.rs @@ -11,24 +11,72 @@ //! collectives) can deadlock on discrete PCIe GPUs when another stream issues //! concurrent device-to-host or host-to-device Copy Engine batches on the same //! devices. This gate lets offload workers issue batches concurrently across ranks -//! while no peer-copy graph is in flight, and pauses new offload batches between -//! `BATCH_BYTES` windows while any peer-copy graph executes. +//! while no peer-copy graph is in flight, pauses new offload batches between +//! `BATCH_BYTES` windows while peer-copy graphs execute, and grants bounded +//! fairness turns to waiting offload batches under continuous pipelined peer-copy +//! traffic so neither inbound restores nor outbound checkpoint unpins starve. +use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use crate::{Error, ExecutionError, Result, cache::Fence}; + +/// Maximum time a model worker waits for in-flight offload Copy Engine batches +/// to drain before failing the submission rather than hanging silently. +/// Aligned with `ThreadedExecutor`'s 120 s stall deadline. +pub const PEER_GRAPH_GATE_TIMEOUT: Duration = Duration::from_secs(120); + +/// Maximum consecutive peer-copy graph admissions while at least one offload +/// batch is waiting before the gate yields one concurrent wave to waiting +/// offload workers. Bounds starvation under 2-frame pipelined decode while +/// keeping prefill bursts prioritized. +const MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING: usize = 4; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Turn { + #[default] + Peer, + Offload, +} #[derive(Default, Debug)] struct State { peer_graphs_active: usize, peer_graphs_waiting: usize, offload_batches_active: usize, + offload_batches_waiting: usize, + peer_entries_while_offload_waiting: usize, + turn: Turn, + offload_wave_remaining: usize, +} + +impl State { + fn maybe_arm_offload_wave(&mut self) -> bool { + if self.peer_graphs_active == 0 + && self.turn == Turn::Peer + && self.offload_batches_waiting > 0 + && self.peer_entries_while_offload_waiting >= MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING + { + self.turn = Turn::Offload; + self.offload_wave_remaining = self.offload_batches_waiting; + self.peer_entries_while_offload_waiting = 0; + true + } else { + false + } + } } /// Per-runtime gate serializing offload Copy Engine batches against peer-copy graphs. /// /// Offload workers on different ranks may hold [`OffloadBatchGuard`] concurrently. /// Multiple pipelined peer-copy graphs may hold [`PeerGraphGuard`] concurrently. -/// Peer-copy graphs take priority once waiting so sustained offload traffic cannot -/// starve prefill launch, and every guard releases on drop including panic unwind. +/// Peer-copy graphs take priority by default, yield a bounded concurrent wave to +/// waiting offload batches after [`MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING`] +/// consecutive admissions so pipelined decode cannot starve offload, and fail +/// with a timeout error if an offload batch fails to drain within +/// [`PEER_GRAPH_GATE_TIMEOUT`]. Every guard releases on drop including panic unwind. #[derive(Default, Debug)] pub struct CopyEngineGate { state: Mutex, @@ -40,30 +88,114 @@ impl CopyEngineGate { Self::default() } - /// Wait for any in-flight offload Copy Engine batches to finish and hold the - /// gate open for a peer-copy graph until the returned guard drops. - pub fn enter_peer_graph(self: &Arc) -> PeerGraphGuard { + /// True when waiting offload batches have earned the next Copy Engine turn so + /// a pipelined executor should pause submitting additional frames until active + /// peer-copy frames drain to zero. + pub fn should_yield_to_offload(&self) -> bool { + let state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + state.turn == Turn::Offload + || (state.offload_batches_waiting > 0 + && state.peer_entries_while_offload_waiting + >= MAX_PEER_STREAK_WHILE_OFFLOAD_WAITING) + } + + /// Wait up to [`PEER_GRAPH_GATE_TIMEOUT`] for any in-flight offload Copy Engine + /// batches to finish and hold the gate open for a peer-copy graph until the + /// returned guard drops. + pub fn enter_peer_graph(self: &Arc) -> Result { + self.enter_peer_graph_timeout(PEER_GRAPH_GATE_TIMEOUT) + } + + /// Bounded variant of [`Self::enter_peer_graph`] with an explicit timeout. + pub fn enter_peer_graph_timeout( + self: &Arc, + timeout: Duration, + ) -> Result { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); - state.peer_graphs_waiting += 1; - while state.offload_batches_active > 0 { - state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + if state.maybe_arm_offload_wave() { + self.changed.notify_all(); + } + // Only wait for an offload turn when no peer graph is currently active so + // a single-threaded pipelined caller can never self-deadlock on its own frame. + let needs_wait = |s: &State| { + s.offload_batches_active > 0 + || (s.peer_graphs_active == 0 + && s.turn == Turn::Offload + && s.offload_wave_remaining > 0) + }; + if needs_wait(&state) { + state.peer_graphs_waiting += 1; + let deadline = Instant::now() + timeout; + while needs_wait(&state) { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + state.peer_graphs_waiting = state.peer_graphs_waiting.saturating_sub(1); + if state.peer_graphs_waiting == 0 { + self.changed.notify_all(); + } + return Err(Error::execution( + ExecutionError::Drain, + format!( + "timed out after {timeout:?} waiting for offload Copy Engine batches to drain \ + (offload_active={}, offload_waiting={}, turn={:?}, wave_remaining={})", + state.offload_batches_active, + state.offload_batches_waiting, + state.turn, + state.offload_wave_remaining, + ), + )); + } + let (guard, wait_res) = self + .changed + .wait_timeout(state, remaining) + .unwrap_or_else(|e| e.into_inner()); + state = guard; + if wait_res.timed_out() && needs_wait(&state) { + continue; + } + } + state.peer_graphs_waiting = state.peer_graphs_waiting.saturating_sub(1); + } + state.turn = Turn::Peer; + if state.offload_batches_waiting > 0 { + state.peer_entries_while_offload_waiting += 1; + } else { + state.peer_entries_while_offload_waiting = 0; } - state.peer_graphs_waiting -= 1; state.peer_graphs_active += 1; - PeerGraphGuard { + Ok(PeerGraphGuard { gate: Arc::clone(self), - } + }) } - /// Wait until no peer-copy graph is waiting or active, then permit one offload - /// Copy Engine batch until the returned guard drops. - pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> { + /// Wait until no peer-copy graph is active and this batch is permitted to run, + /// returning the active lease together with the time spent waiting on the gate. + pub fn enter_offload_batch(&self) -> (OffloadBatchGuard<'_>, Duration) { let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); - while state.peer_graphs_active > 0 || state.peer_graphs_waiting > 0 { - state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + let must_wait = |s: &State| { + s.peer_graphs_active > 0 + || (s.peer_graphs_waiting > 0 + && !(s.turn == Turn::Offload && s.offload_wave_remaining > 0)) + }; + let waited = if must_wait(&state) { + let started = Instant::now(); + state.offload_batches_waiting += 1; + while must_wait(&state) { + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.offload_batches_waiting = state.offload_batches_waiting.saturating_sub(1); + started.elapsed() + } else { + Duration::ZERO + }; + if state.turn == Turn::Offload && state.offload_wave_remaining > 0 { + state.offload_wave_remaining -= 1; + if state.offload_wave_remaining == 0 { + state.turn = Turn::Peer; + } } state.offload_batches_active += 1; - OffloadBatchGuard { gate: self } + (OffloadBatchGuard { gate: self }, waited) } } @@ -79,6 +211,12 @@ impl Drop for PeerGraphGuard { let mut state = self.gate.state.lock().unwrap_or_else(|e| e.into_inner()); state.peer_graphs_active = state.peer_graphs_active.saturating_sub(1); if state.peer_graphs_active == 0 { + if !state.maybe_arm_offload_wave() && state.offload_batches_waiting == 0 { + state.peer_entries_while_offload_waiting = 0; + if state.offload_wave_remaining == 0 { + state.turn = Turn::Peer; + } + } self.gate.changed.notify_all(); } } @@ -101,6 +239,71 @@ impl Drop for OffloadBatchGuard<'_> { } } +/// Tracks active [`PeerGraphGuard`] leases in fence order for an executor loop. +#[derive(Debug, Default)] +pub struct PeerGraphLeases { + copy_gate: Option>, + peer_copy_graphs: Vec, + guards: VecDeque<(Fence, PeerGraphGuard)>, +} + +impl PeerGraphLeases { + pub fn new(copy_gate: Option>, peer_copy_graphs: Vec) -> Self { + Self { + copy_gate, + peer_copy_graphs, + guards: VecDeque::new(), + } + } + + /// True when the executor holds at least one active peer-copy lease and waiting + /// offload batches have earned a bounded turn, signaling the worker to drain + /// in-flight frames before submitting another pipelined frame. + pub fn should_drain_for_offload(&self) -> bool { + !self.guards.is_empty() + && self + .copy_gate + .as_deref() + .is_some_and(CopyEngineGate::should_yield_to_offload) + } + + /// Acquire a peer-copy lease when `graph` contains peer-copy nodes and a gate is attached. + pub fn enter(&self, graph: usize) -> Result> { + if self.peer_copy_graphs.get(graph).copied().unwrap_or(false) { + self.copy_gate + .as_ref() + .map(CopyEngineGate::enter_peer_graph) + .transpose() + } else { + Ok(None) + } + } + + /// Record an acquired lease against its submitted fence. + pub fn track(&mut self, fence: Option, guard: Option) { + if let (Some(fence), Some(guard)) = (fence, guard) { + self.guards.push_back((fence, guard)); + } + } + + /// Release every lease whose fence completed at or before `fence`. + pub fn release_through(&mut self, fence: Fence) { + while self + .guards + .front() + .is_some_and(|(queued, _)| *queued <= fence) + { + self.guards.pop_front(); + } + } + + /// Release all remaining leases after executor drain or teardown so host-store + /// close cannot block waiting on paused offload threads. + pub fn clear(&mut self) { + self.guards.clear(); + } +} + #[cfg(test)] mod tests { use super::*; @@ -109,7 +312,6 @@ mod tests { atomic::{AtomicBool, AtomicUsize, Ordering}, }; use std::thread; - use std::time::{Duration, Instant}; #[test] fn offload_batches_run_concurrently_across_ranks() { @@ -120,7 +322,8 @@ mod tests { let gate = Arc::clone(&gate); let barrier = Arc::clone(&barrier); thread::spawn(move || { - let _guard = gate.enter_offload_batch(); + let (_guard, waited) = gate.enter_offload_batch(); + assert_eq!(waited, Duration::ZERO); barrier.wait(); }) }) @@ -143,7 +346,7 @@ mod tests { let started = Arc::clone(&offload_started); let release = Arc::clone(&release_offload); let first_offload = thread::spawn(move || { - let _guard = g1.enter_offload_batch(); + let (_guard, _) = g1.enter_offload_batch(); started.wait(); release.wait(); }); @@ -157,16 +360,16 @@ mod tests { let pr = Arc::clone(&peer_ready); let pl = Arc::clone(&peer_release); let peer_thread = thread::spawn(move || { - let _guard1 = g2.enter_peer_graph(); + let guard1 = g2.enter_peer_graph().unwrap(); // Pipelined second peer-copy graph must enter immediately without blocking. - let _guard2 = g2.enter_peer_graph(); + let guard2 = g2.enter_peer_graph().unwrap(); entered.store(true, Ordering::Release); pr.wait(); - drop(_guard1); - // Still holding _guard2: new offload batches must stay blocked. + drop(guard1); + // Still holding guard2: new offload batches must stay blocked. thread::sleep(Duration::from_millis(20)); pl.wait(); - drop(_guard2); + drop(guard2); }); thread::sleep(Duration::from_millis(15)); @@ -181,11 +384,12 @@ mod tests { peer_ready.wait(); assert!(peer_entered.load(Ordering::Acquire)); - // 4. Start a second offload batch while _guard2 is still active -> must block. + // 4. Start a second offload batch while guard2 is still active -> must block. let g3 = Arc::clone(&gate); let second_entered = Arc::clone(&second_offload_entered); let second_offload = thread::spawn(move || { - let _guard = g3.enter_offload_batch(); + let (_guard, waited) = g3.enter_offload_batch(); + assert!(waited > Duration::ZERO); second_entered.store(true, Ordering::Release); }); @@ -195,7 +399,7 @@ mod tests { "offload batch entered while pipelined peer-copy graph was still active" ); - // 5. Release _guard2 -> second offload completes. + // 5. Release guard2 -> second offload completes. peer_release.wait(); peer_thread.join().unwrap(); second_offload.join().unwrap(); @@ -214,7 +418,7 @@ mod tests { let completed = Arc::clone(&completed); thread::spawn(move || { while !stop.load(Ordering::Acquire) { - let _guard = gate.enter_offload_batch(); + let (_guard, _) = gate.enter_offload_batch(); completed.fetch_add(1, Ordering::Relaxed); thread::sleep(Duration::from_millis(1)); } @@ -226,7 +430,7 @@ mod tests { thread::yield_now(); } let started = Instant::now(); - let guard = gate.enter_peer_graph(); + let guard = gate.enter_peer_graph().unwrap(); assert!( started.elapsed() < Duration::from_secs(1), "peer-copy graph was starved by continuous offload batches" @@ -238,26 +442,142 @@ mod tests { } } + #[test] + fn offload_makes_forward_progress_under_pipelined_peer_graphs() { + let gate = Arc::new(CopyEngineGate::new()); + let stop = Arc::new(AtomicBool::new(false)); + let offload_completed = Arc::new(AtomicUsize::new(0)); + + // Simulate Worker::run's single-threaded 2-frame pipelined loop using + // PeerGraphLeases: poll one completed frame, pause pipelining whenever + // should_drain_for_offload() is true, and otherwise submit up to depth 2. + let gp = Arc::clone(&gate); + let sp = Arc::clone(&stop); + let pipeline = thread::spawn(move || { + let mut leases = PeerGraphLeases::new(Some(gp), vec![true]); + let mut in_flight: VecDeque = VecDeque::new(); + let mut next_fence = 1u64; + while !sp.load(Ordering::Acquire) { + while in_flight.len() < 2 && !leases.should_drain_for_offload() { + let guard = leases.enter(0).unwrap(); + let fence = Fence(next_fence); + next_fence += 1; + leases.track(Some(fence), guard); + in_flight.push_back(fence); + } + thread::sleep(Duration::from_millis(1)); + if let Some(done) = in_flight.pop_front() { + leases.release_through(done); + } + } + leases.clear(); + }); + + // Two offload ranks must both make repeated forward progress concurrently. + let workers: Vec<_> = (0..2) + .map(|_| { + let gate = Arc::clone(&gate); + let completed = Arc::clone(&offload_completed); + thread::spawn(move || { + for _ in 0..4 { + let (_guard, _) = gate.enter_offload_batch(); + completed.fetch_add(1, Ordering::Relaxed); + thread::sleep(Duration::from_millis(1)); + } + }) + }) + .collect(); + + let started = Instant::now(); + for worker in workers { + worker.join().unwrap(); + } + assert_eq!(offload_completed.load(Ordering::Acquire), 8); + assert!( + started.elapsed() < Duration::from_secs(2), + "offload starved under 2-frame pipelined peer graphs" + ); + stop.store(true, Ordering::Release); + pipeline.join().unwrap(); + } + + #[test] + fn enter_peer_graph_times_out_without_stranding_gate() { + let gate = Arc::new(CopyEngineGate::new()); + let (_offload, _) = gate.enter_offload_batch(); + let err = gate + .enter_peer_graph_timeout(Duration::from_millis(20)) + .expect_err("peer graph must time out while offload holds the gate"); + assert!( + err.to_string().contains("timed out"), + "unexpected timeout error: {err}" + ); + // Releasing the stuck offload batch must leave the gate clean for both sides. + drop(_offload); + let peer = gate + .enter_peer_graph_timeout(Duration::from_millis(100)) + .unwrap(); + drop(peer); + let (_offload2, _) = gate.enter_offload_batch(); + } + #[test] fn panic_unwind_releases_guards_without_stranding_waiters() { let gate = Arc::new(CopyEngineGate::new()); let g = Arc::clone(&gate); let _ = thread::spawn(move || { - let _guard = g.enter_peer_graph(); + let _guard = g.enter_peer_graph().unwrap(); panic!("simulated panic holding peer graph guard"); }) .join(); // Subsequent offload batch must acquire immediately. - let _offload = gate.enter_offload_batch(); + let (_offload, _) = gate.enter_offload_batch(); drop(_offload); let g = Arc::clone(&gate); let _ = thread::spawn(move || { - let _guard = g.enter_offload_batch(); + let (_guard, _) = g.enter_offload_batch(); panic!("simulated panic holding offload batch guard"); }) .join(); // Subsequent peer-copy graph must acquire immediately. - let _peer = gate.enter_peer_graph(); + let _peer = gate.enter_peer_graph().unwrap(); + } + + #[test] + fn peer_graph_leases_release_in_fence_order_and_clear_on_close() { + let gate = Arc::new(CopyEngineGate::new()); + let mut leases = PeerGraphLeases::new(Some(Arc::clone(&gate)), vec![false, true]); + + // Unflagged graph takes no lease. + assert!(leases.enter(0).unwrap().is_none()); + + // Track two pipelined peer-copy graphs on fences 10 and 11. + let g1 = leases.enter(1).unwrap(); + assert!(g1.is_some()); + leases.track(Some(Fence(10)), g1); + let g2 = leases.enter(1).unwrap(); + assert!(g2.is_some()); + leases.track(Some(Fence(11)), g2); + + // Completing fence 10 pops only the first lease; offload must still block on fence 11. + leases.release_through(Fence(10)); + let entered = Arc::new(AtomicBool::new(false)); + let g_off = Arc::clone(&gate); + let ent = Arc::clone(&entered); + let worker = thread::spawn(move || { + let (_guard, _) = g_off.enter_offload_batch(); + ent.store(true, Ordering::Release); + }); + thread::sleep(Duration::from_millis(15)); + assert!( + !entered.load(Ordering::Acquire), + "offload entered while fence 11 lease was still active" + ); + + // Clearing residual leases on close immediately unblocks waiting offload. + leases.clear(); + worker.join().unwrap(); + assert!(entered.load(Ordering::Acquire)); } } diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 371facdad..4110b8183 100644 --- a/helios/src/offload/mod.rs +++ b/helios/src/offload/mod.rs @@ -23,7 +23,7 @@ mod registrar; pub mod shard; pub mod transfer; -pub use copy_gate::{CopyEngineGate, OffloadBatchGuard, PeerGraphGuard}; +pub use copy_gate::{CopyEngineGate, PeerGraphGuard, PeerGraphLeases}; pub use flare_selene::pool::{PoolOptions, parse_pool_address}; use flare_selene::{CacheGeometry, HostStore}; @@ -39,14 +39,14 @@ pub use flare_selene::offload::{ pub struct Binding { inner: flare_selene::offload::Binding, gpu_cubins: Vec>>, - copy_gate: std::sync::Arc, + copy_gate: Option>, } impl Binding { pub(crate) fn new( inner: flare_selene::offload::Binding, gpu_cubins: Vec>>, - copy_gate: std::sync::Arc, + copy_gate: Option>, ) -> Self { Self { inner, @@ -55,8 +55,8 @@ impl Binding { } } - pub(crate) fn copy_gate(&self) -> std::sync::Arc { - std::sync::Arc::clone(&self.copy_gate) + pub(crate) fn copy_gate(&self) -> Option> { + self.copy_gate.clone() } pub fn inputs(&self) -> Option { diff --git a/helios/src/offload/shard.rs b/helios/src/offload/shard.rs index d32d7e886..b2aef35e5 100644 --- a/helios/src/offload/shard.rs +++ b/helios/src/offload/shard.rs @@ -40,11 +40,22 @@ pub fn join_peer( stream: &mut RankStream, rank: usize, world: usize, +) -> Result> { + join_peer_with_gate(store, gpu_cubins, None, stream, rank, world) +} + +pub fn join_peer_with_gate( + store: Option<&Shared>, + gpu_cubins: Vec>>, + copy_gate: Option>, + stream: &mut RankStream, + rank: usize, + world: usize, ) -> Result> { Ok(flare_selene::offload::sharded::join_peer( store, rank, - &super::transfer::Copiers::new(gpu_cubins), + &super::transfer::Copiers::with_gate(gpu_cubins, copy_gate), |record| Ok(rendezvous::exchange_record(stream, record, world)?), )?) } diff --git a/helios/src/offload/transfer.rs b/helios/src/offload/transfer.rs index 2efe566f6..59ae9fd9b 100644 --- a/helios/src/offload/transfer.rs +++ b/helios/src/offload/transfer.rs @@ -16,7 +16,10 @@ //! is reported only after the stream has drained, so destination ids are //! quiescent when the scheduler frees them. The model stream never waits on //! these streams: host-observed completion orders later model work after the -//! copies. +//! copies. When a loaded model contains CUDA graphs with in-graph peer-to-peer +//! Copy Engine nodes, offload batches coordinate with those graphs through +//! [`super::CopyEngineGate`] so host copies never overlap peer-copy graphs on +//! the same devices while leaving single-GPU and non-peer-copy models ungated. //! //! Copies within one batch execute in no defined order, so a job may not name //! a page id or a slab address twice: either would be two writes to one range @@ -30,7 +33,7 @@ use std::{ collections::HashMap, sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, SyncSender, TrySendError}, thread::JoinHandle, - time::Instant, + time::{Duration, Instant}, }; use flare_selene::{ @@ -72,12 +75,14 @@ struct RankReply { rank: usize, result: Result<()>, bytes: u64, + gate_wait: Duration, } struct Pending { direction: Direction, remaining: usize, bytes: u64, + max_gate_wait: Duration, error: Option, started: Instant, } @@ -282,6 +287,57 @@ fn lower_priority() { crate::os::lower_priority(NICE); } +/// Wait for every copy issued on `stream` so far, sleeping on `event` where it +/// can be recorded and spinning on the stream otherwise. +pub(super) fn drain_stream(stream: &Stream, event: &Event) { + if stream.record(event).is_err() || event.synchronize().is_err() { + let _ = stream.synchronize(); + } +} + +/// Issue one Copy Engine batch, optionally bounded by `copy_gate`. +/// +/// When `copy_gate` is `Some`, acquires an offload batch lease, synchronizes the +/// stream before releasing the lease (including on error), and returns the time +/// spent waiting on the gate. When `None`, enqueues the batch without syncing so +/// the caller can synchronize once at window completion. +/// +/// # Safety +/// Every `(destination, source, bytes)` entry must point to live, mapped, non-overlapping +/// ranges valid for the duration of the copy. +pub(super) unsafe fn copy_batch_gated( + stream: &Stream, + event: &Event, + copy_gate: Option<&super::CopyEngineGate>, + destinations: &[u64], + sources: &[u64], + sizes: &[usize], +) -> Result { + if let Some(gate) = copy_gate { + struct DrainOnDrop<'a>(&'a Stream, &'a Event); + impl Drop for DrainOnDrop<'_> { + fn drop(&mut self) { + drain_stream(self.0, self.1); + } + } + let (_ce, waited) = gate.enter_offload_batch(); + // Declared after `_ce` so any error drains the stream before releasing the gate. + let drain = DrainOnDrop(stream, event); + unsafe { + stream.copy_batch(destinations, sources, sizes)?; + } + stream.record(event)?; + event.synchronize()?; + std::mem::forget(drain); + Ok(waited) + } else { + unsafe { + stream.copy_batch(destinations, sources, sizes)?; + } + Ok(Duration::ZERO) + } +} + struct RankWorker { codec: Option, rank: usize, @@ -354,8 +410,9 @@ impl RankWorker { }) } - /// Issue every batch of the job, then wait for the last one; returns the bytes copied. - fn run(&mut self, job: &Job) -> Result { + /// Issue every batch of the job, then wait for the last one; returns the bytes copied + /// and cumulative time spent waiting on `CopyEngineGate`. + fn run(&mut self, job: &Job) -> Result<(u64, Duration)> { if let Some(window) = &job.codec { return self .codec @@ -381,6 +438,7 @@ impl RankWorker { )?; let mut start = 0; let mut bytes = 0u64; + let mut gate_wait = Duration::ZERO; while start < self.descriptors.len() { let end = batch_end(&self.descriptors, start); if end == start { @@ -395,63 +453,43 @@ impl RankWorker { self.sizes.push(descriptor.bytes); bytes += descriptor.bytes as u64; } - if let Some(gate) = self.copy_gate.as_deref() { - struct DrainOnDrop<'a>(&'a Stream, &'a Event); - impl Drop for DrainOnDrop<'_> { - fn drop(&mut self) { - if self.0.record(self.1).is_err() || self.1.synchronize().is_err() { - let _ = self.0.synchronize(); - } - } - } - let _ce = gate.enter_offload_batch(); - // Declared after `_ce` so any error drains the stream before releasing the gate. - let drain = DrainOnDrop(&self.stream, &self.event); - // SAFETY: Device ranges lie inside the rank's cache allocations by - // the id checks in `expand`, and the submitting store keeps every - // slab mapped, registered, and unchanged until this job's reply. - unsafe { - self.stream - .copy_batch(&self.destinations, &self.sources, &self.sizes)?; - } - self.stream.record(&self.event)?; - self.event.synchronize()?; - std::mem::forget(drain); - } else { - // SAFETY: Device ranges lie inside the rank's cache allocations by - // the id checks in `expand`, and the submitting store keeps every - // slab mapped, registered, and unchanged until this job's reply. - unsafe { - self.stream - .copy_batch(&self.destinations, &self.sources, &self.sizes)?; - } - } + // SAFETY: Device ranges lie inside the rank's cache allocations by + // the id checks in `expand`, and the submitting store keeps every + // slab mapped, registered, and unchanged until this job's reply. + gate_wait += unsafe { + copy_batch_gated( + &self.stream, + &self.event, + self.copy_gate.as_deref(), + &self.destinations, + &self.sources, + &self.sizes, + )? + }; start = end; } if self.copy_gate.is_none() { self.stream.record(&self.event)?; self.event.synchronize()?; } - Ok(bytes) + Ok((bytes, gate_wait)) } /// Wait for every copy issued so far, sleeping on the blocking event where /// it can be recorded and spinning on the stream otherwise. fn drain(&self) { - if self.stream.record(&self.event).is_err() || self.event.synchronize().is_err() { - let _ = self.stream.synchronize(); - } + drain_stream(&self.stream, &self.event); } fn serve(mut self, jobs: Receiver, replies: Sender) { for job in jobs { - let (result, bytes) = match self.run(&job) { - Ok(bytes) => (Ok(()), bytes), + let (result, bytes, gate_wait) = match self.run(&job) { + Ok((bytes, gate_wait)) => (Ok(()), bytes, gate_wait), Err(error) => { // Drain the stream before reporting, so destination ids // are quiescent when the caller frees them. self.drain(); - (Err(error), 0) + (Err(error), 0, Duration::ZERO) } }; let reply = RankReply { @@ -460,6 +498,7 @@ impl RankWorker { rank: self.rank, result, bytes, + gate_wait, }; if replies.send(reply).is_err() { break; @@ -648,6 +687,7 @@ impl PageCopier for Transfers { direction: job.direction, remaining: self.ranks.len(), bytes: 0, + max_gate_wait: Duration::ZERO, error: None, started: Instant::now(), }; @@ -737,6 +777,7 @@ impl Transfers { return; }; pending.bytes += reply.bytes; + pending.max_gate_wait = pending.max_gate_wait.max(reply.gate_wait); if let Err(error) = reply.result { pending.error.get_or_insert(error); } @@ -751,7 +792,10 @@ impl Transfers { direction: pending.direction, result: pending.error.map_or(Ok(()), Err), bytes: pending.bytes, - elapsed: pending.started.elapsed(), + elapsed: pending + .started + .elapsed() + .saturating_sub(pending.max_gate_wait), }); } } @@ -1243,6 +1287,7 @@ mod tests { direction: Direction::Out, remaining: 2, bytes: 0, + max_gate_wait: Duration::ZERO, error: None, started, }, @@ -1254,6 +1299,7 @@ mod tests { rank, result, bytes, + gate_wait: Duration::ZERO, }; let mut replies = Vec::new(); sender.send(reply(JobId(1), 0, 1, Ok(()), 100)).unwrap(); @@ -1296,6 +1342,7 @@ mod tests { direction: Direction::In, remaining: 1, bytes: 0, + max_gate_wait: Duration::ZERO, error: None, started: Instant::now(), }, @@ -1376,6 +1423,7 @@ mod tests { rank: 0, result: Ok(()), bytes: 40, + gate_wait: Duration::ZERO, }) .unwrap(); transfers.poll(&mut replies); @@ -1961,6 +2009,49 @@ mod tests { } transfers.close().unwrap(); drop(transfers); + + // Also exercise the gated transfer path: holding a PeerGraphGuard must defer + // offload batches until dropped, and the reported elapsed duration must exclude + // the time paused on the gate. + let gate = std::sync::Arc::new(crate::offload::CopyEngineGate::new()); + let mut gated = Copiers::with_gate(Vec::new(), Some(std::sync::Arc::clone(&gate))) + .start(&contexts, geometry.clone(), Some(&pool)) + .unwrap(); + let peer_guard = gate.enter_peer_graph().unwrap(); + gated + .submit(Job { + codec: None, + replication: Default::default(), + id: JobId(3), + window: 0, + direction: Direction::Out, + pages: sources + .iter() + .zip(&slabs) + .map(|(id, slab)| (PageId(*id), *slab)) + .collect(), + row: Some((StateSlotId(1), vec![row_slab])), + }) + .unwrap(); + std::thread::sleep(Duration::from_millis(30)); + let mut early = Vec::new(); + gated.poll(&mut early); + assert!( + early.is_empty(), + "gated offload transfer completed while PeerGraphGuard was held" + ); + drop(peer_guard); + let reply = wait(&mut gated); + assert!(reply.result.is_ok(), "{:?}", reply.result); + assert_eq!(reply.bytes, unit_bytes); + assert!( + reply.elapsed < Duration::from_millis(25), + "gate wait was not subtracted from transfer elapsed: {:?}", + reply.elapsed + ); + gated.close().unwrap(); + drop(gated); + drop(pool); let released = free(); for rank in 0..2 { @@ -2074,6 +2165,7 @@ pub(crate) struct Copiers { } impl Copiers { + #[cfg(test)] pub(crate) fn new(gpu_cubins: Vec>>) -> Self { Self::with_gate(gpu_cubins, None) } diff --git a/helios/src/offload/transfer/codec.rs b/helios/src/offload/transfer/codec.rs index 5e57eaacd..b71dbdb8f 100644 --- a/helios/src/offload/transfer/codec.rs +++ b/helios/src/offload/transfer/codec.rs @@ -160,7 +160,7 @@ impl RankCodec { copy_gate: Option<&super::super::CopyEngineGate>, job: &Job, window: &Window, - ) -> Result { + ) -> Result<(u64, Duration)> { let mut stats = DecodeStats::default(); let result = match job.direction { Direction::In => self.restore_window( @@ -228,7 +228,7 @@ impl RankCodec { job: &Job, window: &Window, stats: &mut DecodeStats, - ) -> Result { + ) -> Result<(u64, Duration)> { let capture = window .capture .as_ref() @@ -237,6 +237,7 @@ impl RankCodec { let first = window.first; let mut transferred = 0u64; let mut stored = 0u64; + let mut gate_wait = Duration::ZERO; match self.write_mode { KvCompression::Gpu => { let page_bytes = self.original_bytes(false); @@ -280,14 +281,15 @@ impl RankCodec { owned_batches.push((units, spans_per_page)); page_offset += chunk.len(); } - let start = Instant::now(); let batch_refs: Vec<(&[PackedUnit], &[Vec])> = owned_batches .iter() .map(|(u, s)| (u.as_slice(), s.as_slice())) .collect(); - let stored_len = { + let (stored_len, elapsed, waited) = { let mut guard = gpu.codec.lock().unwrap(); - let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let res = guard.encode_pages_batches_with( page_plan, &batch_refs, @@ -296,10 +298,11 @@ impl RankCodec { event, |unit, bytes| capture.push_slice(unit, bytes), ); - sync_on_err(stream, res) - } - .map_err(decode_error)?; - stats.transform_ns += start.elapsed().as_nanos() as u64; + let stored_len = sync_on_err(stream, res).map_err(decode_error)?; + (stored_len, start.elapsed(), waited) + }; + gate_wait += waited; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; } transferred += (page_bytes * job.pages.len()) as u64; @@ -312,10 +315,11 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let start = Instant::now(); - let stored_len = { + let (stored_len, elapsed, waited) = { let mut guard = gpu.codec.lock().unwrap(); - let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let res = guard.encode_from_device_with( page_plan, base_unit, @@ -329,10 +333,11 @@ impl RankCodec { slen }, ); - sync_on_err(stream, res) - } - .map_err(decode_error)?; - stats.transform_ns += start.elapsed().as_nanos() as u64; + let stored_len = sync_on_err(stream, res).map_err(decode_error)?; + (stored_len, start.elapsed(), waited) + }; + gate_wait += waited; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += page_bytes as u64; } @@ -346,10 +351,11 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let start = Instant::now(); - let stored_len = { + let (stored_len, elapsed, waited) = { let mut guard = gpu.codec.lock().unwrap(); - let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let res = guard.encode_from_device_with( &self.cpu.gpu_row, base_unit, @@ -363,10 +369,11 @@ impl RankCodec { slen }, ); - sync_on_err(stream, res) - } - .map_err(decode_error)?; - stats.transform_ns += start.elapsed().as_nanos() as u64; + let stored_len = sync_on_err(stream, res).map_err(decode_error)?; + (stored_len, start.elapsed(), waited) + }; + gate_wait += waited; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += n as u64; } @@ -389,7 +396,7 @@ impl RankCodec { ); batch_spans.push((slot_start, spans)); } - copy_spans_batch( + gate_wait += copy_spans_batch( stream, event, copy_gate, @@ -460,7 +467,7 @@ impl RankCodec { let n = self.cpu.row.original_bytes(); let spans = device_spans(geometry, layout, true, u64::from(slot.0))?; zero_span_gaps(&mut self.cpu.staging.bytes_mut()[..n], &spans); - copy_spans_batch( + gate_wait += copy_spans_batch( stream, event, copy_gate, @@ -494,7 +501,7 @@ impl RankCodec { } } stats.stored_bytes = stored; - Ok(transferred) + Ok((transferred, gate_wait)) } fn decode_route(&self, u: &PackedUnit, representation: Representation) -> Result { @@ -535,7 +542,7 @@ impl RankCodec { event: &Event, copy_gate: Option<&super::super::CopyEngineGate>, stats: &mut DecodeStats, - ) -> Result<()> { + ) -> Result { let pool = cpu_pool()?; let page_bytes = self.cpu.page.original_bytes(); let staging_slice = &mut self.cpu.staging.bytes_mut()[..items.len() * page_bytes]; @@ -586,11 +593,12 @@ impl RankCodec { job: &Job, window: &Window, stats: &mut DecodeStats, - ) -> Result { + ) -> Result<(u64, Duration)> { reject_duplicate_pages(job)?; let first = window.first; let mut transferred = 0u64; let mut stored = 0u64; + let mut gate_wait = Duration::ZERO; let page_bytes = self.cpu.page.original_bytes(); let batch_cap = (self.cpu.staging.bytes().len() / page_bytes.max(1)).max(1); let all_pages_cpu_path = job.pages.len() > 1 @@ -624,7 +632,8 @@ impl RankCodec { items.push((u, route, chunks)); batch_spans.push((slot_idx * page_bytes, spans)); } - self.decode_pages_cpu_batch(&items, &batch_spans, stream, event, copy_gate, stats)?; + gate_wait += + self.decode_pages_cpu_batch(&items, &batch_spans, stream, event, copy_gate, stats)?; transferred += (chunk.len() * page_bytes) as u64; remaining_pages_offset += chunk.len(); } @@ -661,11 +670,12 @@ impl RankCodec { j += 1; } if run_chunks.len() > 1 { - let start = Instant::now(); let gpu_ran = { if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { - let _ce = + let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let packets: Vec<(&[&[u8]], u32, u32)> = run_chunks .iter() .zip(&run_units) @@ -679,13 +689,14 @@ impl RankCodec { event, ); sync_on_err(stream, res).map_err(decode_error)?; - true + Some((start.elapsed(), waited)) } else { - false + None } }; - if gpu_ran { - stats.transform_ns += start.elapsed().as_nanos() as u64; + if let Some((elapsed, waited)) = gpu_ran { + gate_wait += waited; + stats.transform_ns += elapsed.as_nanos() as u64; } else { // Background GPU capture currently holds the codec mutex: decode this // critical-path restore run on the bounded CPU pool instead of blocking. @@ -704,7 +715,7 @@ impl RankCodec { .enumerate() .map(|(s, sp)| (s * page_bytes, sp.clone())) .collect(); - self.decode_pages_cpu_batch( + gate_wait += self.decode_pages_cpu_batch( &items, &batch_spans, stream, @@ -746,10 +757,11 @@ impl RankCodec { } else { &self.cpu.gpu_page }; - let start = Instant::now(); let gpu_ran = { if let Ok(mut guard) = self.gpu.as_mut().unwrap().codec.try_lock() { - let _ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let ce = copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let res = guard.decode_to_device( plan, &chunks, @@ -760,13 +772,14 @@ impl RankCodec { event, ); sync_on_err(stream, res).map_err(decode_error)?; - true + Some((start.elapsed(), waited)) } else { - false + None } }; - if gpu_ran { - stats.transform_ns += start.elapsed().as_nanos() as u64; + if let Some((elapsed, waited)) = gpu_ran { + gate_wait += waited; + stats.transform_ns += elapsed.as_nanos() as u64; } else { route = DecodeRoute::GpuOnCpu; } @@ -785,7 +798,7 @@ impl RankCodec { if route != DecodeRoute::Literal { stats.transform_ns += start.elapsed().as_nanos() as u64; } - copy_spans_batch( + gate_wait += copy_spans_batch( stream, event, copy_gate, @@ -797,7 +810,7 @@ impl RankCodec { transferred += n as u64; } stats.stored_bytes = stored; - Ok(transferred) + Ok((transferred, gate_wait)) } } @@ -962,36 +975,26 @@ fn copy_spans_batch( direction: Direction, batch: &[(usize, Vec)], host: u64, -) -> Result<()> { - struct Fence<'a>(&'a Stream); +) -> Result { + struct Fence<'a>(&'a Stream, &'a Event); impl Drop for Fence<'_> { fn drop(&mut self) { - let _ = self.0.synchronize(); + drain_stream(self.0, self.1); } } let mut dsts = Vec::new(); let mut srcs = Vec::new(); let mut lens = Vec::new(); let mut queued = 0usize; - let flush = |dsts: &mut Vec, srcs: &mut Vec, lens: &mut Vec, queued: &mut usize| -> Result<()> { + let mut gate_wait = Duration::ZERO; + let mut flush = |dsts: &mut Vec, + srcs: &mut Vec, + lens: &mut Vec, + queued: &mut usize| + -> Result<()> { if !lens.is_empty() { - if let Some(gate) = copy_gate { - let _ce = gate.enter_offload_batch(); - // Declared after `_ce` so any error drains the stream before releasing the gate. - let fence = Fence(stream); - // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. - unsafe { - stream.copy_batch(dsts, srcs, lens)?; - } - stream.record(event)?; - event.synchronize()?; - std::mem::forget(fence); - } else { - // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. - unsafe { - stream.copy_batch(dsts, srcs, lens)?; - } - } + // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. + gate_wait += unsafe { copy_batch_gated(stream, event, copy_gate, dsts, srcs, lens)? }; dsts.clear(); srcs.clear(); lens.clear(); @@ -999,7 +1002,7 @@ fn copy_spans_batch( } Ok(()) }; - let fence = copy_gate.is_none().then_some(Fence(stream)); + let fence = copy_gate.is_none().then_some(Fence(stream, event)); for (slot_start, spans) in batch { let base = host + *slot_start as u64; for p in spans { @@ -1027,7 +1030,7 @@ fn copy_spans_batch( event.synchronize()?; } std::mem::forget(fence); - Ok(()) + Ok(gate_wait) } #[cfg(all(test, target_os = "linux", feature = "runtime-core"))] @@ -1042,7 +1045,10 @@ mod tests { shared::wire::packed_unit::Kind, }; - fn run_roundtrip_mode(placement: KvCompression) { + fn run_roundtrip_mode( + placement: KvCompression, + copy_gate: Option>, + ) { let driver = Driver::load().unwrap(); let mut ctx = std::ptr::null_mut(); unsafe { @@ -1126,17 +1132,18 @@ mod tests { let path = std::env::var("FLARE_TEST_KV_CODEC_CUBIN") .expect("set FLARE_TEST_KV_CODEC_CUBIN to a compiled kv_codec_gpu.cubin"); let cubin = Arc::new(std::fs::read(path).unwrap()); - Copiers::new(vec![cubin]) + Copiers::with_gate(vec![cubin], copy_gate.clone()) .start(&[(context, 0)], vec![geometry.clone()], None) .unwrap() } else { - Copiers::new(Vec::new()) + Copiers::with_gate(Vec::new(), copy_gate.clone()) .start(&[(context, 0)], vec![geometry.clone()], None) .unwrap() }; // 1. Capture VRAM -> packed host (Direction::Out) across multiple pages + row. let cap_win = Window::capture(0); + let peer_guard = copy_gate.as_ref().map(|g| g.enter_peer_graph().unwrap()); transfers .submit(Job { id: flare_selene::JobId(1), @@ -1148,6 +1155,16 @@ mod tests { codec: Some(cap_win.clone()), }) .unwrap(); + if let Some(guard) = peer_guard { + std::thread::sleep(Duration::from_millis(30)); + let mut early = Vec::new(); + transfers.poll(&mut early); + assert!( + early.is_empty(), + "gated codec capture completed while PeerGraphGuard was held" + ); + drop(guard); + } let cap_reply = loop { let mut out = Vec::new(); transfers.poll(&mut out); @@ -1257,13 +1274,21 @@ mod tests { #[test] #[ignore = "exercises CPU VRAM <-> DRAM capture and restore onto a GPU"] fn cpu_vram_capture_and_restore_copies_exact_bytes_and_rejects_corruption() { - run_roundtrip_mode(KvCompression::Cpu); + run_roundtrip_mode(KvCompression::Cpu, None); } #[test] #[ignore = "exercises GPU GKV1 VRAM <-> DRAM capture and restore onto a GPU"] fn gpu_vram_capture_and_restore_copies_exact_bytes_and_rejects_corruption() { - run_roundtrip_mode(KvCompression::Gpu); + run_roundtrip_mode(KvCompression::Gpu, None); + } + + #[test] + #[ignore = "exercises gated CPU and GPU codec capture and restore against CopyEngineGate"] + fn gated_cpu_and_gpu_codec_capture_and_restore_defer_while_peer_graph_holds_gate() { + let gate = Arc::new(crate::offload::CopyEngineGate::new()); + run_roundtrip_mode(KvCompression::Cpu, Some(Arc::clone(&gate))); + run_roundtrip_mode(KvCompression::Gpu, Some(gate)); } #[test] diff --git a/helios/src/offload/transfer/lifecycle_tests.rs b/helios/src/offload/transfer/lifecycle_tests.rs index 284218159..80046ecf8 100644 --- a/helios/src/offload/transfer/lifecycle_tests.rs +++ b/helios/src/offload/transfer/lifecycle_tests.rs @@ -289,6 +289,7 @@ fn offload_transfers_match_model() { Ok(()) }, bytes: if failed { 0 } else { rank as u64 + 1 }, + gate_wait: Duration::ZERO, }; if index % 2 == 0 { fixture.replies.send(reply).unwrap(); @@ -409,6 +410,7 @@ fn a_failed_packed_decode_fences_the_other_two_ranks_before_release() { Ok(()) }, bytes: 0, + gate_wait: Duration::ZERO, }, &mut replies, ); diff --git a/helios/src/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index e219d4023..ebf8d270b 100644 --- a/helios/src/runtime_core/mod.rs +++ b/helios/src/runtime_core/mod.rs @@ -1344,6 +1344,10 @@ impl NativeResources { Ok(()) } + pub(super) fn has_any_peer_copy_graphs(&self) -> bool { + self.peer_copy_graphs.iter().any(|&has_peer| has_peer) + } + unsafe fn clamp_cooperative_launch( &self, params: &mut KernelParams, diff --git a/helios/src/runtime_core/model.rs b/helios/src/runtime_core/model.rs index fd0badf00..98099facd 100644 --- a/helios/src/runtime_core/model.rs +++ b/helios/src/runtime_core/model.rs @@ -24,7 +24,7 @@ pub struct NativeModel { pub(super) server_config: serde_json::Value, engram: Vec<(std::sync::Arc, usize)>, pub(super) offload: flare_selene::offload::Startup, - copy_gate: std::sync::Arc, + copy_gate: Option>, gpu_codec_cubins: Vec>>, cluster: Option, roce: Vec>, @@ -659,7 +659,7 @@ impl NativeModel { server_config, engram: Vec::new(), offload: Default::default(), - copy_gate: std::sync::Arc::new(crate::offload::CopyEngineGate::new()), + copy_gate: None, gpu_codec_cubins, cluster, roce, @@ -824,6 +824,11 @@ impl NativeModel { model.parallel(&cores, &files, |rank, core, files| { rank.prepare_graphs(files, core, &phase) })?; + model.copy_gate = model + .ranks + .iter() + .any(NativeResources::has_any_peer_copy_graphs) + .then(|| std::sync::Arc::new(crate::offload::CopyEngineGate::new())); phase.finish(format!("concurrency {active}")); if !engram.is_empty() { let phase = progress.phase("Prepare embedding tables", None); @@ -985,11 +990,15 @@ impl NativeModel { fn attach_offload(&mut self, prepared: crate::offload::Preparation) -> Result { let copiers = crate::offload::transfer::Copiers::with_gate( self.gpu_codec_cubins.clone(), - Some(std::sync::Arc::clone(&self.copy_gate)), + self.copy_gate.clone(), ); Ok(self.offload.attach(prepared, &copiers)?) } + pub fn copy_gate(&self) -> Option> { + self.copy_gate.clone() + } + fn parallel( &mut self, cores: &[Core], @@ -1033,7 +1042,7 @@ impl NativeModel { crate::offload::Binding::new( b, self.gpu_codec_cubins.clone(), - std::sync::Arc::clone(&self.copy_gate), + self.copy_gate.clone(), ) }); if let Some((shared, delivery_rank)) = self.engram.get(index) { @@ -1302,7 +1311,7 @@ mod tests { server_config: serde_json::Value::Null, engram: Vec::new(), offload: Default::default(), - copy_gate: std::sync::Arc::new(crate::offload::CopyEngineGate::new()), + copy_gate: None, cluster: None, roce: Vec::new(), gpu_codec_cubins: Vec::new(), diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 6fba26864..10753af06 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -728,7 +728,7 @@ impl ModelRuntime { if let Some(warning) = prepared.intake_warning() { if log_to_stderr { eprintln!("warning: {warning}"); } } - crate::offload::open_with_gate(prepared, gpu_cubins, Some(copy_gate)) + crate::offload::open_with_gate(prepared, gpu_cubins, copy_gate) }) .transpose() { @@ -2280,27 +2280,6 @@ impl<'a> Worker<'a> { let fence = executor.next_fence()?; self.reserve_and_pack(step, fence)?; let feedback = self.scheduler.submitted_step(fence)?.requires_feedback; - if step - .lanes - .iter() - .enumerate() - .any(|(row, _)| step.lane_kind(row).is_prefill()) - && self.store.is_some() - { - if self.prefill_started.len() >= 8 { - self.prefill_started.pop_front(); - } - self.prefill_started.push_back(( - fence, - std::time::Instant::now(), - step.lanes - .iter() - .enumerate() - .filter(|(row, _)| step.lane_kind(*row).is_prefill()) - .map(|(_, lane)| lane.tokens as u64) - .sum(), - )); - } let mut flags = [0u8; crate::execution::REQUEST_LANES * size_of::()]; let mut counts = [0u8; crate::execution::REQUEST_LANES * size_of::()]; let mut selections = Vec::new(); @@ -2358,6 +2337,27 @@ impl<'a> Worker<'a> { { return Err("executor refused a reserved scheduler submission".into()); } + if step + .lanes + .iter() + .enumerate() + .any(|(row, _)| step.lane_kind(row).is_prefill()) + && self.store.is_some() + { + if self.prefill_started.len() >= 8 { + self.prefill_started.pop_front(); + } + self.prefill_started.push_back(( + fence, + std::time::Instant::now(), + step.lanes + .iter() + .enumerate() + .filter(|(row, _)| step.lane_kind(*row).is_prefill()) + .map(|(_, lane)| lane.tokens as u64) + .sum(), + )); + } observe_submission(self.metrics, &self.scheduler, step, executor.outstanding())?; self.metrics .scheduler_trace