diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index f4294f83a..5d1133615 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,8 +1022,10 @@ 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 +- 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 copy batch or + GPU-codec batch/wave 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. diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 083244444..3531faecc 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -254,6 +254,7 @@ pub fn peer( let records = flare_helios::offload::shard::join_peer( owner.offload(), owner.gpu_codec_cubins().to_vec(), + owner.copy_gate(), &mut stream, cluster.rank, cluster.world, 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, @@ -831,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..310c6a338 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) => { @@ -599,6 +603,7 @@ pub unsafe fn serve_rank( executor.finish_startup()?; channel.send(STARTED, &[])?; let mut prepared: Option<(Fence, usize, bool, Vec)> = None; + let mut ready_pending = false; let mut prepared_at: Option = None; let mut started = VecDeque::new(); loop { @@ -630,11 +635,19 @@ pub unsafe fn serve_rank( if executor.validate_submission(graph, &uploads, grammar)? != Some(fence) { return Err(invalid("rank submission sequence or capacity differs")); } - channel.send(READY, &identity(fence, graph))?; prepared = Some((fence, graph, grammar, owned)); - prepared_at = Some(Instant::now()); + if leases.should_drain_for_offload() { + ready_pending = true; + prepared_at = None; + } else { + channel.send(READY, &identity(fence, graph))?; + prepared_at = Some(Instant::now()); + } } COMMIT => { + if ready_pending { + return Err(invalid("rank commit arrived before READY")); + } let (fence, graph) = read_identity(&bytes)?; prepared_at = None; let (expected, expected_graph, grammar, owned) = prepared.take() @@ -645,29 +658,40 @@ 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))?; } + if ready_pending && !leases.should_drain_for_offload() { + if let Some((fence, graph, _, _)) = prepared.as_ref() { + channel.send(READY, &identity(*fence, *graph))?; + prepared_at = Some(Instant::now()); + } + ready_pending = false; + } if prepared_at.is_some_and(|time| time.elapsed() > TIMEOUT) { return Err(invalid("rank commit deadline expired after preparation")); } if started.front().is_some_and(|time| time.elapsed() > TIMEOUT) { return Err(invalid("rank graph completion deadline expired")); } - // A peer waiting only on its own running frame parks on it; a prepared frame waits + // A peer waiting only on its own running frame (or draining active frames + // before sending READY for an offload turn) parks on it; a ready frame waits // for rank zero's commit over the socket, which cannot end a park. The yield keeps // the old loop's cooperative handoff after either. if active { - if prepared.is_none() { executor.park(); } + if prepared.is_none() || ready_pending { executor.park(); } std::thread::yield_now(); } } @@ -678,8 +702,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 e5d193a7c..766ce261d 100644 --- a/helios/src/execution/ranks.rs +++ b/helios/src/execution/ranks.rs @@ -9,42 +9,21 @@ use super::{ ExecutionManifest, FrameCompletion, GraphExecutor, RankStream, TensorParallelExecutor, Upload, }; -use crate::{Result, Shutdown, cache::Fence}; +use crate::{Result, Shutdown, cache::Fence, offload::PeerGraphLeases}; pub enum RankPeers { Processes(Vec), Threads(Vec), } -pub(crate) enum RankExecutor { +enum RankExecutorInner { Threaded(Box), Local(Box), Parallel(Box), } -impl RankExecutor { - /// # Safety - /// Prepared graphs, contexts, buffers, and b12x IPC allocations must remain - /// retained until coordinated drain. Peer sockets identify ranks 1..world. - pub(crate) unsafe fn new( - manifest: ExecutionManifest, - peers: Option, - ) -> Result { - match peers { - Some(RankPeers::Threads(ranks)) => { - unsafe { super::threaded::ThreadedExecutor::new(manifest, ranks) } - .map(|executor| Self::Threaded(Box::new(executor))) - } - Some(RankPeers::Processes(peers)) => { - unsafe { TensorParallelExecutor::new(manifest, peers) } - .map(|executor| Self::Parallel(Box::new(executor))) - } - None => unsafe { GraphExecutor::new(manifest) } - .map(|executor| Self::Local(Box::new(executor))), - } - } - - pub(crate) fn submit( +impl RankExecutorInner { + fn submit( &mut self, graph: usize, uploads: &[Upload<'_>], @@ -57,7 +36,7 @@ impl RankExecutor { } } - pub(crate) fn poll(&mut self) -> Result> { + fn poll(&mut self) -> Result> { match self { Self::Local(executor) => executor.poll(), Self::Parallel(executor) => executor.poll(), @@ -65,8 +44,7 @@ impl RankExecutor { } } - /// Wait briefly for this rank's running frame; false when the caller should keep polling. - pub(crate) fn park(&self) -> bool { + fn park(&self) -> bool { match self { Self::Local(executor) => executor.park(), Self::Parallel(executor) => executor.park(), @@ -74,7 +52,7 @@ impl RankExecutor { } } - pub(crate) fn outstanding(&self) -> usize { + fn outstanding(&self) -> usize { match self { Self::Local(executor) => executor.outstanding(), Self::Parallel(executor) => executor.outstanding(), @@ -83,7 +61,7 @@ impl RankExecutor { } #[cfg(feature = "server")] - pub(crate) fn manifest(&self) -> &ExecutionManifest { + fn manifest(&self) -> &ExecutionManifest { match self { Self::Local(executor) => executor.manifest(), Self::Parallel(executor) => executor.manifest(), @@ -92,7 +70,7 @@ impl RankExecutor { } #[cfg(feature = "server")] - pub(crate) fn can_submit(&self, grammar: bool) -> bool { + fn can_submit(&self, grammar: bool) -> bool { match self { Self::Local(executor) => executor.can_submit(grammar), Self::Parallel(executor) => executor.can_submit(grammar), @@ -101,7 +79,7 @@ impl RankExecutor { } #[cfg(feature = "server")] - pub(crate) fn next_fence(&self) -> Result { + fn next_fence(&self) -> Result { match self { Self::Local(executor) => executor.next_fence(), Self::Parallel(executor) => executor.next_fence(), @@ -109,7 +87,7 @@ impl RankExecutor { } } - pub(crate) fn close(&mut self) -> Shutdown { + fn close(&mut self) -> Shutdown { match self { Self::Local(executor) => executor.close(), Self::Parallel(executor) => executor.close(), @@ -117,3 +95,133 @@ impl RankExecutor { } } } + +pub(crate) struct RankExecutor { + inner: RankExecutorInner, + leases: PeerGraphLeases, +} + +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 + /// retained until coordinated drain. Peer sockets identify ranks 1..world. + pub(crate) unsafe fn new( + manifest: ExecutionManifest, + peers: Option, + ) -> Result { + 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)) => { + unsafe { super::threaded::ThreadedExecutor::new(manifest, ranks) } + .map(|executor| RankExecutorInner::Threaded(Box::new(executor)))? + } + Some(RankPeers::Processes(peers)) => { + unsafe { TensorParallelExecutor::new(manifest, peers) } + .map(|executor| RankExecutorInner::Parallel(Box::new(executor)))? + } + None => unsafe { GraphExecutor::new(manifest) } + .map(|executor| RankExecutorInner::Local(Box::new(executor)))?, + }; + Ok(Self { + inner, + leases: PeerGraphLeases::new(copy_gate, peer_copy_graphs), + }) + } + + pub(crate) fn submit( + &mut self, + graph: usize, + uploads: &[Upload<'_>], + grammar: bool, + ) -> Result> { + 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 = self.inner.poll()?; + if let Some(ref frame) = completion { + 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 { + self.inner.park() + } + + pub(crate) fn outstanding(&self) -> usize { + self.inner.outstanding() + } + + #[cfg(feature = "server")] + pub(crate) fn manifest(&self) -> &ExecutionManifest { + self.inner.manifest() + } + + #[cfg(feature = "server")] + pub(crate) fn can_submit(&self, grammar: bool) -> bool { + !self.leases.should_drain_for_offload() && self.inner.can_submit(grammar) + } + + #[cfg(feature = "server")] + pub(crate) fn next_fence(&self) -> Result { + self.inner.next_fence() + } + + pub(crate) fn close(&mut self) -> Shutdown { + let shutdown = self.inner.close(); + self.leases.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]); + } + + #[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/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..1dbb63af6 --- /dev/null +++ b/helios/src/offload/copy_gate.rs @@ -0,0 +1,645 @@ +/* + * 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, 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 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, + changed: Condvar, +} + +impl CopyEngineGate { + pub fn new() -> Self { + Self::default() + } + + /// 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. + fn enter_peer_graph_timeout( + self: &Arc, + timeout: Duration, + ) -> Result { + let mut state = self.state.lock().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_active += 1; + Ok(PeerGraphGuard { + gate: Arc::clone(self), + }) + } + + /// Wait until no peer-copy graph is active and this batch is permitted to run, + /// returning the active offload batch lease. + pub fn enter_offload_batch(&self) -> OffloadBatchGuard<'_> { + let mut state = self.state.lock().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)) + }; + if must_wait(&state) { + 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); + } + 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 } + } +} + +/// 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 { + 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(); + } + } +} + +/// 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(); + } + } +} + +/// 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::*; + use std::sync::{ + Barrier, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + use std::thread; + + #[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().unwrap(); + // Pipelined second peer-copy graph must enter immediately without blocking. + 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. + 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().unwrap(); + 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 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().unwrap(); + 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().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)); + } + + #[test] + fn peer_deferred_ready_drains_active_frames_for_waiting_offload() { + // Exercises the serve_rank PREPARE -> deferred READY -> poll drain -> READY -> COMMIT + // protocol when rank 0 pipelines frames while the peer's local gate has waiting offload. + let gate = Arc::new(CopyEngineGate::new()); + let stop = Arc::new(AtomicBool::new(false)); + let offload_completed = Arc::new(AtomicUsize::new(0)); + + let gp = Arc::clone(&gate); + let sp = Arc::clone(&stop); + let peer = thread::spawn(move || { + let mut leases = PeerGraphLeases::new(Some(gp), vec![true]); + let mut in_flight: VecDeque = VecDeque::new(); + let mut prepared: Option = None; + let mut ready_pending = false; + let mut next_fence = 1u64; + while !sp.load(Ordering::Acquire) { + // Incoming PREPARE from rank 0 whenever peer has capacity (< 2 in-flight). + if prepared.is_none() && in_flight.len() < 2 { + let fence = Fence(next_fence); + next_fence += 1; + prepared = Some(fence); + if leases.should_drain_for_offload() { + ready_pending = true; + } else { + // Immediate READY -> COMMIT -> enter + track. + let fence = prepared.take().unwrap(); + let guard = leases.enter(0).unwrap(); + 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); + } + if ready_pending && !leases.should_drain_for_offload() { + ready_pending = false; + let fence = prepared.take().unwrap(); + let guard = leases.enter(0).unwrap(); + leases.track(Some(fence), guard); + in_flight.push_back(fence); + } + } + leases.clear(); + }); + + let g_off = Arc::clone(&gate); + let completed = Arc::clone(&offload_completed); + let worker = thread::spawn(move || { + for _ in 0..4 { + let _guard = g_off.enter_offload_batch(); + completed.fetch_add(1, Ordering::Relaxed); + thread::sleep(Duration::from_millis(1)); + } + }); + + let started = Instant::now(); + worker.join().unwrap(); + assert_eq!(offload_completed.load(Ordering::Acquire), 4); + assert!( + started.elapsed() < Duration::from_secs(2), + "peer offload starved under deferred-READY pipelining" + ); + stop.store(true, Ordering::Release); + peer.join().unwrap(); + } +} diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 6ff75244c..f6e2ff3c8 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, PeerGraphGuard, PeerGraphLeases}; + 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: Option>, } impl Binding { pub(crate) fn new( inner: flare_selene::offload::Binding, gpu_cubins: Vec>>, + copy_gate: Option>, ) -> Self { - Self { inner, gpu_cubins } + Self { + inner, + gpu_cubins, + copy_gate, + } + } + + pub(crate) fn copy_gate(&self) -> Option> { + self.copy_gate.clone() } pub fn inputs(&self) -> Option { @@ -101,10 +114,11 @@ pub fn prepare_with_inputs_budget( pub fn open( 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/pool/tests.rs b/helios/src/offload/pool/tests.rs index 91ebeaa02..b79dbdc5d 100644 --- a/helios/src/offload/pool/tests.rs +++ b/helios/src/offload/pool/tests.rs @@ -146,6 +146,7 @@ fn peer_registration_budget_fails_startup() { super::super::shard::join_peer( Some(&shared), Vec::new(), + None, &mut RankStream::Tcp(stream), 1, 2, diff --git a/helios/src/offload/shard.rs b/helios/src/offload/shard.rs index d32d7e886..8c1863b48 100644 --- a/helios/src/offload/shard.rs +++ b/helios/src/offload/shard.rs @@ -37,6 +37,7 @@ pub fn join_rank_zero(store: Option<&Shared>, peers: &mut [RankStream]) -> Resul pub fn join_peer( store: Option<&Shared>, gpu_cubins: Vec>>, + copy_gate: Option>, stream: &mut RankStream, rank: usize, world: usize, @@ -44,7 +45,7 @@ pub fn join_peer( 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/shard/tests.rs b/helios/src/offload/shard/tests.rs index ecdd0f9a0..643b6d01a 100644 --- a/helios/src/offload/shard/tests.rs +++ b/helios/src/offload/shard/tests.rs @@ -17,7 +17,7 @@ use super::*; join_rank_zero(None, &mut peers) }); assert!( - join_peer(None, Vec::new(), &mut peer_stream, 1, 2) + join_peer(None, Vec::new(), None, &mut peer_stream, 1, 2) .unwrap() .is_none() ); diff --git a/helios/src/offload/transfer.rs b/helios/src/offload/transfer.rs index 8c0d54409..2ad32340c 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 @@ -282,6 +285,92 @@ 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(); + } +} + +/// Sequences one or more batched Copy Engine transfers with optional `CopyEngineGate` +/// coordination and automatic stream drain on error. +/// +/// When `copy_gate` is `Some`, each [`Self::batch`] call acquires an offload lease and +/// synchronizes before releasing it (including on error). When `None`, batches enqueue +/// without intermediate syncs and [`Self::finish`] performs one sync at window end; +/// dropping before `finish` drains any already-enqueued ungated batches. +pub(super) struct GatedCopies<'a> { + stream: &'a Stream, + event: &'a Event, + copy_gate: Option<&'a super::CopyEngineGate>, + needs_drain: bool, +} + +impl<'a> GatedCopies<'a> { + pub(super) fn new( + stream: &'a Stream, + event: &'a Event, + copy_gate: Option<&'a super::CopyEngineGate>, + ) -> Self { + Self { + stream, + event, + copy_gate, + needs_drain: false, + } + } + + /// # 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 batch( + &mut self, + destinations: &[u64], + sources: &[u64], + sizes: &[usize], + ) -> Result<()> { + if let Some(gate) = self.copy_gate { + let _ce = gate.enter_offload_batch(); + let result = (|| -> Result<()> { + unsafe { + self.stream.copy_batch(destinations, sources, sizes)?; + } + self.stream.record(self.event)?; + self.event.synchronize()?; + Ok(()) + })(); + if result.is_err() { + drain_stream(self.stream, self.event); + } + result + } else { + self.needs_drain = true; + unsafe { + self.stream.copy_batch(destinations, sources, sizes)?; + } + Ok(()) + } + } + + pub(super) fn finish(mut self) -> Result<()> { + if self.copy_gate.is_none() { + self.stream.record(self.event)?; + self.event.synchronize()?; + } + self.needs_drain = false; + Ok(()) + } +} + +impl Drop for GatedCopies<'_> { + fn drop(&mut self) { + if self.needs_drain { + drain_stream(self.stream, self.event); + } + } +} + struct RankWorker { codec: Option, rank: usize, @@ -290,6 +379,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 +391,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 +401,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 +433,7 @@ impl RankWorker { geometry, layout, part: None, + copy_gate, stream, event, descriptors: Vec::with_capacity(window), @@ -363,6 +456,7 @@ impl RankWorker { &self.layout, &self.stream, &self.event, + self.copy_gate.as_deref(), job, window, ); @@ -374,6 +468,7 @@ impl RankWorker { job, &mut self.descriptors, )?; + let mut copies = GatedCopies::new(&self.stream, &self.event, self.copy_gate.as_deref()); let mut start = 0; let mut bytes = 0u64; while start < self.descriptors.len() { @@ -394,22 +489,18 @@ impl RankWorker { // 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)?; + copies.batch(&self.destinations, &self.sources, &self.sizes)?; } start = end; } - self.stream.record(&self.event)?; - self.event.synchronize()?; + copies.finish()?; Ok(bytes) } /// 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) { @@ -446,6 +537,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 +597,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 +611,7 @@ impl Transfers { decode, gpu_cubin, shared_gpu, + copy_gate, ) { Ok(mut worker) => { worker.part = part; @@ -1927,6 +2021,43 @@ mod tests { } transfers.close().unwrap(); drop(transfers); + + // Also exercise the gated transfer path: holding a PeerGraphGuard must defer + // offload batches until dropped, and the transfer must complete cleanly once released. + 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); + gated.close().unwrap(); + drop(gated); + drop(pool); let released = free(); for rank in 0..2 { @@ -2036,13 +2167,23 @@ mod tests { pub(crate) struct Copiers { gpu_cubins: Vec>>, shared_gpu: codec::SharedGpuCodecs, + copy_gate: Option>, } impl Copiers { + #[cfg(test)] 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 +2205,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..30f330655 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, @@ -261,13 +280,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) = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = + copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let start = Instant::now(); let res = guard.encode_pages_batches_with( page_plan, &batch_refs, @@ -276,10 +297,9 @@ 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; + (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) + }; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; } transferred += (page_bytes * job.pages.len()) as u64; @@ -292,9 +312,11 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let start = Instant::now(); - let stored_len = { + let (stored_len, elapsed) = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = + copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let start = Instant::now(); let res = guard.encode_from_device_with( page_plan, base_unit, @@ -308,10 +330,9 @@ impl RankCodec { slen }, ); - sync_on_err(stream, res) - } - .map_err(decode_error)?; - stats.transform_ns += start.elapsed().as_nanos() as u64; + (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) + }; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += page_bytes as u64; } @@ -325,9 +346,11 @@ impl RankCodec { stored_rank: rank as u32, ..Default::default() }; - let start = Instant::now(); - let stored_len = { + let (stored_len, elapsed) = { let mut guard = gpu.codec.lock().unwrap(); + let _ce = + copy_gate.map(super::super::CopyEngineGate::enter_offload_batch); + let start = Instant::now(); let res = guard.encode_from_device_with( &self.cpu.gpu_row, base_unit, @@ -341,10 +364,9 @@ impl RankCodec { slen }, ); - sync_on_err(stream, res) - } - .map_err(decode_error)?; - stats.transform_ns += start.elapsed().as_nanos() as u64; + (sync_on_err(stream, res).map_err(decode_error)?, start.elapsed()) + }; + stats.transform_ns += elapsed.as_nanos() as u64; stored += stored_len; transferred += n as u64; } @@ -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(); } @@ -634,9 +661,11 @@ impl RankCodec { j += 1; } if run_chunks.len() > 1 { - let start = Instant::now(); - let gpu_ran = { + let gpu_elapsed = { 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 start = Instant::now(); let packets: Vec<(&[&[u8]], u32, u32)> = run_chunks .iter() .zip(&run_units) @@ -650,13 +679,13 @@ impl RankCodec { event, ); sync_on_err(stream, res).map_err(decode_error)?; - true + Some(start.elapsed()) } else { - false + None } }; - if gpu_ran { - stats.transform_ns += start.elapsed().as_nanos() as u64; + if let Some(elapsed) = gpu_elapsed { + 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. @@ -680,6 +709,7 @@ impl RankCodec { &batch_spans, stream, event, + copy_gate, stats, )?; off += take; @@ -716,9 +746,10 @@ impl RankCodec { } else { &self.cpu.gpu_page }; - let start = Instant::now(); - let gpu_ran = { + let gpu_elapsed = { 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 start = Instant::now(); let res = guard.decode_to_device( plan, &chunks, @@ -729,13 +760,13 @@ impl RankCodec { event, ); sync_on_err(stream, res).map_err(decode_error)?; - true + Some(start.elapsed()) } else { - false + None } }; - if gpu_ran { - stats.transform_ns += start.elapsed().as_nanos() as u64; + if let Some(elapsed) = gpu_elapsed { + stats.transform_ns += elapsed.as_nanos() as u64; } else { route = DecodeRoute::GpuOnCpu; } @@ -757,6 +788,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::In, &[(0, spans)], self.cpu.staging_alias, @@ -926,26 +958,25 @@ 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, ) -> Result<()> { - struct Fence<'a>(&'a Stream); - impl Drop for Fence<'_> { - fn drop(&mut self) { - let _ = self.0.synchronize(); - } - } - let fence = Fence(stream); + let mut copies = GatedCopies::new(stream, event, copy_gate); 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 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)?; + copies.batch(dsts, srcs, lens)?; } dsts.clear(); srcs.clear(); @@ -976,15 +1007,13 @@ fn copy_spans_batch( } } flush(&mut dsts, &mut srcs, &mut lens, &mut queued)?; - stream.record(event)?; - event.synchronize()?; - std::mem::forget(fence); - Ok(()) + copies.finish() } #[cfg(all(test, target_os = "linux", feature = "runtime-core"))] mod tests { use super::*; + use std::time::Duration; use crate::runtime_core::driver::Driver; use flare_selene::{ PageId, StateSlotId, @@ -994,7 +1023,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 { @@ -1078,17 +1110,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), @@ -1100,6 +1133,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); @@ -1209,13 +1252,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/runtime_core/mod.rs b/helios/src/runtime_core/mod.rs index 1f2f01cf3..ebf8d270b 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), @@ -1332,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 b9561b074..98099facd 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: Option>, gpu_codec_cubins: Vec>>, cluster: Option, roce: Vec>, @@ -658,6 +659,7 @@ impl NativeModel { server_config, engram: Vec::new(), offload: Default::default(), + copy_gate: None, gpu_codec_cubins, cluster, roce, @@ -822,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); @@ -981,10 +988,17 @@ 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(), + 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], @@ -1024,10 +1038,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(), + self.copy_gate.clone(), + ) + }); if let Some((shared, delivery_rank)) = self.engram.get(index) { let events = shared .index @@ -1294,6 +1311,7 @@ mod tests { server_config: serde_json::Value::Null, engram: Vec::new(), offload: Default::default(), + copy_gate: None, 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..341f88d41 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(prepared, gpu_cubins, copy_gate) }) .transpose() { @@ -2275,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(); @@ -2353,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