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/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..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 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..596f381ad --- /dev/null +++ b/helios/src/offload/copy_gate.rs @@ -0,0 +1,583 @@ +/* + * 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. + pub 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 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()); + 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 }, waited) + } +} + +/// 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, waited) = gate.enter_offload_batch(); + assert_eq!(waited, Duration::ZERO); + 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, waited) = g3.enter_offload_batch(); + assert!(waited > Duration::ZERO); + 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)); + } +} diff --git a/helios/src/offload/mod.rs b/helios/src/offload/mod.rs index 6ff75244c..4110b8183 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,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/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 8c0d54409..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, @@ -290,6 +346,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 +358,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 +368,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 +400,7 @@ impl RankWorker { geometry, layout, part: None, + copy_gate, stream, event, descriptors: Vec::with_capacity(window), @@ -350,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 @@ -363,6 +424,7 @@ impl RankWorker { &self.layout, &self.stream, &self.event, + self.copy_gate.as_deref(), job, window, ); @@ -376,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 { @@ -393,34 +456,40 @@ impl RankWorker { // 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)?; - } + gate_wait += unsafe { + copy_batch_gated( + &self.stream, + &self.event, + self.copy_gate.as_deref(), + &self.destinations, + &self.sources, + &self.sizes, + )? + }; start = end; } - self.stream.record(&self.event)?; - self.event.synchronize()?; - Ok(bytes) + if self.copy_gate.is_none() { + self.stream.record(&self.event)?; + self.event.synchronize()?; + } + 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 { @@ -429,6 +498,7 @@ impl RankWorker { rank: self.rank, result, bytes, + gate_wait, }; if replies.send(reply).is_err() { break; @@ -446,6 +516,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 +576,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 +590,7 @@ impl Transfers { decode, gpu_cubin, shared_gpu, + copy_gate, ) { Ok(mut worker) => { worker.part = part; @@ -614,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(), }; @@ -703,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); } @@ -717,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), }); } } @@ -1209,6 +1287,7 @@ mod tests { direction: Direction::Out, remaining: 2, bytes: 0, + max_gate_wait: Duration::ZERO, error: None, started, }, @@ -1220,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(); @@ -1262,6 +1342,7 @@ mod tests { direction: Direction::In, remaining: 1, bytes: 0, + max_gate_wait: Duration::ZERO, error: None, started: Instant::now(), }, @@ -1342,6 +1423,7 @@ mod tests { rank: 0, result: Ok(()), bytes: 40, + gate_wait: Duration::ZERO, }) .unwrap(); transfers.poll(&mut replies); @@ -1927,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 { @@ -2036,13 +2161,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 +2199,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..b71dbdb8f 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 { + ) -> Result<(u64, Duration)> { 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,10 +224,11 @@ impl RankCodec { layout: &RankLayout, stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, job: &Job, window: &Window, stats: &mut DecodeStats, - ) -> Result { + ) -> Result<(u64, Duration)> { let capture = window .capture .as_ref() @@ -218,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); @@ -261,13 +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 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, @@ -276,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; @@ -292,9 +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 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, @@ -308,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; } @@ -325,9 +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 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, @@ -341,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; } @@ -367,9 +396,10 @@ impl RankCodec { ); batch_spans.push((slot_start, spans)); } - copy_spans_batch( + gate_wait += copy_spans_batch( stream, event, + copy_gate, Direction::Out, &batch_spans, self.cpu.staging_alias, @@ -437,9 +467,10 @@ 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, Direction::Out, &[(0, spans)], self.cpu.staging_alias, @@ -470,7 +501,7 @@ impl RankCodec { } } stats.stored_bytes = stored; - Ok(transferred) + Ok((transferred, gate_wait)) } fn decode_route(&self, u: &PackedUnit, representation: Representation) -> Result { @@ -509,8 +540,9 @@ impl RankCodec { batch_spans: &[(usize, Vec)], stream: &Stream, 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]; @@ -542,6 +574,7 @@ impl RankCodec { copy_spans_batch( stream, event, + copy_gate, Direction::In, batch_spans, self.cpu.staging_alias, @@ -556,14 +589,16 @@ impl RankCodec { layout: &RankLayout, stream: &Stream, event: &Event, + copy_gate: Option<&super::super::CopyEngineGate>, 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 @@ -597,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, 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(); } @@ -634,9 +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 = + 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) @@ -650,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. @@ -675,11 +715,12 @@ 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, event, + copy_gate, stats, )?; off += take; @@ -716,9 +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 waited = ce.as_ref().map_or(Duration::ZERO, |(_, w)| *w); + let start = Instant::now(); let res = guard.decode_to_device( plan, &chunks, @@ -729,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; } @@ -754,9 +798,10 @@ 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, Direction::In, &[(0, spans)], self.cpu.staging_alias, @@ -765,7 +810,7 @@ impl RankCodec { transferred += n as u64; } stats.stored_bytes = stored; - Ok(transferred) + Ok((transferred, gate_wait)) } } @@ -926,27 +971,30 @@ 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); +) -> 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 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<()> { + 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() { // SAFETY: Each span is inside this rank's cache and the pinned staging buffer stays mapped. - unsafe { - stream.copy_batch(dsts, srcs, lens)?; - } + gate_wait += unsafe { copy_batch_gated(stream, event, copy_gate, dsts, srcs, lens)? }; dsts.clear(); srcs.clear(); lens.clear(); @@ -954,6 +1002,7 @@ fn copy_spans_batch( } Ok(()) }; + 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 { @@ -976,10 +1025,12 @@ 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(()) + Ok(gate_wait) } #[cfg(all(test, target_os = "linux", feature = "runtime-core"))] @@ -994,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 { @@ -1078,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), @@ -1100,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); @@ -1209,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 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..10753af06 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, 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