diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index ea7208073..11c99a92f 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -209,6 +209,20 @@ output token: beta + f/x output delivery: g/z ``` +When active decoders are under-batched relative to the measured decode or +speculative catalog and queued prefills can enter decode (`max_new_tokens > 1`, +not `prompt_logprobs`), each queued prefiller's per-token prefill price receives +an additional coalescing continuation term pricing the multi-step `K -> K + m` +decode-batch throughput surplus over a bounded per-stream decode horizon +(`coalescing_horizon_tokens`, default `64.0`, clamped to each prefiller's +post-prefill output budget and the active decoders' minimum remaining budget), +amortized uniformly across the prefiller's uncached prompt tokens so total +credit sums to 1× regardless of chunking and chunk sizing stays smooth under +active decoder waiting age. The surplus is valued at intrinsic +`output_token_value`, avoiding amplification of low-rate fairness prices, and +vanishes when active decode capacity is already saturated or when a queued +prefiller cannot enter decode (`max_new_tokens == 1`). + Only decoding requests have a delivery coordinate or output-age cost. Normalized service prices follow the entropy-dual update in `scheduling-utility.md`. When a prefilling request's maximum feasible token rate changes between chunks (for @@ -403,16 +417,32 @@ Every selected complete speculative program enters the cost catalog with its actual B/D/W/P. A smaller captured producer is a distinct physical program; metadata must not relabel it as a deeper producer. -The first positive device observation sets the estimate. Further valid samples -while fresh use the median of the last nine replay observations, averaging the -middle pair when fewer than nine samples give an even count. An entry becomes stale after 30 seconds +The first positive device observation sets the estimate. For non-prefill +graphs, further valid samples while fresh use the median of the last nine +replay observations, averaging the middle pair when fewer than nine samples give +an even count. For pure prefill graphs (`PREFILL`, `TERMINAL_PREFILL`, and +`SCORED_PREFILL`), samples are stratified across six fill-ratio and KV-context +depth buckets (`u <= 0.5` vs `u > 0.5` crossed with `< 4096`, `4096..32768`, +and `>= 32768` starting tokens), each retaining a nine-sample rolling median. +Predictions fit a three-parameter nonnegative linear model +`theta_0 + theta_1 * u + theta_2 * u * (start_position / 4096)` by exact +relative-error-weighted nonnegative least squares over populated stratum +medians; when only a narrow fill regime (spread `< 0.15`) has been observed, +queries above `u_max` apply a bounded constant-throughput upward floor +`t_at_umax * min(u / u_max, 4)` to the base term (before adding `theta_2 * h`) +so partial fills cannot discount full-chunk cost estimates or lock out a large +capacity after TTL reset. When a smaller prefill capacity has no deep-context observations +(`start_position >= 4096`), it borrows the per-token KV-context slope +`theta_2 / peer_capacity` from the largest fresh strictly larger peer of the +same graph kind so deep prompts do not drift down onto stale shallow smaller +capacities. An entry becomes stale after 30 seconds without a valid observation. Its measured cost remains available for selection and service-rate normalization. The first valid observation of a stale entry -replaces its estimate directly; elapsed time alone never makes a measured graph -unknown. When multiple packed speculative shapes cover a `(batch, width)` lookup -for service-rate normalization or continuation pricing, Helios takes the minimum -positive measured duration across matching shapes and returns zero only when -every matching shape is unmeasured. +replaces its estimate directly (clearing all prefill strata); elapsed time alone +never makes a measured graph unknown. When multiple packed speculative shapes +cover a `(batch, width)` lookup for service-rate normalization or continuation +pricing, Helios takes the minimum positive measured duration across matching +shapes and returns zero only when every matching shape is unmeasured. The raw device observation is the maximum positive rank-local CUDA replay interval. When the prepared graphs expose frame-owned readiness timestamps, the cost sample @@ -559,13 +589,15 @@ resource availability, and feedback dependencies without rerunning selection. Cancellation stops further selection immediately; pages and state slots remain owned through their last submitted fence. -The transport has two frame slots. Only ordinary decode and complete speculative -generation may occupy both. Prefill, scored prefill, mixed execution, resume, -vision, and state operations drain the window. Unknown or stale costs, grammar, -copy-only proposals, host-fed pending tokens or committed cursors, history -inputs, and phase transitions also require completion feedback. Dependency -checks apply to the actual selected program. A finishing prefill exposes its -decoder and checkpoint operation only after completion. +The transport has two frame slots. Ordinary decode, complete speculative +generation, and consecutive nonterminal `PREFILL` chunks may occupy both when +they neither reach prompt completion or a conditioned-window limit nor arm or +land on a checkpoint cut. Terminal prefill (`TERMINAL_PREFILL`), scored prefill, +mixed execution, resume, vision, and state operations drain the window. Unknown +or stale costs, grammar, copy-only proposals, host-fed pending tokens or +committed cursors, history inputs, and phase transitions also require completion +feedback. Dependency checks apply to the actual selected program. A finishing +prefill exposes its decoder and checkpoint operation only after completion. Checkpoint retention uses the exact token endpoints supplied by the native frontend. Zero snapshot capacity disables all checkpoint cuts. Otherwise, the last @@ -649,6 +681,7 @@ Defaults specify these preferences: | `adaptation_ms` | 100 | Service-price adaptation time | | `estimate_ttl_ns` | 30,000,000,000 | Timing freshness interval | | `adaptive_verification_alpha` | 1 | Exponent on prefix-survival estimates in speculative selection scores | +| `coalescing_horizon_tokens` | 64 | Output-token horizon for decode-batch coalescing bonus on queued prefills | These weights express a throughput/cadence tradeoff. They are not graph timing measurements or latency guarantees. Setting fairness or age coefficients to zero diff --git a/helios/README.md b/helios/README.md index b10957132..9c5f7b782 100644 --- a/helios/README.md +++ b/helios/README.md @@ -478,8 +478,9 @@ delivery price initializes from its reference delivery interval. See `PolicyConfig` holds value coefficients, not time limits. Its defaults are an output-token value of 64 prompt-token units, token fairness 16, delivery fairness 4, decode-age price 0.1, terminal value 256, terminal-age price 1, a -100 ms service-price adaptation time, a 30-second timing freshness interval, and -adaptive-verification exponent 1. No millisecond cap applies to a frame or to +100 ms service-price adaptation time, a 30-second timing freshness interval, +adaptive-verification exponent 1, and a 64-token decode-batch coalescing +horizon. No millisecond cap applies to a frame or to the queued frames together. When the oldest queued graph runs past its expected finish, further queueing stops until its completion arrives. The coefficients are preferences, not latency bounds. Mixed prefill/generation graphs are diff --git a/helios/src/execution/manifest.rs b/helios/src/execution/manifest.rs index 6ada373e6..92e55e897 100644 --- a/helios/src/execution/manifest.rs +++ b/helios/src/execution/manifest.rs @@ -86,6 +86,10 @@ impl GraphKind { matches!(self, Self::Prefill | Self::TerminalPrefill | Self::ScoredPrefill) } + pub fn pipelines(self) -> bool { + matches!(self, Self::Decode | Self::Speculative | Self::Prefill) + } + pub fn samples(self) -> bool { matches!( self, diff --git a/helios/src/execution/parallel.rs b/helios/src/execution/parallel.rs index 807df36c2..f139d6964 100644 --- a/helios/src/execution/parallel.rs +++ b/helios/src/execution/parallel.rs @@ -259,8 +259,13 @@ impl TensorParallelExecutor { if self.shutdown.is_some() { return Err(invalid("tensor-parallel executor is closed")); } - let barrier = grammar || !matches!(self.local.manifest().graphs.get(graph).map(|g| g.kind), - Some(super::GraphKind::Decode | super::GraphKind::Speculative)); + let barrier = grammar + || !self + .local + .manifest() + .graphs + .get(graph) + .is_some_and(|g| g.kind.pipelines()); if !self.can_submit(barrier) { return Ok(None); } let Some(fence) = self.local.validate_submission(graph, uploads, grammar)? else { return Ok(None); diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index c3997a03e..61dbbe96b 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -870,10 +870,12 @@ impl ThreadedExecutor { return Err(error); } let barrier = grammar - || !matches!( - self.local.manifest().graphs.get(graph).map(|g| g.kind), - Some(super::GraphKind::Decode | super::GraphKind::Speculative) - ); + || !self + .local + .manifest() + .graphs + .get(graph) + .is_some_and(|g| g.kind.pipelines()); if !self.can_submit(barrier) { return Ok(None); } diff --git a/helios/src/execution/threaded/protocol.rs b/helios/src/execution/threaded/protocol.rs index a2fae59d1..98068745c 100644 --- a/helios/src/execution/threaded/protocol.rs +++ b/helios/src/execution/threaded/protocol.rs @@ -7,7 +7,6 @@ use std::{fmt::Write as _, time::Duration}; use super::{ExecutionManifest, Fence, FrameCompletion, Result, VecDeque, invalid}; -use crate::execution::GraphKind; pub(crate) trait PendingFrame { fn fence(&self) -> Fence; @@ -29,11 +28,7 @@ pub(crate) fn can_submit_pending( && pending.back().is_none_or(|frame| frame.committed()) && (!barrier || pending.is_empty()) && !pending.iter().any(|frame| { - frame.grammar() - || !matches!( - manifest.graphs[frame.graph()].kind, - GraphKind::Decode | GraphKind::Speculative - ) + frame.grammar() || !manifest.graphs[frame.graph()].kind.pipelines() }) } diff --git a/helios/src/execution/threaded/protocol_tests.rs b/helios/src/execution/threaded/protocol_tests.rs index 1d09f7026..c35b81ba9 100644 --- a/helios/src/execution/threaded/protocol_tests.rs +++ b/helios/src/execution/threaded/protocol_tests.rs @@ -360,6 +360,11 @@ fn rank_coordinator_matches_model_pending_window() { assert!(can_submit_pending(&pending, false, &manifest)); assert!(!can_submit_pending(&pending, true, &manifest)); manifest.graphs[0].kind = GraphKind::Prefill; + assert!(can_submit_pending(&pending, false, &manifest)); + pending[0].grammar = true; + assert!(!can_submit_pending(&pending, false, &manifest)); + pending[0].grammar = false; + manifest.graphs[0].kind = GraphKind::TerminalPrefill; assert!(!can_submit_pending(&pending, false, &manifest)); manifest.graphs[0].kind = GraphKind::Speculative; assert!(can_submit_pending(&pending, false, &manifest)); diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index 1f39e36eb..7b21e4e3a 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -964,8 +964,7 @@ impl GraphExecutor { ) -> Result> { let fence = self.next_fence()?; validate_uploads(&self.manifest, graph, uploads, &mut self.resolved_uploads)?; - if !self.can_submit(grammar || !matches!(self.manifest.graphs[graph].kind, - GraphKind::Decode | GraphKind::Speculative)) { + if !self.can_submit(grammar || !self.manifest.graphs[graph].kind.pipelines()) { return Ok(None); } if crate::engram::consumes(self.manifest.graphs[graph].kind) { @@ -1017,8 +1016,7 @@ impl GraphExecutor { self.manifest.graphs.get(graph_index).ok_or_else(|| { Error::execution(ExecutionError::State, "graph index out of range") })?; - let grammar_constrained = grammar_constrained - || !matches!(graph.kind, GraphKind::Decode | GraphKind::Speculative); + let grammar_constrained = grammar_constrained || !graph.kind.pipelines(); let mut resolved = validate_uploads( &self.manifest, graph_index, diff --git a/helios/src/model.rs b/helios/src/model.rs index 21465c6bd..601a298fb 100644 --- a/helios/src/model.rs +++ b/helios/src/model.rs @@ -349,7 +349,7 @@ pub fn scheduler_capabilities_with_manifest( let semantics = config.contract.graph(&graph.name)?; let inputs: Vec<_> = semantics.inputs.iter().filter(|binding| matches!(binding.source, ValueSource::PendingToken | ValueSource::PromptAndPendingToken) - || matches!(graph.kind, GraphKind::Decode | GraphKind::Speculative | GraphKind::Mixed) + || matches!(graph.kind, GraphKind::Prefill | GraphKind::Decode | GraphKind::Speculative | GraphKind::Mixed) && matches!(binding.source, ValueSource::ConsumedTokens | ValueSource::SnapshotConsumedTokens)) .map(|binding| binding.buffer.clone()).collect(); if !inputs.is_empty() { diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 00e0457c2..e1d274769 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -851,12 +851,27 @@ impl RequestScheduler { .unwrap_or(0) } + pub(super) fn prefill_cursor(request: &LiveRequest) -> usize { + request.scheduled_consumed.max(request.consumed_tokens) as usize + } + pub(super) fn resolve_prefill_kind( &self, request: &LiveRequest, capacity: usize, work: usize, cut: Option, + ) -> GraphKind { + self.resolve_prefill_kind_from(request, Self::prefill_cursor(request), capacity, work, cut) + } + + pub(super) fn resolve_prefill_kind_from( + &self, + request: &LiveRequest, + start: usize, + capacity: usize, + work: usize, + cut: Option, ) -> GraphKind { if request.prompt_logprobs { return GraphKind::ScoredPrefill; @@ -865,7 +880,7 @@ impl RequestScheduler { .unwrap_or(request.prompt_tokens) .min(request.prefill_limit()) .min(request.prompt_tokens); - let end = (request.consumed_tokens as usize).saturating_add(work); + let end = start.saturating_add(work); let window = self.terminal_prefill_window(); let needs_terminal = end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window); @@ -887,6 +902,15 @@ impl RequestScheduler { &self, request: &LiveRequest, cut: Option, + ) -> bool { + self.prefill_requires_terminal_completion_from(request, Self::prefill_cursor(request), cut) + } + + pub(super) fn prefill_requires_terminal_completion_from( + &self, + request: &LiveRequest, + start: usize, + cut: Option, ) -> bool { if request.prompt_logprobs || self.terminal_prefill_catalog.is_empty() { return false; @@ -895,7 +919,7 @@ impl RequestScheduler { .unwrap_or(request.prompt_tokens) .min(request.prefill_limit()) .min(request.prompt_tokens); - let remaining = next_stop.saturating_sub(request.consumed_tokens as usize); + let remaining = next_stop.saturating_sub(start); if remaining == 0 { return false; } @@ -903,12 +927,12 @@ impl RequestScheduler { let Some(&max_terminal) = self.terminal_prefill_catalog.last() else { return false; }; - return self.prefill_work_through(request, max_terminal, cut) >= remaining; + return self.prefill_work_from(request, start, max_terminal, cut) >= remaining; } let Some(&max_capacity) = self.prefill_catalog.last() else { return false; }; - if self.prefill_work_through(request, max_capacity, cut) < remaining { + if self.prefill_work_from(request, start, max_capacity, cut) < remaining { return false; } let Some(&smallest_fit) = self.prefill_catalog.iter().find(|&&cap| cap >= remaining) else { @@ -1082,10 +1106,35 @@ impl RequestScheduler { Ok(()) } + fn prefill_step_requires_feedback(&self, plan: &ScheduledPlan) -> bool { + if plan + .checkpoint_plans + .iter() + .any(checkpoints::CapturePlan::requires_feedback) + { + return true; + } + plan.lanes.iter().any(|lane| { + let Ok(request) = self.request(lane.request) else { + return true; + }; + let end = lane.start_position.saturating_add(lane.tokens as u64); + request.prompt_logprobs + || request.checkpoint_capture.is_some() + || end >= request.prompt_tokens as u64 + || end >= request.prefill_limit() as u64 + }) + } + pub fn plan_requires_feedback(&self, plan: &ScheduledPlan) -> bool { let geometry = (plan.kind, plan.batch_capacity, plan.draft_tokens, plan.token_capacity, plan.packed_token_capacity, plan.prefill_capacity()); - plan.requires_feedback || !matches!(plan.kind, GraphKind::Decode | GraphKind::Speculative) + let kind_requires_feedback = match plan.kind { + GraphKind::Prefill => self.prefill_step_requires_feedback(plan), + kind => !kind.pipelines(), + }; + plan.requires_feedback + || kind_requires_feedback || self.capabilities.completion_inputs.iter().any(|(key, inputs)| *key == geometry && !inputs.is_empty()) || plan.lanes.iter().any(|lane| self.request(lane.request).is_ok_and(|request| request.grammar_constrained)) diff --git a/helios/src/scheduler/checkpoints.rs b/helios/src/scheduler/checkpoints.rs index 400a31459..ddaa34d81 100644 --- a/helios/src/scheduler/checkpoints.rs +++ b/helios/src/scheduler/checkpoints.rs @@ -83,6 +83,12 @@ pub(super) struct CapturePlan { budget: bool, } +impl CapturePlan { + pub(super) fn requires_feedback(&self) -> bool { + self.cut.is_some() || self.reserve_guard + } +} + fn allowance(work: u64, fraction: f64) -> u64 { ((work as f64) * fraction).floor().min(u64::MAX as f64) as u64 } @@ -91,8 +97,8 @@ fn allowance(work: u64, fraction: f64) -> u64 { struct PrefillCatalogCost { capacity: usize, has_terminal: bool, - non_terminal_ns: Option, - terminal_ns: Option, + non_terminal: Option, + terminal: Option, } /// Whether `work` tokens for `nanos` cost less per token than `best`; a tie prefers more work. @@ -172,33 +178,29 @@ impl RequestScheduler { .map(|&capacity| { // Prefill dispatch retains measured costs after expiry; aging alone // does not make its predicted work unknown. - let prefill_ns = self - .costs - .duration(request.prefill_kind(), 1, capacity) - .filter(|&nanos| nanos != 0); + let prefill = self.costs.prefill_predictor(request.prefill_kind(), capacity); if !has_terminal_catalog { return PrefillCatalogCost { capacity, has_terminal: false, - non_terminal_ns: prefill_ns, - terminal_ns: prefill_ns, + non_terminal: prefill, + terminal: prefill, }; } let has_terminal = self.terminal_prefill_catalog.binary_search(&capacity).is_ok(); - let terminal_ns = if has_terminal { + let terminal = if has_terminal { self.costs - .duration(GraphKind::TerminalPrefill, 1, capacity) - .filter(|&nanos| nanos != 0) - .or(prefill_ns) + .prefill_predictor(GraphKind::TerminalPrefill, capacity) + .or(prefill) } else { - prefill_ns + prefill }; - let non_terminal_ns = prefill_ns.or(terminal_ns); + let non_terminal = prefill.or(terminal); PrefillCatalogCost { capacity, has_terminal, - non_terminal_ns, - terminal_ns, + non_terminal, + terminal, } }) .collect() @@ -213,13 +215,14 @@ impl RequestScheduler { ) -> Option { let has_terminal_catalog = catalog.iter().any(|entry| entry.has_terminal); let uniform = terminal_window == 0 && !has_terminal_catalog; - // With every cost known, the capacity cheapest per token is chosen whole at each - // position whose chunk ends by the next window end, span start or interval end: a - // smaller one fits unchanged, and a larger one only does worse when cut short. - let stride = catalog + // With every non-terminal cost known and full-chunk affine in `start_position`, + // a full chunk of the per-token cheapest capacity dominates every partial fill + // (since `theta_0 >= 0`), so consecutive full chunks before the next window end, + // span start, terminal window, or capacity crossover collapse to O(1) arithmetic. + let constant_stride = catalog .iter() .try_fold(None, |best, entry| { - let nanos = entry.non_terminal_ns?; + let nanos = entry.non_terminal?.full_chunk_affine().exact_constant_ns?; Some(if cheaper(entry.capacity, nanos, best) { Some((entry.capacity, nanos)) } else { @@ -227,6 +230,9 @@ impl RequestScheduler { }) }) .flatten(); + let all_affine = constant_stride.is_none() + && !catalog.is_empty() + && catalog.iter().all(|entry| entry.non_terminal.is_some()); let mut total = 0u64; while start < end { let limit = request @@ -238,7 +244,7 @@ impl RequestScheduler { .min() .unwrap_or(end) .min(end); - if let Some((capacity, nanos)) = stride + if (constant_stride.is_some() || all_affine) && !request .prefill_spans .iter() @@ -255,13 +261,73 @@ impl RequestScheduler { // SWA tail protection window so those chunks price with `terminal_ns`. bound = bound.min(end.saturating_sub(terminal_window + 1)); } - let chunks = bound.saturating_sub(start) / capacity; - if chunks > 0 { - #[cfg(test)] - tests::STRIDE_RUNS.set(tests::STRIDE_RUNS.get() + 1); - total = total.checked_add(nanos.checked_mul(chunks as u64)?)?; - start += chunks * capacity; - continue; + if let Some((capacity, nanos)) = constant_stride { + let chunks = bound.saturating_sub(start) / capacity; + if chunks > 0 { + #[cfg(test)] + tests::STRIDE_RUNS.set(tests::STRIDE_RUNS.get() + 1); + total = total.checked_add(nanos.checked_mul(chunks as u64)?)?; + start += chunks * capacity; + continue; + } + } else if all_affine && start < bound { + let mut best: Option<(usize, u64, cost::FullChunkAffine)> = None; + for entry in catalog { + let pred = entry.non_terminal.unwrap(); + let aff = pred.full_chunk_affine(); + let nanos = pred.predict(entry.capacity, start as u64); + if cheaper(entry.capacity, nanos, best.map(|(w, n, _)| (w, n))) { + best = Some((entry.capacity, nanos, aff)); + } + } + if let Some((win_cap, _, win_aff)) = best { + let win_inv_cap = 1.0 / win_cap as f64; + let win_intercept = win_aff.intercept_ns * win_inv_cap; + let win_slope = win_aff.slope_per_pos_ns * win_inv_cap; + let mut limit_pos = bound; + for entry in catalog { + if entry.capacity == win_cap { + continue; + } + let other = entry.non_terminal.unwrap().full_chunk_affine(); + let other_inv_cap = 1.0 / entry.capacity as f64; + let other_slope = other.slope_per_pos_ns * other_inv_cap; + if other_slope < win_slope { + let diff_intercept = + other.intercept_ns * other_inv_cap - win_intercept; + let diff_slope = win_slope - other_slope; + if diff_intercept <= 0.0 { + limit_pos = start; + break; + } + let cross = (diff_intercept / diff_slope).floor(); + if cross < limit_pos as f64 { + limit_pos = cross.max(start as f64) as usize; + } + } + } + let chunks = limit_pos.saturating_sub(start) / win_cap; + if chunks > 0 { + #[cfg(test)] + tests::STRIDE_RUNS.set(tests::STRIDE_RUNS.get() + 1); + let step_ns = if let Some(nanos) = win_aff.exact_constant_ns { + nanos.checked_mul(chunks as u64)? + } else { + let m = chunks as f64; + let sum = m * win_aff.intercept_ns + + win_aff.slope_per_pos_ns + * (m * start as f64 + + win_cap as f64 * (m * (m - 1.0) * 0.5)); + if !sum.is_finite() || sum >= u64::MAX as f64 { + return None; + } + sum.floor().max(m) as u64 + }; + total = total.checked_add(step_ns)?; + start += chunks * win_cap; + continue; + } + } } } let remaining = end.saturating_sub(start); @@ -311,20 +377,21 @@ impl RequestScheduler { } let adds_work = work > max_work; max_work = max_work.max(work); - let nanos = if is_terminal { - entry.terminal_ns + let predictor = if is_terminal { + entry.terminal } else { - entry.non_terminal_ns + entry.non_terminal }; // Only an unmeasured pricing capacity that adds work makes the price // unknown: the pricing capacity covers at least as much work, so the // skip loses no capacity that could cover more. - let Some(nanos) = nanos else { + let Some(predictor) = predictor else { if !adds_work || Some(entry.capacity) != pricing_capacity { continue; } return None; }; + let nanos = predictor.predict(work, start as u64); if cheaper(work, nanos, best) { best = Some((work, nanos)); } @@ -483,7 +550,7 @@ impl RequestScheduler { return (accounting, false, false); } let raw_anchor = request.checkpoint_anchor(); - let start = request.consumed_tokens as usize; + let start = Self::prefill_cursor(request); let (baseline_start, baseline_end) = *accounting.baseline_interval.get_or_insert(( request.admission_reused_tokens as usize, request.prompt_tokens, @@ -677,19 +744,21 @@ impl RequestScheduler { pub(super) fn estimated_checkpoint_cut(&self, request: &LiveRequest) -> Option { let (accounting, _, _) = self.checkpoint_selection_cached(request, false); + let start = Self::prefill_cursor(request); accounting .cuts .iter() - .find(|cut| cut.endpoint > request.consumed_tokens as usize) + .find(|cut| cut.endpoint > start) .map(|cut| cut.endpoint) } pub(super) fn checkpoint_cut(&self, request: &LiveRequest) -> Option { let (accounting, _, _) = self.checkpoint_selection(request); + let start = Self::prefill_cursor(request); accounting .cuts .iter() - .find(|cut| cut.endpoint > request.consumed_tokens as usize) + .find(|cut| cut.endpoint > start) .map(|cut| cut.endpoint) } @@ -1338,6 +1407,130 @@ mod tests { assert_eq!(SELECTIONS.get(), 1); } + #[test] + fn non_constant_prefill_cost_model_preserves_stride_fast_path_on_long_agentic_prompts() { + let template = super::super::tests::scheduler(4, 128, 16); + let mut scheduler = RequestScheduler::new( + [11; 32], + SchedulerLimits { + max_sequence_tokens: 262_144, + prefill_chunk_size: 8192, + pages: 16_384, + ..template.limits + }, + template.capabilities.clone(), + ) + .unwrap(); + let mut graphs = super::super::tests::duration_graphs(4); + graphs.extend(extra_graphs()); + scheduler.measured_graph_durations(&graphs).unwrap(); + // Seed non-constant fill + KV-context predictors via real prefill observations. + let observe = |scheduler: &mut RequestScheduler, cap: usize, work: usize, pos: u64, ns: u64| { + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(ns); + scheduler.observe_execution( + &ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Prefill, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position: pos, + tokens: work, + }], + requires_feedback: true, + }, + crate::execution::ExecutionTiming { + gpu_ns, + wall_ns: ns, + queued: false, + readiness: None, + }, + ); + }; + let caps: Vec = scheduler.prefill_catalog.clone(); + for cap in caps { + // Non-zero fixed overhead + fill slope + KV-context slope. + let full_0 = 2_000_000 + cap as u64 * 25_000; + let quarter_0 = 2_000_000 + (cap / 4).max(1) as u64 * 25_000; + let full_64k = full_0 + cap as u64 * 8_000; + observe(&mut scheduler, cap, cap, 0, full_0); + observe(&mut scheduler, cap, (cap / 4).max(1), 0, quarter_0); + observe(&mut scheduler, cap, cap, 65_536, full_64k); + assert!( + !scheduler + .costs + .prefill_predictor(GraphKind::Prefill, cap) + .unwrap() + .is_constant(), + "expected non-constant predictor for cap={cap}" + ); + } + // Also measure Snapshot so checkpoint selection runs the full boundary loop. + let mut snap_gpu = [None; 16]; + snap_gpu[0] = Some(1_000_000); + scheduler.observe_execution( + &ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Snapshot, + batch_capacity: 1, + token_capacity: 1, + packed_token_capacity: 0, + mixed: None, + lanes: vec![], + requires_feedback: true, + }, + crate::execution::ExecutionTiming { + gpu_ns: snap_gpu, + wall_ns: 1_000_000, + queued: false, + readiness: None, + }, + ); + scheduler + .configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.05, + ..Default::default() + }) + .unwrap(); + let mut handles = Vec::new(); + for _ in 0..4 { + let mut spec = super::super::tests::spec(150_000, 1); + spec.message_boundaries = (150..150_000).step_by(150).collect(); + handles.push(scheduler.admit(spec).unwrap()); + } + let catalog_len = scheduler.prefill_catalog.len(); + super::super::cost::ENTRY_LOOKUPS.set(0); + STRIDE_RUNS.set(0); + for &handle in &handles { + let request = scheduler.request(handle).unwrap(); + std::hint::black_box(scheduler.checkpoint_cut(request)); + } + let lookups = super::super::cost::ENTRY_LOOKUPS.get(); + let stride_runs = STRIDE_RUNS.get(); + assert!(lookups <= handles.len() * (catalog_len + 4), "{lookups} cost lookups"); + assert!( + stride_runs >= handles.len() * 100, + "expected affine O(1) stride fast path to engage across 999 boundaries, got {stride_runs}" + ); + + // Verify exact chunk-aligned anchor split remains zero-cost under positive context slope. + let request = scheduler.request(handles[0]).unwrap(); + let catalog = scheduler.prefill_catalog_costs(request); + let max_cap = *scheduler.prefill_catalog.last().unwrap(); + assert!(RequestScheduler::anchor_split_is_zero_cost( + request, + &catalog, + 0, + 0, + max_cap * 10, + max_cap * 4, + )); + } + #[test] fn prefill_capacity_matches_submitted_work_without_snapshot_storage() { for (prompt_tokens, capacity, refresh) in [ diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 9060e84c3..023713477 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -63,32 +63,446 @@ pub(super) struct PackedRoundShape { pub nanos: u64, } +const PREFILL_FILL_STRATA: usize = 2; +const PREFILL_CTX_STRATA: usize = 3; +const PREFILL_STRATA: usize = PREFILL_FILL_STRATA * PREFILL_CTX_STRATA; +const PREFILL_CTX_SCALE: f64 = 4096.0; +const PREFILL_MAX_UPWARD_EXTRAPOLATION: f64 = 4.0; + +#[derive(Clone, Copy, Debug)] +pub(super) struct FullChunkAffine { + pub exact_constant_ns: Option, + pub intercept_ns: f64, + pub slope_per_pos_ns: f64, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct PrefillPredictor { + capacity: usize, + constant_nanos: Option, + theta: [f64; 3], + u_min: f64, + u_max: f64, + t_at_umax: f64, + has_deep_context: bool, +} + +impl PrefillPredictor { + pub fn constant(capacity: usize, nanos: u64) -> Self { + let nanos_f = nanos as f64; + Self { + capacity: capacity.max(1), + constant_nanos: Some(nanos), + theta: [nanos_f, 0.0, 0.0], + u_min: 1.0, + u_max: 1.0, + t_at_umax: nanos_f, + has_deep_context: false, + } + } + + #[cfg(test)] + pub fn is_constant(&self) -> bool { + self.constant_nanos.is_some() + } + + #[cfg(test)] + pub fn constant_ns(&self) -> Option { + self.constant_nanos + } + + pub fn has_deep_context(&self) -> bool { + self.has_deep_context + } + + pub fn context_slope_per_token(self) -> Option { + (self.has_deep_context && self.theta[2] > 0.0 && self.theta[2].is_finite()) + .then_some(self.theta[2] / self.capacity.max(1) as f64) + } + + pub fn with_borrowed_context_slope(mut self, theta2: f64) -> Self { + if !self.has_deep_context && theta2 > 0.0 && theta2.is_finite() { + self.theta[2] = theta2; + self.constant_nanos = None; + } + self + } + + fn upward_extrapolation_floor(&self, u: f64) -> f64 { + if (self.u_max - self.u_min) < 0.15 && u > self.u_max && self.u_max > 0.0 { + self.t_at_umax * (u / self.u_max).min(PREFILL_MAX_UPWARD_EXTRAPOLATION) + } else { + 0.0 + } + } + + /// Affine representation of full-chunk (`work == capacity`) duration as a function of + /// `start_position`: `intercept_ns + slope_per_pos_ns * start_position`. + pub fn full_chunk_affine(&self) -> FullChunkAffine { + if let Some(nanos) = self.constant_nanos { + return FullChunkAffine { + exact_constant_ns: Some(nanos), + intercept_ns: nanos as f64, + slope_per_pos_ns: 0.0, + }; + } + let intercept = (self.theta[0] + self.theta[1]).max(self.upward_extrapolation_floor(1.0)); + let slope = self.theta[2] / PREFILL_CTX_SCALE; + if slope == 0.0 { + let nanos = self.predict(self.capacity, 0); + FullChunkAffine { + exact_constant_ns: Some(nanos), + intercept_ns: nanos as f64, + slope_per_pos_ns: 0.0, + } + } else { + FullChunkAffine { + exact_constant_ns: None, + intercept_ns: intercept, + slope_per_pos_ns: slope, + } + } + } + + pub fn predict(&self, work: usize, start_position: u64) -> u64 { + if let Some(nanos) = self.constant_nanos { + return nanos; + } + let cap = self.capacity.max(1); + let u = work.clamp(1, cap) as f64 / cap as f64; + let h = u * (start_position as f64 / PREFILL_CTX_SCALE); + // Bounded constant-throughput upward guard when only a narrow fill regime has been + // observed (`u_max - u_min < 0.15`), preventing partial fills from discounting + // full-chunk cost while avoiding uncapped post-TTL lockout on large capacities. + let base = (self.theta[0] + self.theta[1] * u).max(self.upward_extrapolation_floor(u)); + let pred = base + self.theta[2] * h; + if !pred.is_finite() || pred <= 1.0 { + 1 + } else if pred >= u64::MAX as f64 { + u64::MAX + } else { + pred.round() as u64 + } + } +} + +#[derive(Clone, Copy)] +struct Ring9 { + samples: [T; 9], + len: usize, + next: usize, +} + +impl Default for Ring9 { + fn default() -> Self { + Self { + samples: [T::default(); 9], + len: 0, + next: 0, + } + } +} + +impl Ring9 { + fn push(&mut self, value: T) { + self.samples[self.next] = value; + self.next = (self.next + 1) % self.samples.len(); + self.len = (self.len + 1).min(self.samples.len()); + } + + fn reset(&mut self) { + *self = Self::default(); + } + + fn sorted_by(&self, mut cmp: impl FnMut(&T, &T) -> std::cmp::Ordering) -> ([T; 9], usize) { + let mut ordered = self.samples; + ordered[..self.len].sort_unstable_by(&mut cmp); + (ordered, self.len) + } +} + +#[derive(Clone, Copy, Default)] +struct PrefillSample { + nanos: u64, + u: f64, + h: f64, +} + +#[derive(Clone, Copy, Default)] +struct PrefillBucket { + ring: Ring9, +} + +impl PrefillBucket { + fn observe(&mut self, sample: PrefillSample) { + self.ring.push(sample); + } + + fn median(&self) -> Option<(f64, f64, f64)> { + let (ordered, len) = self.ring.sorted_by(|a, b| { + a.nanos + .cmp(&b.nanos) + .then_with(|| a.u.total_cmp(&b.u)) + .then_with(|| a.h.total_cmp(&b.h)) + }); + if len == 0 { + return None; + } + let mid = len / 2; + if len % 2 == 0 { + let lo = ordered[mid - 1]; + let hi = ordered[mid]; + let nanos = ((u128::from(lo.nanos) + u128::from(hi.nanos) + 1) / 2) as f64; + Some((nanos, 0.5 * (lo.u + hi.u), 0.5 * (lo.h + hi.h))) + } else { + let s = ordered[mid]; + Some((s.nanos as f64, s.u, s.h)) + } + } +} + +#[derive(Clone)] +struct PrefillCostModel { + capacity: usize, + strata: [PrefillBucket; PREFILL_STRATA], + predictor: Option, +} + +impl PrefillCostModel { + fn new(capacity: usize) -> Self { + Self { + capacity: capacity.max(1), + strata: [PrefillBucket::default(); PREFILL_STRATA], + predictor: None, + } + } + + #[cfg(test)] + fn reset_with_full(&mut self, nanos: u64) { + self.strata = [PrefillBucket::default(); PREFILL_STRATA]; + if nanos == 0 { + self.predictor = None; + return; + } + self.strata[3].observe(PrefillSample { nanos, u: 1.0, h: 0.0 }); + self.predictor = Some(PrefillPredictor::constant(self.capacity, nanos)); + } + + /// Records a prefill replay sample and returns the fitted full-fill, zero-context + /// prediction (`predict(capacity, 0)`), which `Estimate::nanos` and telemetry + /// (`SubmittedTiming.retained_ns`) retain as the graph's baseline duration. + fn observe(&mut self, nanos: u64, work: usize, start_position: u64, fresh: bool) -> u64 { + if !fresh { + self.strata = [PrefillBucket::default(); PREFILL_STRATA]; + } + let cap = self.capacity.max(1); + let u = work.clamp(1, cap) as f64 / cap as f64; + let h = u * (start_position as f64 / PREFILL_CTX_SCALE); + let fill_bin = usize::from(u > 0.5); + let ctx_bin = if start_position < 4096 { + 0 + } else if start_position < 32768 { + 1 + } else { + 2 + }; + self.strata[fill_bin * PREFILL_CTX_STRATA + ctx_bin] + .observe(PrefillSample { nanos, u, h }); + let predictor = self.fit(); + self.predictor = Some(predictor); + predictor.predict(self.capacity, 0) + } + + fn fit(&self) -> PrefillPredictor { + let mut pts = [(0.0f64, 0.0f64, 0.0f64); PREFILL_STRATA]; + let mut n = 0usize; + let mut u_min = f64::INFINITY; + let mut u_max = f64::NEG_INFINITY; + let mut t_at_umax = 0.0f64; + let mut h_at_umax = f64::INFINITY; + let mut has_deep_context = false; + for (stratum_idx, bucket) in self.strata.iter().enumerate() { + let Some((t, u, h)) = bucket.median() else { + continue; + }; + if t <= 0.0 || !t.is_finite() { + continue; + } + if stratum_idx % PREFILL_CTX_STRATA > 0 { + has_deep_context = true; + } + pts[n] = (t, u, h); + n += 1; + u_min = u_min.min(u); + if u > u_max + 1e-12 || ((u - u_max).abs() <= 1e-12 && h < h_at_umax) { + u_max = u; + t_at_umax = t; + h_at_umax = h; + } + } + if n == 0 { + return PrefillPredictor::constant(self.capacity, 1); + } + let pts = &pts[..n]; + // Normal equations for relative-error weighted NNLS: + // minimize sum_s ((theta_0 + theta_1*u_s + theta_2*h_s - t_s) / t_s)^2, theta >= 0. + let mut ata = [[0.0f64; 3]; 3]; + let mut atb = [0.0f64; 3]; + for &(t, u, h) in pts { + let inv = 1.0 / t; + let row = [inv, u * inv, h * inv]; + for i in 0..3 { + atb[i] += row[i]; + for j in 0..3 { + ata[i][j] += row[i] * row[j]; + } + } + } + let mut best_theta = [t_at_umax, 0.0, 0.0]; + let mut best_sse = f64::INFINITY; + let mut best_params = usize::MAX; + for mask in 1u8..8u8 { + let mut idx = [0usize; 3]; + let mut k = 0usize; + for j in 0..3 { + if mask & (1 << j) != 0 { + idx[k] = j; + k += 1; + } + } + let Some(sol) = solve_small_spd(&ata, &atb, &idx[..k]) else { + continue; + }; + if sol[..k].iter().any(|&v| !v.is_finite() || v < -1e-9) { + continue; + } + let mut theta = [0.0f64; 3]; + for pos in 0..k { + theta[idx[pos]] = sol[pos].max(0.0); + } + let sse: f64 = pts + .iter() + .map(|&(t, u, h)| { + let err = (theta[0] + theta[1] * u + theta[2] * h - t) / t; + err * err + }) + .sum(); + let better = sse + 1e-12 < best_sse + || ((sse - best_sse).abs() <= 1e-12 && k < best_params); + if better { + best_sse = sse; + best_theta = theta; + best_params = k; + } + } + let constant_nanos = (best_theta[1] == 0.0 + && best_theta[2] == 0.0 + && (u_max >= 1.0 - 1e-9 || (u_max - u_min) >= 0.15)) + .then_some(best_theta[0].round().clamp(1.0, u64::MAX as f64) as u64); + PrefillPredictor { + capacity: self.capacity, + constant_nanos, + theta: best_theta, + u_min, + u_max, + t_at_umax, + has_deep_context, + } + } +} + +fn solve_small_spd(a: &[[f64; 3]; 3], b: &[f64; 3], idx: &[usize]) -> Option<[f64; 3]> { + let mut out = [0.0f64; 3]; + match idx.len() { + 1 => { + let i = idx[0]; + if a[i][i] <= 1e-30 { + return None; + } + out[0] = b[i] / a[i][i]; + Some(out) + } + 2 => { + let (i, j) = (idx[0], idx[1]); + let (a00, a01, a11) = (a[i][i], a[i][j], a[j][j]); + let det = a00 * a11 - a01 * a01; + if det <= 1e-18 * (a00 * a11).max(1e-30) { + return None; + } + out[0] = (b[i] * a11 - b[j] * a01) / det; + out[1] = (a00 * b[j] - a01 * b[i]) / det; + Some(out) + } + 3 => { + let mut m = [[0.0f64; 4]; 3]; + for r in 0..3 { + for c in 0..3 { + m[r][c] = a[idx[r]][idx[c]]; + } + m[r][3] = b[idx[r]]; + } + let scale = (m[0][0] * m[1][1] * m[2][2]).max(1e-30); + let mut det = 1.0; + for col in 0..3 { + let mut pivot = col; + for r in (col + 1)..3 { + if m[r][col].abs() > m[pivot][col].abs() { + pivot = r; + } + } + if pivot != col { + m.swap(col, pivot); + } + let diag = m[col][col]; + if diag.abs() <= 1e-30 { + return None; + } + det *= diag.abs(); + for r in (col + 1)..3 { + let factor = m[r][col] / diag; + for c in col..4 { + m[r][c] -= factor * m[col][c]; + } + } + } + if det <= 1e-18 * scale { + return None; + } + for r in (0..3).rev() { + let mut rhs = m[r][3]; + for c in (r + 1)..3 { + rhs -= m[r][c] * out[c]; + } + out[r] = rhs / m[r][r]; + } + Some(out) + } + _ => None, + } +} + struct Estimate { nanos: u64, replays: ReplayTimes, + prefill: Option, observed_at_ns: u64, last_attempt_ns: u64, } #[derive(Default)] struct ReplayTimes { - samples: [u64; 9], - len: usize, - next: usize, + ring: Ring9, } impl ReplayTimes { fn observe(&mut self, sample: u64, fresh: bool) -> u64 { if !fresh { - *self = Self::default(); + self.ring.reset(); } - self.samples[self.next] = sample; - self.next = (self.next + 1) % self.samples.len(); - self.len = (self.len + 1).min(self.samples.len()); - let mut ordered = self.samples; - ordered[..self.len].sort_unstable(); - let middle = self.len / 2; - if self.len % 2 == 0 { + self.ring.push(sample); + let (ordered, len) = self.ring.sorted_by(u64::cmp); + let middle = len / 2; + if len % 2 == 0 { ((u128::from(ordered[middle - 1]) + u128::from(ordered[middle]) + 1) / 2) as u64 } else { ordered[middle] @@ -118,12 +532,25 @@ fn kind_index(kind: GraphKind) -> usize { } } +fn prefill_kind_slot(kind: GraphKind) -> Option { + match kind { + GraphKind::Prefill => Some(0), + GraphKind::TerminalPrefill => Some(1), + GraphKind::ScoredPrefill => Some(2), + _ => None, + } +} + #[derive(Default)] pub(super) struct ActionCosts { entries: Vec<(Key, Estimate)>, index: std::collections::HashMap, batches: [Vec; 11], packed_round_durations: Vec>>, + /// Per prefill kind, measured `(capacity, theta_2 / capacity, observed_at_ns)` peers + /// sorted descending by `capacity` so unmeasured-at-deep-context smaller capacities can + /// borrow KV-attention scaling from strictly larger fresh peers without extra lookups. + prefill_context_slopes: [Vec<(usize, f64, u64)>; 3], now_ns: u64, ttl_ns: u64, } @@ -146,8 +573,14 @@ impl ActionCosts { let estimate = &mut self.entries[self.index[&key]].1; estimate.nanos = nanos; estimate.replays.observe(nanos, false); + if let Some(model) = estimate.prefill.as_mut() { + model.reset_with_full(nanos); + } estimate.observed_at_ns = self.now_ns; self.refresh_packed_durations(); + if key.kind.is_prefill() { + self.refresh_prefill_context_slopes(); + } } pub fn prepared(graphs: &[GraphDescriptor], token_capacity: usize) -> Result { @@ -170,6 +603,7 @@ impl ActionCosts { Estimate { nanos: 0, replays: ReplayTimes::default(), + prefill: key.kind.is_prefill().then(|| PrefillCostModel::new(key.tokens)), observed_at_ns: 0, last_attempt_ns: 0, }, @@ -206,6 +640,89 @@ impl ActionCosts { self.shape_duration(kind, batch, tokens, 0) } + pub fn prefill_duration( + &self, + kind: GraphKind, + capacity: usize, + work: usize, + start_position: u64, + ) -> Option { + self.prefill_entry(kind, capacity) + .map(|predictor| predictor.map_or(0, |p| p.predict(work, start_position))) + } + + pub fn prefill_entry( + &self, + kind: GraphKind, + capacity: usize, + ) -> Option> { + let key = Key { + drafts: 0, + kind, + batch: 1, + tokens: capacity, + prefill: 0, + packed: 0, + }; + let estimate = self.entry(key)?; + if estimate.nanos == 0 { + return Some(None); + } + let mut predictor = estimate + .prefill + .as_ref() + .and_then(|model| model.predictor) + .unwrap_or_else(|| PrefillPredictor::constant(capacity, estimate.nanos)); + if !predictor.has_deep_context() + && let Some(theta2) = self.borrowed_prefill_context_slope(kind, capacity) + { + predictor = predictor.with_borrowed_context_slope(theta2); + } + Some(Some(predictor)) + } + + pub fn prefill_predictor(&self, kind: GraphKind, capacity: usize) -> Option { + self.prefill_entry(kind, capacity).flatten() + } + + fn borrowed_prefill_context_slope(&self, kind: GraphKind, capacity: usize) -> Option { + let slot = prefill_kind_slot(kind)?; + self.prefill_context_slopes[slot] + .iter() + .find(|&&(peer_cap, slope, observed_at_ns)| { + peer_cap > capacity + && slope > 0.0 + && self.now_ns.saturating_sub(observed_at_ns) < self.ttl_ns + }) + .map(|&(_, slope, _)| slope * capacity.max(1) as f64) + } + + fn refresh_prefill_context_slopes(&mut self) { + for list in &mut self.prefill_context_slopes { + list.clear(); + } + for (key, estimate) in &self.entries { + if key.batch != 1 || estimate.nanos == 0 { + continue; + } + let Some(slot) = prefill_kind_slot(key.kind) else { + continue; + }; + let Some(slope) = estimate + .prefill + .as_ref() + .and_then(|model| model.predictor) + .and_then(PrefillPredictor::context_slope_per_token) + else { + continue; + }; + self.prefill_context_slopes[slot].push((key.tokens, slope, estimate.observed_at_ns)); + } + for list in &mut self.prefill_context_slopes { + list.sort_unstable_by(|a, b| b.0.cmp(&a.0)); + } + } + fn refresh_packed_durations(&mut self) { for row in &mut self.packed_round_durations { row.fill(None); } for (key, estimate) in &self.entries { @@ -297,6 +814,16 @@ impl ActionCosts { } pub fn get(&self, step: &ScheduledStep) -> Option { + if step.kind.is_prefill() && step.batch_capacity == 1 { + if let Some(lane) = step.lanes.first() { + return self.prefill_duration( + step.kind, + step.token_capacity, + lane.tokens, + lane.start_position, + ); + } + } self.duration_key(Key::from_step(step)) } @@ -319,9 +846,20 @@ impl ActionCosts { if let Some(&index) = self.index.get(&key) { let estimate = &mut self.entries[index].1; let fresh = estimate.fresh(self.now_ns, self.ttl_ns); - estimate.nanos = estimate.replays.observe(sample, fresh); + if let Some(model) = estimate.prefill.as_mut() { + let (work, start_position) = step + .lanes + .first() + .map_or((step.token_capacity, 0), |lane| (lane.tokens, lane.start_position)); + estimate.nanos = model.observe(sample, work, start_position, fresh); + } else { + estimate.nanos = estimate.replays.observe(sample, fresh); + } estimate.observed_at_ns = self.now_ns; self.refresh_packed_durations(); + if key.kind.is_prefill() { + self.refresh_prefill_context_slopes(); + } } } } @@ -445,4 +983,196 @@ mod tests { costs.set_measured(&step, 750_000); assert_eq!(costs.fresh_duration(GraphKind::Snapshot, 1), Some(750_000)); } + + #[test] + fn prefill_cost_model_prevents_tail_poisoning_and_tracks_fill_and_context() { + use crate::execution::ExecutionTiming; + use crate::scheduler::{RequestHandle, ScheduledLane}; + + let make_prefill = |name: &str, cap: usize| GraphDescriptor { + name: name.into(), + kind: GraphKind::Prefill, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }; + let step_for = |cap: usize, tokens: usize, start_position: u64| ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Prefill, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position, + tokens, + }], + requires_feedback: true, + }; + let timing = |ns: u64| { + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(ns); + ExecutionTiming { + gpu_ns, + wall_ns: ns, + queued: false, + readiness: None, + } + }; + + let graphs = vec![make_prefill("p3584", 3584), make_prefill("p4096", 4096)]; + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + let ttl = 30_000_000_000u64; + costs.advance_to(1_000_000_000, ttl); + + // Kimi K3.1 #485 scenario: 3584 full chunk takes 7.81 s, 4096 full chunk takes 1.76 s. + costs.observe(&step_for(3584, 3584, 0), timing(7_810_000_000)); + costs.observe(&step_for(4096, 4096, 0), timing(1_760_000_000)); + + // 100 consecutive 128-token tails at 1.51 s must NOT evict or poison the full-chunk cost. + for _ in 0..100 { + costs.observe(&step_for(3584, 128, 0), timing(1_510_000_000)); + } + let tail_3584 = costs.prefill_duration(GraphKind::Prefill, 3584, 128, 0).unwrap(); + let mid_3584 = costs.prefill_duration(GraphKind::Prefill, 3584, 1792, 0).unwrap(); + let full_3584 = costs.prefill_duration(GraphKind::Prefill, 3584, 3584, 0).unwrap(); + let full_4096 = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 0).unwrap(); + assert!((tail_3584 as i64 - 1_510_000_000).abs() < 50_000_000, "tail={tail_3584}"); + assert!((mid_3584 as i64 - 4_547_000_000).abs() < 100_000_000, "mid={mid_3584}"); + assert!((full_3584 as i64 - 7_810_000_000).abs() < 50_000_000, "full={full_3584}"); + assert!(full_4096 < full_3584 / 4, "4096 ({full_4096}) must beat 3584 ({full_3584})"); + + // Post-TTL reset with ONLY a single 128-token tail at 1.51 s: bounded upward + // extrapolation must prevent 3584 full-chunk from looking cheaper than 4096 at 1.76 s + // without exploding to an uncapped 28x (42.28 s) lockout cost. + costs.advance_to(1_000_000_000 + ttl + 1, ttl); + costs.observe(&step_for(3584, 128, 0), timing(1_510_000_000)); + assert_eq!(costs.prefill_duration(GraphKind::Prefill, 3584, 128, 0), Some(1_510_000_000)); + let guarded_full_3584 = costs.prefill_duration(GraphKind::Prefill, 3584, 3584, 0).unwrap(); + let expected_capped = 1_510_000_000 * 4; + assert!( + guarded_full_3584 >= expected_capped - 10_000_000 + && guarded_full_3584 <= expected_capped + 10_000_000, + "single tail must be bounded at 4x upward extrapolation: guarded={guarded_full_3584}" + ); + assert!( + guarded_full_3584 > 1_760_000_000 * 3, + "guarded 3584 ({guarded_full_3584}) must still not undercut 4096 at 1.76 s" + ); + + // Deep KV context scaling: 4096 full chunk at start=0 (100 ms) vs start=32768 (260 ms). + costs.advance_to(1_000_000_000 + 2 * ttl + 2, ttl); + costs.observe(&step_for(4096, 4096, 0), timing(100_000_000)); + costs.observe(&step_for(4096, 4096, 32768), timing(260_000_000)); + let shallow = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 0).unwrap(); + let mid_ctx = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 16384).unwrap(); + let deep = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 32768).unwrap(); + assert!((shallow as i64 - 100_000_000).abs() < 2_000_000, "shallow={shallow}"); + assert!((mid_ctx as i64 - 180_000_000).abs() < 2_000_000, "mid_ctx={mid_ctx}"); + assert!((deep as i64 - 260_000_000).abs() < 2_000_000, "deep={deep}"); + + // Flat unmasked graph: partial and full chunks have identical runtime -> constant predictor. + costs.advance_to(1_000_000_000 + 3 * ttl + 3, ttl); + costs.observe(&step_for(4096, 4096, 0), timing(50_000_000)); + costs.observe(&step_for(4096, 128, 0), timing(50_000_000)); + let pred = costs.prefill_predictor(GraphKind::Prefill, 4096).unwrap(); + assert!(pred.is_constant()); + assert_eq!(pred.constant_ns(), Some(50_000_000)); + } + + #[test] + fn smaller_prefill_borrows_larger_peer_context_slope_to_prevent_run1_ladder_drift() { + use crate::execution::ExecutionTiming; + use crate::scheduler::{RequestHandle, ScheduledLane}; + + let make_prefill = |name: &str, cap: usize| GraphDescriptor { + name: name.into(), + kind: GraphKind::Prefill, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }; + let step_for = |cap: usize, tokens: usize, start_position: u64| ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Prefill, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position, + tokens, + }], + requires_feedback: true, + }; + let timing = |ns: u64| { + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(ns); + ExecutionTiming { + gpu_ns, + wall_ns: ns, + queued: false, + readiness: None, + } + }; + + let graphs = vec![ + make_prefill("p4096", 4096), + make_prefill("p7168", 7168), + make_prefill("p8192", 8192), + ]; + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + let ttl = 30_000_000_000u64; + costs.advance_to(1_000_000_000, ttl); + + // At start_position = 0, larger capacities are cheaper per token (24.4 vs 25.1 vs 26.9 ns/tok). + costs.observe(&step_for(4096, 4096, 0), timing(110_000_000)); + costs.observe(&step_for(7168, 7168, 0), timing(180_000_000)); + costs.observe(&step_for(8192, 8192, 0), timing(200_000_000)); + + // On Run 1 at 64k context, 8192 slows down by +80 ms (10 ms per 8k history). + // 4096 and 7168 have never run at deep context yet. + costs.observe(&step_for(8192, 8192, 65_536), timing(280_000_000)); + + // At start_position = 0, borrowing must leave shallow costs untouched. + assert_eq!(costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 0), Some(110_000_000)); + assert_eq!(costs.prefill_duration(GraphKind::Prefill, 7168, 7168, 0), Some(180_000_000)); + + // At start_position = 98304, 4096 and 7168 borrow 8192's per-token KV slope, so + // 8192 stays strictly cheaper per token (no Run-1 ladder drift onto stale 0k smaller shapes). + let ns_8192 = costs.prefill_duration(GraphKind::Prefill, 8192, 8192, 98_304).unwrap(); + let ns_7168 = costs.prefill_duration(GraphKind::Prefill, 7168, 7168, 98_304).unwrap(); + let ns_4096 = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 98_304).unwrap(); + assert!( + u128::from(ns_8192) * 7168 < u128::from(ns_7168) * 8192, + "8192 ({ns_8192}) must beat 7168 ({ns_7168}) per token at 96k" + ); + assert!( + u128::from(ns_8192) * 4096 < u128::from(ns_4096) * 8192, + "8192 ({ns_8192}) must beat 4096 ({ns_4096}) per token at 96k" + ); + + // Once 4096 observes its own deep-context runtime, it uses its own fit rather than borrowing. + costs.observe(&step_for(4096, 4096, 65_536), timing(120_000_000)); + let own_4096 = costs.prefill_duration(GraphKind::Prefill, 4096, 4096, 65_536).unwrap(); + assert!((own_4096 as i64 - 120_000_000).abs() < 2_000_000, "own_4096={own_4096}"); + } } diff --git a/helios/src/scheduler/learning.rs b/helios/src/scheduler/learning.rs index 91efd40d8..5ebfffb11 100644 --- a/helios/src/scheduler/learning.rs +++ b/helios/src/scheduler/learning.rs @@ -9,7 +9,7 @@ use super::{policy::{Candidate, bits}, utility::LaneValue, *}; impl RequestScheduler { pub(super) fn optimistic_tokens(&self, request: &LiveRequest, width: usize) -> f64 { - f64::from(width != 0) + self.speculative_curve(request, true)[..width.saturating_sub(1)].iter().sum::() + super::rounds::forecast_tokens(&self.powered_curve(request, true), width) } pub(super) fn acceptance_probe(&self, ordinary: Candidate, diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index d054396f6..19c2778f5 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -23,6 +23,7 @@ pub struct PolicyConfig { pub estimate_ttl_ns: u64, pub adaptive_verification_alpha: f64, pub checkpoint_extra_work_fraction: f64, + pub coalescing_horizon_tokens: f64, } impl Default for PolicyConfig { @@ -38,6 +39,7 @@ impl Default for PolicyConfig { estimate_ttl_ns: 30_000_000_000, checkpoint_extra_work_fraction: 0.05, adaptive_verification_alpha: 1.0, + coalescing_horizon_tokens: 64.0, } } } @@ -223,6 +225,7 @@ impl RequestScheduler { policy.decode_age_price, policy.terminal_value, policy.terminal_age_price, + policy.coalescing_horizon_tokens, ] .into_iter() .any(|v| !v.is_finite() || v < 0.0) @@ -306,7 +309,12 @@ impl RequestScheduler { return false; } if request.pending > 0 - && !(request.phase == RequestPhase::Decode + && !((request.phase == RequestPhase::Decode + || (request.phase == RequestPhase::Prefill + && !request.prompt_logprobs + && request.checkpoint_capture.is_none() + && request.scheduled_consumed < request.prefill_limit() as u64 + && request.scheduled_consumed < request.prompt_tokens as u64)) && request.pending < 2 && !request.grammar_constrained) { @@ -330,12 +338,36 @@ impl RequestScheduler { } } + fn effective_prefill_catalog( + &self, + request: &LiveRequest, + kind: GraphKind, + cut: Option, + ) -> &[usize] { + if kind == GraphKind::ScoredPrefill { + &self.scored_prefill_catalog + } else if self.prefill_requires_terminal_completion(request, cut) { + &self.terminal_prefill_catalog + } else { + &self.prefill_catalog + } + } + pub(super) fn prefill_work(&self, request: &LiveRequest, capacity: usize) -> usize { self.prefill_work_through(request, capacity, self.estimated_checkpoint_cut(request)) } pub(super) fn prefill_work_through(&self, request: &LiveRequest, capacity: usize, cut: Option) -> usize { - let start = request.consumed_tokens as usize; + self.prefill_work_from(request, Self::prefill_cursor(request), capacity, cut) + } + + pub(super) fn prefill_work_from( + &self, + request: &LiveRequest, + start: usize, + capacity: usize, + cut: Option, + ) -> usize { let mut end = cut .unwrap_or(request.prompt_tokens) .min(start.saturating_add(capacity)) @@ -405,6 +437,173 @@ impl RequestScheduler { ) } + /// Unscaled per-prefill-token coalescing continuation value (in log form) + /// pricing the steady-state decode-batch efficiency gain (`K -> K + m`) + /// unlocked over a bounded output horizon when queued prefills join an + /// under-batched active decode cohort. + fn coalescing_prefill_log_bonus(&self) -> [f64; REQUEST_LANES] { + let mut bonus_log = [f64::NEG_INFINITY; REQUEST_LANES]; + if self.policy.coalescing_horizon_tokens <= 0.0 { + return bonus_log; + } + let mut decoder_slots = [0usize; REQUEST_LANES]; + let mut decoder_count = 0usize; + let mut peer_budget = usize::MAX; + let mut prefillers = [(0usize, 0usize, 0usize); REQUEST_LANES]; + let mut prefiller_count = 0usize; + for (slot, entry) in self.slots.iter().enumerate() { + let Some(r) = entry + .request + .as_ref() + .filter(|r| !terminal_cleanup(r) && self.request_kind(r).is_some()) + else { + continue; + }; + if r.consumed_tokens >= r.prompt_tokens as u64 { + if r.generated_tokens > 0 + && r.generated_tokens < r.max_new_tokens + && r.scheduled_consumed < self.limits.max_sequence_tokens as u64 + { + let rem = ((r.max_new_tokens - r.generated_tokens) as usize) + .min(self.limits.max_sequence_tokens.saturating_sub(r.scheduled_consumed as usize)); + if rem > 0 { + decoder_slots[decoder_count] = slot; + decoder_count += 1; + peer_budget = peer_budget.min(rem); + } + } + } else if !r.prompt_logprobs && r.scheduled_consumed < r.prompt_tokens as u64 { + let initial_prefill = r + .prompt_tokens + .saturating_sub(r.admission_reused_tokens as usize) + .max(1); + let post_prefill = (r.max_new_tokens as usize) + .min(self.limits.max_sequence_tokens.saturating_sub(r.prompt_tokens)) + .saturating_sub(1); + if post_prefill > 0 { + prefillers[prefiller_count] = (slot, initial_prefill, post_prefill); + prefiller_count += 1; + } + } + } + if decoder_count == 0 || prefiller_count == 0 || peer_budget == usize::MAX { + return bonus_log; + } + let max_drafts = self.capabilities.completion_token_capacity.saturating_sub(1); + let mut mean_curve = Vec::new(); + if !self.speculative_widths.is_empty() && max_drafts > 0 { + mean_curve.resize(max_drafts, 0.0f64); + for &slot in &decoder_slots[..decoder_count] { + let r = self.slots[slot].request.as_ref().unwrap(); + let curve = self.powered_curve(r, false); + for (dst, src) in mean_curve.iter_mut().zip(curve.iter()) { + *dst += *src; + } + } + let inv = 1.0 / decoder_count as f64; + for value in &mut mean_curve { + *value *= inv; + } + } + let expected_at = |eff_width: f64| -> f64 { + if eff_width <= 1.0 || mean_curve.is_empty() { + return 1.0; + } + let drafts = eff_width - 1.0; + let full = (drafts.floor() as usize).min(mean_curve.len()); + let frac = (drafts - full as f64).clamp(0.0, 1.0); + let mut sum = 1.0 + mean_curve[..full].iter().sum::(); + if full < mean_curve.len() { + sum += frac * mean_curve[full]; + } + sum + }; + let best_decode_rate = |n_streams: usize| -> f64 { + let mut best = 0.0f64; + if self.speculative_widths.is_empty() { + for &batch in self.costs.batches(GraphKind::Decode) { + if let Some(ns) = self.costs.duration(GraphKind::Decode, batch, 1).filter(|&n| n > 0) { + let served = n_streams.min(batch) as f64; + let ms = ns as f64 / 1e6; + best = best.max(served / ms); + } + } + } else { + let mut saw_packed = false; + for shape in self.costs.packed_round_shapes() { + saw_packed = true; + if shape.nanos == 0 + || shape.batch > self.limits.request_slots + || !self.speculative_widths_for(shape.batch).contains(&shape.width) + { + continue; + } + let served = n_streams.min(shape.batch); + let max_per_lane = (shape.drafts + 1).min(shape.width) as f64; + let packed_per_lane = if shape.tokens > 0 { + shape.tokens as f64 / served as f64 + } else { + max_per_lane + }; + let eff_width = max_per_lane.min(packed_per_lane).max(1.0); + let mean_out = expected_at(eff_width).min(peer_budget as f64).max(1.0); + let ms = shape.nanos as f64 / 1e6; + best = best.max(served as f64 * mean_out / ms); + } + if !saw_packed { + for &(batch, ref widths) in &self.speculative_catalog { + for &width in widths { + if let Some(ns) = self.costs.duration(GraphKind::Speculative, batch, width).filter(|&n| n > 0) { + let served = n_streams.min(batch); + let mean_out = expected_at(width as f64).min(peer_budget as f64).max(1.0); + let ms = ns as f64 / 1e6; + best = best.max(served as f64 * mean_out / ms); + } + } + } + } + } + best + }; + let base_rate = best_decode_rate(decoder_count); + if base_rate <= 0.0 { + return bonus_log; + } + let mut best_surplus_per_horizon = 0.0f64; + for added in 1..=prefiller_count { + let next_rate = best_decode_rate(decoder_count + added); + if next_rate > base_rate { + let total = (decoder_count + added) as f64; + let multiplier = (total / added as f64) * (1.0 - base_rate / next_rate); + // Value the unlocked batch-efficiency throughput surplus at intrinsic + // `output_token_value` so coalescing never amplifies low-rate fairness + // prices into starving active decoders during long prefills. + best_surplus_per_horizon = + best_surplus_per_horizon.max(self.policy.output_token_value * multiplier); + } + } + if best_surplus_per_horizon <= 0.0 { + return bonus_log; + } + for &(slot, initial_prefill, post_prefill) in &prefillers[..prefiller_count] { + let horizon = self + .policy + .coalescing_horizon_tokens + .min(post_prefill as f64) + .min(peer_budget as f64); + if horizon > 0.0 { + // Amortize the unlocked coalescing surplus uniformly across the prefiller's + // uncached prompt tokens so total credit sums to 1x regardless of chunking + // and chunk sizing stays smooth under active decode waiting age. + let per_token = (best_surplus_per_horizon * horizon) / initial_prefill as f64; + if per_token.is_finite() && per_token > 0.0 { + bonus_log[slot] = per_token.ln(); + } + } + } + bonus_log + } + pub(super) fn lane_values(&self, window_ns: u64) -> ([LaneValue; REQUEST_LANES], f64, f64) { let mut values = [LaneValue::default(); REQUEST_LANES]; let count = self @@ -416,6 +615,7 @@ impl RequestScheduler { .max(1); let mut token_log = [f64::NEG_INFINITY; REQUEST_LANES]; let mut delivery_log = token_log; + let coalesce_log = self.coalescing_prefill_log_bonus(); let rates: [_; REQUEST_LANES] = std::array::from_fn(|slot| { self.slots .get(slot) @@ -479,12 +679,16 @@ impl RequestScheduler { values[slot].age_ms = self.now_ns.saturating_add(window_ns) .saturating_sub(last_delivery) as f64 / 1e6; } - scale = scale.max(token_log[slot]).max(delivery_log[slot]); + scale = scale + .max(token_log[slot]) + .max(delivery_log[slot]) + .max(coalesce_log[slot]); } let unit = (-scale).exp(); let mut age_price = 0.0; for (slot, value) in values.iter_mut().enumerate() { - value.prefill_token = unit + (token_log[slot] - scale).exp(); + value.prefill_token = + unit + (token_log[slot] - scale).exp() + (coalesce_log[slot] - scale).exp(); value.output_token = self.policy.output_token_value * unit + (token_log[slot] - scale).exp(); value.delivery = (delivery_log[slot] - scale).exp(); @@ -504,9 +708,9 @@ impl RequestScheduler { } }; if r.consumed_tokens < r.prompt_tokens as u64 { - let catalog = self.prefill_catalog(r.prefill_kind()); let cut = self.estimated_checkpoint_cut(r); let terminal_only = self.prefill_requires_terminal_completion(r, cut); + let catalog = self.effective_prefill_catalog(r, r.prefill_kind(), cut); let mut natural_fit = None; for &capacity in catalog { let work = self.prefill_work_through(r, capacity, cut); @@ -517,7 +721,7 @@ impl RequestScheduler { if terminal_only && kind == GraphKind::Prefill { continue; } - if let Some(ns) = self.costs.duration(kind, 1, capacity) { + if let Some(ns) = self.costs.prefill_duration(kind, capacity, work, r.scheduled_consumed) { if ns == 0 && *natural_fit .get_or_insert_with(|| self.natural_fit_prefill_capacity(r, catalog, cut)) @@ -529,7 +733,7 @@ impl RequestScheduler { ns, value.prefill( work, - r.consumed_tokens + work as u64 == r.prompt_tokens as u64, + r.scheduled_consumed + work as u64 == r.prompt_tokens as u64, ), ); } @@ -559,6 +763,7 @@ impl RequestScheduler { } } } + let mut mixed_curve = None; for &(batch, width, prefill) in &self.mixed_catalog { let Some(ns) = self .costs @@ -570,25 +775,29 @@ impl RequestScheduler { && !r.prompt_logprobs && !r.deferred_prefill { - let work = self.prefill_work(r, prefill); + let cut = self.estimated_checkpoint_cut(r); + if self.prefill_requires_terminal_completion(r, cut) { + continue; + } + let work = self.prefill_work_through(r, prefill, cut); if work > 0 { consider( ns, value.prefill( work, - r.consumed_tokens + work as u64 == r.prompt_tokens as u64, + r.scheduled_consumed + work as u64 == r.prompt_tokens as u64, ), ); } - } else if r.generated_tokens > 0 { + } else if r.consumed_tokens >= r.prompt_tokens as u64 && r.generated_tokens > 0 { let tokens = self.speculative_tokens(r, width); - consider( - ns, - value.decode( - r.acceptance.expected_tokens(tokens), - ns as f64 / 1e6, - ), - ); + let expected = if self.speculative_widths.is_empty() { + 1.0 + } else { + let curve = mixed_curve.get_or_insert_with(|| self.powered_curve(r, false)); + super::rounds::forecast_tokens(curve, tokens) + }; + consider(ns, value.decode(expected, ns as f64 / 1e6)); } } best.map(|(rate, value)| (rate.duration_ns, value)) @@ -704,7 +913,85 @@ impl RequestScheduler { selected | best_cohort::(&remaining[..n], capacity - count) }; let mut best: Option<(u64, ValueRate)> = None; - let mut consider = |following, batch, width, prefill| { + let mut consider = |following: GraphKind, batch, width, prefill| { + if following.is_prefill() { + let Some(predictor) = self.costs.prefill_entry(following, width) else { + return; + }; + let first_ms = duration_ns as f64 / 1e6; + for (slot, entry) in self.slots.iter().enumerate() { + let Some(request) = entry.request.as_ref() else { + continue; + }; + if mask & (1 << slot) == 0 || terminal_cleanup(request) { + continue; + } + let Some(promoted_kind) = self.following_kind(request, kind) else { + continue; + }; + let matches_kind = if following == GraphKind::TerminalPrefill { + promoted_kind == GraphKind::Prefill + } else { + promoted_kind == following + }; + if !matches_kind { + continue; + } + let cut = self.estimated_checkpoint_cut(request); + let work = self.prefill_work_through(request, width, cut); + if work == 0 + || (matches!(following, GraphKind::Prefill | GraphKind::TerminalPrefill) + && (self.resolve_prefill_kind(request, width, work, cut) != following + || (following == GraphKind::Prefill + && self.prefill_requires_terminal_completion(request, cut)))) + || (predictor.is_none() + && self.natural_fit_prefill_capacity( + request, + self.effective_prefill_catalog(request, following, cut), + cut, + ) != Some(width)) + { + continue; + } + let ns = predictor.map_or(0, |p| p.predict(work, request.scheduled_consumed)); + let horizon = if ns == 0 || duration_ns == 0 { + 0 + } else { + ns.saturating_add(duration_ns) + }; + let total_ms = horizon as f64 / 1e6; + let mut value = + self.lane_value_for_tokens(request, following, work, horizon, values[slot]); + let mut selected = 1u64 << slot; + if capacity > 1 { + let mut finishing = [(0usize, 0.0); REQUEST_LANES]; + let mut f = 0; + for (other_slot, other_entry) in self.slots.iter().enumerate() { + if other_slot == slot || mask & (1 << other_slot) == 0 { + continue; + } + if other_entry.request.as_ref().is_some_and(terminal_cleanup) { + finishing[f] = (other_slot, values[other_slot].finish(first_ms, total_ms)); + f += 1; + } + } + if f > 0 { + let extra = best_cohort::(&finishing[..f], capacity - 1); + selected |= extra; + value += finishing[..f] + .iter() + .filter(|(s, _)| extra & (1 << s) != 0) + .map(|(_, v)| *v) + .sum::(); + } + } + let rate = ValueRate::new(horizon, value, age_price); + if best.is_none_or(|(_, old)| rate.compare(old).is_gt()) { + best = Some((fill(selected), rate)); + } + } + return; + } let ns = if following == GraphKind::Speculative { // The full B x W graph is already included in the packed round aggregate. self.costs.packed_round_duration(batch, width) @@ -752,8 +1039,6 @@ impl RequestScheduler { let accepts = |k: GraphKind| { if mixed { (k == GraphKind::Prefill && !request.deferred_prefill) || k == decode - } else if following == GraphKind::TerminalPrefill { - k == GraphKind::Prefill } else { k == following } @@ -772,21 +1057,7 @@ impl RequestScheduler { }; if role.is_prefill() { let cut = self.estimated_checkpoint_cut(request); - let work = self.prefill_work_through(request, extent, cut); - if work == 0 - || (!mixed - && ((matches!(following, GraphKind::Prefill | GraphKind::TerminalPrefill) - && (self.resolve_prefill_kind(request, extent, work, cut) - != following - || (following == GraphKind::Prefill - && self.prefill_requires_terminal_completion(request, cut)))) - || (ns == 0 - && self.natural_fit_prefill_capacity( - request, - self.prefill_catalog(request.prefill_kind()), - cut, - ) != Some(extent)))) - { + if self.prefill_work_through(request, extent, cut) == 0 { continue; } } @@ -951,7 +1222,7 @@ impl RequestScheduler { match kind { GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => value.prefill( tokens, - r.consumed_tokens + tokens as u64 == r.prompt_tokens as u64, + r.scheduled_consumed + tokens as u64 == r.prompt_tokens as u64, ), GraphKind::Decode | GraphKind::Speculative => value.decode_within( self.expected_speculative_tokens(r, tokens), @@ -975,20 +1246,15 @@ impl RequestScheduler { values: &[LaneValue; REQUEST_LANES], age_price: f64, ) { - let Some(duration_ns) = self.costs.duration(kind, batch, capacity) else { - return; - }; - let mut offers = [(0usize, 0.0); REQUEST_LANES]; - let mut count = 0; - for slot in bits(mask) { - let r = self.slots[slot].request.as_ref().unwrap(); - if kind.is_prefill() { - let catalog = if kind == GraphKind::ScoredPrefill { - &self.scored_prefill_catalog - } else { - &self.prefill_catalog - }; + if kind.is_prefill() { + let Some(predictor) = self.costs.prefill_entry(kind, capacity) else { + return; + }; + let mut winner: Option<(usize, usize, u64, ValueRate)> = None; + for slot in bits(mask) { + let r = self.slots[slot].request.as_ref().unwrap(); let cut = self.estimated_checkpoint_cut(r); + let catalog = self.effective_prefill_catalog(r, kind, cut); let work = self.prefill_work_through(r, capacity, cut); let resolved = self.resolve_prefill_kind(r, capacity, work, cut); // Restrict unmeasured pure prefill discovery to the natural-fit capacity @@ -998,12 +1264,55 @@ impl RequestScheduler { || resolved != kind || (kind == GraphKind::Prefill && self.prefill_requires_terminal_completion(r, cut)) - || (duration_ns == 0 + || (predictor.is_none() && self.natural_fit_prefill_capacity(r, catalog, cut) != Some(capacity)) { continue; } + let slot_ns = predictor.map_or(0, |p| p.predict(work, r.scheduled_consumed)); + let expected = self.lane_value_for_tokens(r, kind, work, slot_ns, values[slot]); + let rate = ValueRate::new(slot_ns, expected, age_price); + if winner.is_none_or(|(best_slot, _, _, best_rate)| { + match rate.compare(best_rate) { + std::cmp::Ordering::Greater => true, + std::cmp::Ordering::Equal => slot < best_slot, + std::cmp::Ordering::Less => false, + } + }) { + winner = Some((slot, work, slot_ns, rate)); + } } + let Some((slot, work, duration_ns, rate)) = winner else { + return; + }; + let selected = 1u64 << slot; + // `materialize` computes the authoritative `plan_requires_feedback` after + // checkpoint cuts and any prefill resizing are resolved. + let feedback = !kind.pipelines(); + output.push(Candidate { + host_lengths: None, + draft_tokens: 0, + packed_token_capacity: 0, + kind, + mask: selected, + batch, + capacity, + prefill_capacity: 0, + prefill_slot: None, + work, + duration_ns, + rate, + feedback, + }); + return; + } + let Some(duration_ns) = self.costs.duration(kind, batch, capacity) else { + return; + }; + let mut offers = [(0usize, 0.0); REQUEST_LANES]; + let mut count = 0; + for slot in bits(mask) { + let r = self.slots[slot].request.as_ref().unwrap(); if kind == GraphKind::Vision && capacity < r.vision_patches[0] { continue; } @@ -1027,16 +1336,9 @@ impl RequestScheduler { let feedback = !self.costs.is_fresh(cost::Key { drafts, kind, batch, tokens: capacity, prefill: 0, packed, }) - || !matches!(kind, GraphKind::Decode | GraphKind::Speculative) + || !kind.pipelines() || bits(selected).any(|slot| { - let r = self.slots[slot].request.as_ref().unwrap(); - r.grammar_constrained - || (kind.is_prefill() - && (r.consumed_tokens + self.prefill_work(r, capacity) as u64 - == r.prompt_tokens as u64 - || r.message_boundaries.binary_search( - &(r.consumed_tokens as usize + self.prefill_work(r, capacity)), - ).is_ok())) + self.slots[slot].request.as_ref().unwrap().grammar_constrained }); let (selected, rate) = self .continuation_candidate( @@ -1055,17 +1357,7 @@ impl RequestScheduler { capacity, prefill_capacity: 0, prefill_slot: None, - work: if kind.is_prefill() { - self.prefill_work( - self.slots[selected.trailing_zeros() as usize] - .request - .as_ref() - .unwrap(), - capacity, - ) - } else { - 0 - }, + work: 0, duration_ns, rate, feedback, @@ -1377,24 +1669,23 @@ impl RequestScheduler { let prefill = catalog.filter(|&capacity| capacity >= work).min()?; (candidate.kind, candidate.capacity, prefill, work) } else { - let catalog = if !request.prompt_logprobs - && self.prefill_requires_terminal_completion(request, cut) - { - &self.terminal_prefill_catalog - } else { - self.prefill_catalog(request.prefill_kind()) - }; + let catalog = self.effective_prefill_catalog(request, request.prefill_kind(), cut); let work = self.prefill_work_through(request, *catalog.last()?, cut); let capacity = *catalog.iter().find(|&&capacity| capacity >= work)?; let kind = self.resolve_prefill_kind(request, capacity, work, cut); (kind, capacity, 0, work) }; - let duration_ns = self.costs.shape_duration(kind, candidate.batch, capacity, prefill)?; + let duration_ns = if mixed { + self.costs.shape_duration(kind, candidate.batch, capacity, prefill)? + } else { + self.costs.prefill_duration(kind, capacity, work, request.scheduled_consumed)? + }; candidate.kind = kind; candidate.capacity = capacity; candidate.prefill_capacity = prefill; candidate.work = work; candidate.duration_ns = duration_ns; + candidate.feedback = !kind.pipelines(); let slot = request.handle.slot as usize; let kind = if mixed { GraphKind::Prefill } else { candidate.kind }; let mut expected = self.lane_value_for_tokens(request, kind, work, duration_ns, values[slot]); diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index e00436fa0..ea37ef213 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -1412,22 +1412,69 @@ fn long_prefill_and_low_acceptance_decode_both_make_progress() { } #[test] -fn prefill_frames_drain_even_when_the_next_request_is_independent() { +fn nonterminal_prefill_frames_pipeline_two_deep_and_terminal_chunks_drain() { let mut s = interactive_engine(2, false); - add(&mut s, 1, 32768, 128); - add(&mut s, 2, 32768, 128); + let h1 = add(&mut s, 1, 32768, 128); + let h2 = add(&mut s, 2, 32768, 128); step(&mut s, 0); let first = s.plan().unwrap(); assert_eq!((first.kind, first.token_capacity), (GraphKind::Prefill, 4096)); - let fence = Fence(s.submitted.0 + 1); - s.commit(&first, fence).unwrap(); - assert!(s.plan().is_none()); + assert!(!s.plan_requires_feedback(&first)); + let fence1 = Fence(s.submitted.0 + 1); + s.commit(&first, fence1).unwrap(); assert!(first.estimated_duration_ns() > 10 * MS); - complete(&mut s, &first, fence, 0, false); + + // Second nonterminal prefill pipelines into the second execution frame without draining. let second = s.plan().unwrap(); assert_eq!((second.kind, second.token_capacity), (GraphKind::Prefill, 4096)); - s.commit(&second, Fence(fence.0 + 1)).unwrap(); + assert!(!s.plan_requires_feedback(&second)); + if second.lanes[0].request == first.lanes[0].request { + assert_eq!(second.lanes[0].start_position, 4096); + } + let fence2 = Fence(fence1.0 + 1); + s.commit(&second, fence2).unwrap(); + // Window of 2 frames is now full. assert!(s.plan().is_none()); + + // Completing frame 1 frees a slot immediately while frame 2 remains in flight. + complete(&mut s, &first, fence1, 0, false); + let third = s.plan().unwrap(); + assert_eq!((third.kind, third.token_capacity), (GraphKind::Prefill, 4096)); + complete(&mut s, &second, fence2, 0, false); + assert!(s.request(h1).is_ok() && s.request(h2).is_ok()); + + // A terminal prefill chunk reaching prompt_tokens still drains as a feedback barrier. + let mut term = interactive_engine(2, false); + let short = add(&mut term, 1, 4096, 128); + add(&mut term, 2, 32768, 128); + initialize(&mut term, short); + let terminal = term.plan().unwrap(); + assert_eq!((terminal.kind, terminal.token_capacity), (GraphKind::Prefill, 4096)); + assert_eq!(terminal.lanes[0].tokens, 4096); + assert!(term.plan_requires_feedback(&terminal)); + let tfence = Fence(term.submitted.0 + 1); + term.commit(&terminal, tfence).unwrap(); + assert!(term.plan().is_none()); + + // Single-request pipelining across consecutive nonterminal chunks + mid-flight cancellation. + let mut single = interactive_engine(1, false); + let solo = add(&mut single, 1, 16384, 64); + initialize(&mut single, solo); + let p1 = single.plan().unwrap(); + assert_eq!((p1.kind, p1.lanes[0].start_position, p1.lanes[0].tokens), (GraphKind::Prefill, 0, 4096)); + assert!(!single.plan_requires_feedback(&p1)); + let f1 = Fence(single.submitted.0 + 1); + single.commit(&p1, f1).unwrap(); + let p2 = single.plan().unwrap(); + assert_eq!((p2.kind, p2.lanes[0].start_position, p2.lanes[0].tokens), (GraphKind::Prefill, 4096, 4096)); + assert!(!single.plan_requires_feedback(&p2)); + let f2 = Fence(f1.0 + 1); + single.commit(&p2, f2).unwrap(); + assert!(single.plan().is_none()); + single.cancel(solo).unwrap(); + complete(&mut single, &p1, f1, 0, false); + complete(&mut single, &p2, f2, 0, false); + single.assert_idle().unwrap(); } #[test] @@ -1622,12 +1669,22 @@ fn delivery_reference_uses_batch_throughput_and_excludes_prefill_only_requests() #[test] fn snapshot_enabling_a_shared_decode_batch_competes_by_the_complete_sequence_cost() { let mut s = interactive_engine(16, true); - let handles: Vec<_> = (1..=16).map(|id| add(&mut s, id, 64, 4096)).collect(); + let mut handles: Vec<_> = (1..=15).map(|id| add(&mut s, id, 64, 4096)).collect(); for &h in &handles { for _ in 0..128 { s.request_mut(h).unwrap().acceptance.observe(0, 7, 7, true, None); } } + ready(&mut s, &handles); + let sixteenth = add(&mut s, 16, 64, 4096); + for _ in 0..128 { + s.request_mut(sixteenth) + .unwrap() + .acceptance + .observe(0, 7, 7, true, None); + } + handles.push(sixteenth); + let mut reached = false; for _ in 0..200 { let decoding = handles .iter() @@ -1638,10 +1695,12 @@ fn snapshot_enabling_a_shared_decode_batch_competes_by_the_complete_sequence_cos .filter(|h| s.request(**h).unwrap().phase == RequestPhase::Snapshot) .count(); if decoding == 15 && copying == 1 { + reached = true; break; } step(&mut s, 7); } + assert!(reached, "expected 15 decoding and 1 copying request"); let plan = s.plan().unwrap(); assert_eq!(plan.kind, GraphKind::Snapshot); assert_eq!(plan.lanes.len(), 1); @@ -1848,6 +1907,7 @@ fn throughput_only(s: &mut RequestScheduler) { token_fairness: 0.0, delivery_fairness: 0.0, decode_age_price: 0.0, + coalescing_horizon_tokens: 0.0, ..Default::default() }) .unwrap(); @@ -6611,3 +6671,152 @@ fn oversubscribed_decoders_incur_excluded_wait_and_protect_skipped_lanes() { ); } } + +#[test] +fn simultaneous_burst_coalesces_prefills_into_full_decode_batches() { + assert!(engine(2, false) + .configure_policy(PolicyConfig { + coalescing_horizon_tokens: -1.0, + ..Default::default() + }) + .is_err()); + + let run_burst = |coalescing_horizon_tokens: f64| { + let mut s = interactive_engine(8, false); + s.prefill_graphs(&[512, 1024, 2048, 4096]).unwrap(); + s.configure_policy(PolicyConfig { + coalescing_horizon_tokens, + ..Default::default() + }) + .unwrap(); + set_cost(&mut s, GraphKind::Prefill, 1, 512, 144 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 1024, 280 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 2048, 550 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 4096, 1080 * MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 27 * MS); + set_cost(&mut s, GraphKind::Decode, 2, 1, 30 * MS); + set_cost(&mut s, GraphKind::Decode, 4, 1, 37 * MS); + set_cost(&mut s, GraphKind::Decode, 8, 1, 48_500_000); + let handles: Vec<_> = (1..=4).map(|id| add(&mut s, id, 512, 128)).collect(); + let mut sub_batch_decodes = 0usize; + let mut full_batch_decodes = 0usize; + for _ in 0..400 { + if handles.iter().all(|h| s.request(*h).is_err()) { + break; + } + let plan = step(&mut s, 0); + if plan.kind == GraphKind::Decode { + if plan.lanes.len() == 4 { + full_batch_decodes += 1; + } else { + sub_batch_decodes += 1; + } + } + } + (sub_batch_decodes, full_batch_decodes, s.now_ns) + }; + + let (base_sub, _, base_ns) = run_burst(0.0); + let (coal_sub, coal_full, coal_ns) = run_burst(PolicyConfig::default().coalescing_horizon_tokens); + assert!( + base_sub > coal_sub && coal_sub == 0, + "expected coalescing to eliminate sub-batch decode fragmentation: base_sub={base_sub}, coal_sub={coal_sub}" + ); + assert!(coal_full >= 120, "expected full B=4 decode rounds, got {coal_full}"); + assert!(coal_ns < base_ns, "coalesced burst makespan {coal_ns} should beat baseline {base_ns}"); +} + +#[test] +fn short_prefill_tails_do_not_poison_full_chunk_graph_selection() { + let mut s = interactive_engine(2, false); + s.prefill_graphs(&[128, 3584, 4096]).unwrap(); + let observe_prefill = |s: &mut RequestScheduler, cap: usize, work: usize, ns: u64| { + let step = ScheduledStep { + draft_tokens: 0, + kind: GraphKind::Prefill, + batch_capacity: 1, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position: 0, + tokens: work, + }], + requires_feedback: true, + }; + s.observe_execution(&step, gpu_time(ns)); + }; + observe_prefill(&mut s, 128, 128, 900 * MS); + observe_prefill(&mut s, 3584, 3584, 7_810 * MS); + observe_prefill(&mut s, 4096, 4096, 1_760 * MS); + // Repeated 128-token tails running in the 3584 graph at 1.51 s must not trick the + // scheduler into choosing 3584 over 4096 for a full 16K prefill. + for _ in 0..20 { + observe_prefill(&mut s, 3584, 128, 1_510 * MS); + } + let handle = add(&mut s, 1, 16_384, 32); + initialize(&mut s, handle); + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::Prefill); + assert_eq!(plan.token_capacity, 4096); + assert_eq!(plan.lanes[0].tokens, 4096); +} + +#[test] +fn unmeasured_terminal_prefill_discovery_uses_terminal_catalog_and_mixed_respects_alpha() { + // Unmeasured TerminalPrefill(4096) with prefill catalog [64, 512, 4096] must still + // be discovered when a 512-token prompt requires terminal completion. + let mut s = interactive_engine(2, false); + s.prefill_graphs(&[64, 512, 4096]).unwrap(); + s.terminal_prefill_graphs(&[4096]).unwrap(); + let mut graphs = super::tests::duration_graphs(2); + graphs.retain(|g| !g.kind.is_prefill() || matches!(g.token_capacity, 64 | 512 | 4096)); + graphs.push(crate::execution::GraphDescriptor { + name: "terminal-4096".into(), + kind: GraphKind::TerminalPrefill, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 99, + batch_capacity: 1, + token_capacity: 4096, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + for g in &mut graphs { + if g.kind == GraphKind::TerminalPrefill { + g.estimated_duration_ns = 0; + } + } + s.measured_graph_durations(&graphs).unwrap(); + // 1024 > 512 (the largest non-terminal capacity), so completion requires TerminalPrefill(4096); + // even when deferred_prefill forces a 512-token tail onto TerminalPrefill(4096), discovery must + // use terminal_prefill_catalog rather than prefill_catalog. + let handle = add(&mut s, 1, 512, 32); + s.request_mut(handle).unwrap().deferred_prefill = true; + initialize(&mut s, handle); + let plan = s.plan().unwrap(); + assert_eq!(plan.kind, GraphKind::TerminalPrefill); + assert_eq!(plan.token_capacity, 4096); + + // Mixed service_rates and optimistic_tokens must apply adaptive_verification_alpha. + let mut m = mixed_engine(2, true, &[(2, 8, 512, 10 * MS)]); + m.configure_policy(PolicyConfig { + adaptive_verification_alpha: 2.0, + ..Default::default() + }) + .unwrap(); + let d = add(&mut m, 1, 64, 1024); + ready(&mut m, &[d]); + for _ in 0..32 { + m.request_mut(d).unwrap().acceptance.observe(0, 7, 3, true, None); + } + let req = m.request(d).unwrap(); + let opt = m.optimistic_tokens(req, 8); + let expected_opt = super::rounds::forecast_tokens(&m.powered_curve(req, true), 8); + assert!((opt - expected_opt).abs() < 1e-12, "opt={opt} != expected={expected_opt}"); +} diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index c00f506ed..c37121640 100644 --- a/helios/src/scheduler/service.rs +++ b/helios/src/scheduler/service.rs @@ -191,30 +191,31 @@ impl RequestScheduler { consider(GraphKind::Snapshot, batch, 1, 0.0, true); } } else if prefill { + let start = request.consumed_tokens as usize; let catalog = if request.prompt_logprobs { &self.scored_prefill_catalog } else { &self.prefill_catalog }; - let terminal_only = self.prefill_requires_terminal_completion(request, cut); + let terminal_only = self.prefill_requires_terminal_completion_from(request, start, cut); for &capacity in catalog { - let work = self.prefill_work_through(request, capacity, cut); + let work = self.prefill_work_from(request, start, capacity, cut); if work == 0 { continue; } - let first_output = - request.consumed_tokens + work as u64 == request.prompt_tokens as u64; - let kind = self.resolve_prefill_kind(request, capacity, work, cut); + let first_output = start + work == request.prompt_tokens; + let kind = self.resolve_prefill_kind_from(request, start, capacity, work, cut); if terminal_only && kind == GraphKind::Prefill { continue; } - consider( - kind, - 1, - capacity, - work as f64 + f64::from(first_output), - false, - ); + if let Some(ns) = self + .costs + .prefill_duration(kind, capacity, work, request.consumed_tokens) + .filter(|n| *n > 0) + { + let per_ms = 1e6 / ns as f64; + token_rate = token_rate.max((work as f64 + f64::from(first_output)) * per_ms); + } } } else { let mut curve = None; @@ -247,6 +248,7 @@ impl RequestScheduler { } } if !policy::terminal_cleanup(request) { + let mut mixed_curve = None; for &(batch, width, capacity) in &self.mixed_catalog { let Some(ns) = self .costs @@ -256,24 +258,35 @@ impl RequestScheduler { continue; }; let per_ms = 1e6 / ns as f64; - if prefill && !request.prompt_logprobs && !request.deferred_prefill { - let work = self.prefill_work_through(request, capacity, cut); + if prefill + && !request.prompt_logprobs + && !request.deferred_prefill + && !self.prefill_requires_terminal_completion_from( + request, + request.consumed_tokens as usize, + cut, + ) + { + let start = request.consumed_tokens as usize; + let work = self.prefill_work_from(request, start, capacity, cut); if work > 0 { - let first = - request.consumed_tokens + work as u64 == request.prompt_tokens as u64; + let first = start + work == request.prompt_tokens; token_rate = token_rate.max((work as f64 + f64::from(first)) * per_ms); } - } else if request.generated_tokens > 0 + } else if !prefill + && request.generated_tokens > 0 && request.generated_tokens < request.max_new_tokens { let tokens = self.speculative_tokens(request, width); if tokens > 0 { - token_rate = token_rate.max( - request - .acceptance - .expected_tokens(tokens) - * per_ms, - ); + let expected = if self.speculative_widths.is_empty() { + 1.0 + } else { + let curve = mixed_curve + .get_or_insert_with(|| self.powered_curve(request, false)); + super::rounds::forecast_tokens(curve, tokens) + }; + token_rate = token_rate.max(expected * per_ms); delivery_rate = delivery_rate.max(per_ms); } } diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 6ca976e5d..ca7e1bbf0 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -1308,7 +1308,14 @@ fn worker_observes_prefill_decode_and_prerequisite_timings() { ]; frame.timing.wall_ns = 350; worker.complete(kind, frame).unwrap(); - assert_eq!(worker.scheduler.estimated_duration_ns(&step), Some(600)); + if kind == GraphKind::Prefill { + // The 13-token tail (200 ns) inside capacity 64 (seeded 1000 ns at full fill) + // fits its own fill-ratio regime instead of averaging into the full-chunk cost. + let est = worker.scheduler.estimated_duration_ns(&step).unwrap(); + assert!((195..=210).contains(&est), "partial prefill estimate={est}"); + } else { + assert_eq!(worker.scheduler.estimated_duration_ns(&step), Some(600)); + } let metrics = fixture.metrics.snapshot(false); assert_eq!(metrics.verification_drafts, 0); assert_eq!( diff --git a/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index 72bb0dab4..a276ed64b 100644 --- a/scripts/scheduling_sim/utility.py +++ b/scripts/scheduling_sim/utility.py @@ -6,9 +6,11 @@ from dataclasses import dataclass, replace from math import exp, expm1, isfinite, log, log1p -from .model import Action, Graph, Lane, Value, View +from .model import Action, Graph, Lane, Value, View, expected_output from .scheduler import candidates +COALESCING_HORIZON_TOKENS = 64.0 + @dataclass(frozen=True) class UtilityConfig: @@ -17,9 +19,15 @@ class UtilityConfig: adaptation_ms: float age_price: float = 0.0 rate_history: str = "exponential" + coalescing_horizon_tokens: float = COALESCING_HORIZON_TOKENS def __post_init__(self): - if any(not isfinite(v) or v < 0 for v in (self.token_fairness, self.delivery_fairness, self.age_price)): + if any(not isfinite(v) or v < 0 for v in ( + self.token_fairness, + self.delivery_fairness, + self.age_price, + self.coalescing_horizon_tokens, + )): raise ValueError("fairness values must be finite and nonnegative") if not isfinite(self.adaptation_ms) or self.adaptation_ms <= 0: raise ValueError("price adaptation time must be positive and finite") @@ -118,6 +126,8 @@ def __init__(self, value: Value, config: UtilityConfig): self._references: dict[str, float] = {} self._token_normalizers: set[str] = set() self._delivery_normalizers: set[str] = set() + self._coalesce_token: dict[str, float] = {} + self._initial_prefill: dict[str, int] = {} self._mask_unknown_prices = False def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = 0.0, @@ -129,6 +139,11 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = self._references = {name: ref for name, ref in self._references.items() if name in names} self._token_normalizers.clear() self._delivery_normalizers.clear() + self._coalesce_token.clear() + self._initial_prefill = {name: total for name, total in self._initial_prefill.items() if name in names} + for view in views: + if view.remaining_prefill > 0 and view.name not in self._initial_prefill: + self._initial_prefill[view.name] = view.remaining_prefill self._mask_unknown_prices = mask_unknown_prices self.ages.clear() measured = catalog if known_graphs is None else tuple(g for g in catalog if g.name in known_graphs) @@ -171,15 +186,67 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = has_delivery or not mask_unknown_prices): self.ages[view.name] = (now_ms - view.last_service_ms, reference_wait, view.weight) + raw_coalesce: dict[str, float] = {} + decoders = [v for v in views if not v.remaining_prefill] + prefillers = [v for v in views if v.remaining_prefill and v.output_budget > 1] + if decoders and prefillers and self.config.coalescing_horizon_tokens > 0: + decode_graphs = [g for g in measured if g.decode_capacity > 0 and not g.prefill_capacity] + k = len(decoders) + q = len(prefillers) + if decode_graphs: + def best_decode_rate(n_streams: int) -> float: + best = 0.0 + for graph in decode_graphs: + served = min(n_streams, graph.decode_capacity) + mean_out = sum( + min(v.output_budget, expected_output(v.acceptance, graph.width)) + for v in decoders + ) / k + best = max(best, served * mean_out / graph.duration_ms) + return best + + base_rate = best_decode_rate(k) + best_surplus_per_horizon = 0.0 + if base_rate > 0: + for added in range(1, q + 1): + next_rate = best_decode_rate(k + added) + if next_rate > base_rate: + multiplier = ((k + added) / added) * (1.0 - base_rate / next_rate) + best_surplus_per_horizon = max( + best_surplus_per_horizon, self.value.decode_value * multiplier + ) + if best_surplus_per_horizon > 0: + peer_budget = min(v.output_budget for v in decoders) + for view in prefillers: + horizon = min( + self.config.coalescing_horizon_tokens, + float(view.output_budget - 1), + float(peer_budget), + ) + if horizon > 0: + initial_prefill = max( + self._initial_prefill.get(view.name, view.remaining_prefill), + view.remaining_prefill, + ) + raw_coalesce[view.name] = ( + view.weight * best_surplus_per_horizon * horizon + / initial_prefill + ) self.log_scale = max([0.0, log(self.value.decode_value), log(self.config.age_price) if self.config.age_price else float("-inf"), + *(log(value) for value in raw_coalesce.values() if value > 0), *(price.log_price - log(price.maximum_rate) for row in self.prices.values() for price in (row.tokens, row.deliveries) if price is not None)]) + if raw_coalesce: + unit = exp(-self.log_scale) + self._coalesce_token = {name: unit * value for name, value in raw_coalesce.items()} def lane_value(self, lane: Lane) -> float: prices = self.prices[lane.name] work = exp(-self.log_scale) * lane.useful_work(self.value) + if lane.prefill and lane.name in self._coalesce_token: + work += self._coalesce_token[lane.name] * lane.prefill if prices.tokens is not None and (not self._mask_unknown_prices or lane.name in self._token_normalizers): work += prices.tokens.value(lane.prefill + lane.expected_output, self.log_scale) return work diff --git a/scripts/scheduling_sim/workloads.py b/scripts/scheduling_sim/workloads.py index 7ebec17ab..2536259c8 100644 --- a/scripts/scheduling_sim/workloads.py +++ b/scripts/scheduling_sim/workloads.py @@ -47,4 +47,9 @@ def decode(name, accepted=7, output=128, **kwargs): "short_arrival": [prefill("long"), prefill("short", 64, arrival_ms=1)], "short_decode": [decode("long", output=2048), decode("short", output=3)], "continuous_decode": [prefill("p"), decode("d", output=4096)], + "burst_four": [Request(f"b{i}", 4096, 256) for i in range(4)], + "burst_eight": [Request(f"b{i}", 4096, 256) for i in range(8)], + "burst_eight_8k": [Request(f"b{i}", 8192, 256) for i in range(8)], + "burst_four_low": [Request(f"b{i}", 4096, 256, acceptance=(0.0,) * 7) for i in range(4)], + "burst_eight_low": [Request(f"b{i}", 4096, 256, acceptance=(0.0,) * 7) for i in range(8)], } diff --git a/tests/test_scheduling_utility.py b/tests/test_scheduling_utility.py index b6969ebec..1a634f1e5 100644 --- a/tests/test_scheduling_utility.py +++ b/tests/test_scheduling_utility.py @@ -358,3 +358,62 @@ def test_age_continuation_satisfies_the_reference_poisson_equation(): def test_invalid_preferences_are_rejected(config): with pytest.raises(ValueError): UtilityConfig(*config) + + +def test_simultaneous_burst_coalesces_prefills_into_full_decode_batches(): + # Simultaneous B=8 burst on the synthetic catalog must coalesce prefills into + # higher-utilization decode batches and reduce max TTFT and sub-batch rounds. + base_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)) + coal_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + base = run(workloads()["burst_eight"], catalog(), Value(64), scheduler=base_policy, horizon_ms=15000) + coal = run(workloads()["burst_eight"], catalog(), Value(64), scheduler=coal_policy, horizon_ms=15000) + assert coal.summary["unfinished"] == 0 + base_ttft = max(row["ttft_ms"] for row in base.requests) + coal_ttft = max(row["ttft_ms"] for row in coal.requests) + assert coal_ttft < base_ttft * 0.85, f"expected >=15% max TTFT reduction: {coal_ttft} vs {base_ttft}" + assert coal.trace[-1]["end_ms"] < base.trace[-1]["end_ms"] * 0.95 + base_sub = sum(len(event["lanes"]) < 8 for event in base.trace if event["decode_capacity"]) + coal_sub = sum(len(event["lanes"]) < 8 for event in coal.trace if event["decode_capacity"]) + assert coal_sub <= base_sub // 2, f"coal_sub={coal_sub}, base_sub={base_sub}" + # Under low speculative acceptance, coalescing also reduces max TTFT and sub-batch rounds. + low_base_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)) + low_coal_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + low_base = run(workloads()["burst_eight_low"], catalog(), Value(64), scheduler=low_base_policy, horizon_ms=15000) + low_coal = run(workloads()["burst_eight_low"], catalog(), Value(64), scheduler=low_coal_policy, horizon_ms=15000) + assert low_coal.summary["unfinished"] == 0 + assert max(row["ttft_ms"] for row in low_coal.requests) < max(row["ttft_ms"] for row in low_base.requests) + low_base_sub = sum(len(event["lanes"]) < 8 for event in low_base.trace if event["decode_capacity"]) + low_coal_sub = sum(len(event["lanes"]) < 8 for event in low_coal.trace if event["decode_capacity"]) + assert low_coal_sub < low_base_sub, f"low_coal_sub={low_coal_sub}, low_base_sub={low_base_sub}" + + +def test_coalescing_surplus_vanishes_at_saturated_batch_and_single_token_budget(): + graphs = ( + Graph("prefill-512", 10.0, prefill_capacity=512), + Graph("decode-b4", 20.0, decode_capacity=4), + Graph("decode-b8", 45.0, decode_capacity=8), + ) + decoders = [View(f"d{i}", 0, 256, ()) for i in range(4)] + # Saturated batch (4/20 > 5/45) with a single queued prefill yields zero coalescing bonus. + policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + policy.prepare([*decoders, View("p0", 512, 256, ())], graphs) + assert not policy._coalesce_token + + # Single-token output budget finishes on prefill and never enters decode, so bonus is zero. + graphs_growing = ( + Graph("prefill-512", 10.0, prefill_capacity=512), + Graph("decode-b1", 20.0, decode_capacity=1), + Graph("decode-b2", 22.0, decode_capacity=2), + ) + policy.prepare([View("d0", 0, 256, ()), View("p0", 512, 1, ())], graphs_growing) + assert not policy._coalesce_token + + # With 4 queued prefills and a faster B=8 bucket (8/32 > 4/20), multi-step K->K+m activates. + graphs_jump = ( + Graph("prefill-512", 10.0, prefill_capacity=512), + Graph("decode-b4", 20.0, decode_capacity=4), + Graph("decode-b8", 32.0, decode_capacity=8), + ) + prefills = [View(f"p{i}", 512, 256, ()) for i in range(4)] + policy.prepare([*decoders, *prefills], graphs_jump) + assert all(policy._coalesce_token.get(p.name, 0.0) > 0.0 for p in prefills) diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index 3ddd189e4..2af7e88f3 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -544,6 +544,14 @@ def run_aux(test): " request: &LiveRequest,\n" " cut: Option,\n" " ) -> bool {\n" + " self.prefill_requires_terminal_completion_from(request, Self::prefill_cursor(request), cut)\n" + " }\n\n" + " pub(super) fn prefill_requires_terminal_completion_from(\n" + " &self,\n" + " request: &LiveRequest,\n" + " start: usize,\n" + " cut: Option,\n" + " ) -> bool {\n" " if request.prompt_logprobs || self.terminal_prefill_catalog.is_empty() {\n" " return false;\n" " }\n" @@ -551,7 +559,7 @@ def run_aux(test): " .unwrap_or(request.prompt_tokens)\n" " .min(request.prefill_limit())\n" " .min(request.prompt_tokens);\n" - " let remaining = next_stop.saturating_sub(request.consumed_tokens as usize);\n" + " let remaining = next_stop.saturating_sub(start);\n" " if remaining == 0 {\n" " return false;\n" " }\n" @@ -559,7 +567,7 @@ def run_aux(test): " let Some(&max_terminal) = self.terminal_prefill_catalog.last() else {\n" " return false;\n" " };\n" - " return self.prefill_work_through(request, max_terminal, cut) >= remaining;\n" + " return self.prefill_work_from(request, start, max_terminal, cut) >= remaining;\n" " }", " if self.terminal_prefill_catalog.binary_search(&capacity).is_err() {\n" " return GraphKind::Prefill;\n" @@ -575,6 +583,14 @@ def run_aux(test): " request: &LiveRequest,\n" " cut: Option,\n" " ) -> bool {\n" + " self.prefill_requires_terminal_completion_from(request, Self::prefill_cursor(request), cut)\n" + " }\n\n" + " pub(super) fn prefill_requires_terminal_completion_from(\n" + " &self,\n" + " request: &LiveRequest,\n" + " start: usize,\n" + " cut: Option,\n" + " ) -> bool {\n" " if request.prompt_logprobs || self.terminal_prefill_catalog.is_empty() {\n" " return false;\n" " }\n" @@ -582,7 +598,7 @@ def run_aux(test): " .unwrap_or(request.prompt_tokens)\n" " .min(request.prefill_limit())\n" " .min(request.prompt_tokens);\n" - " let remaining = next_stop.saturating_sub(request.consumed_tokens as usize);\n" + " let remaining = next_stop.saturating_sub(start);\n" " if remaining == 0 {\n" " return false;\n" " }",