diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 2822195e1..4d86bdf90 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -277,8 +277,16 @@ no measured decoder is active); `A_first` is elapsed milliseconds from `first_output_wait_ns` and `frac` is `1` on prompt completion or `work / initial_prefill` on partial chunks, carried through prerequisite and two-stage continuation scoring (`Init`, `Restore`, `Vision`, `Snapshot`). See -`scheduling-utility.md` for wait-clock preservation across anchor splits, -readmission anchoring, and inertness conditions. +`scheduling-utility.md` for anchor-split preservation, readmission anchoring, +and inertness conditions. Under an active age-priced stream +(`decode_age_price > 0`), non-terminal `Prefill` chunks without a checkpoint +capture also preserve `first_output_wait_ns` across chunks whenever the +request's uncached prompt at admission fits in one eligible prefill graph +(`TerminalPrefill` on `TERMINAL_PREFILL` cores). When such a prompt holds +deferred prefill state and a `TerminalPrefill` chunk lands on an interior +checkpoint cut before `prompt_tokens`, `first_output_value` credits the +reconciled segment since `prefix_tokens` (`(end - prefix_tokens) / initial_prefill`) +while token-work credit stays proportional to that chunk's tokens. All values in one decision share a positive scaling factor to keep large prices representable. `ScheduledPlan::selection_value_rate()` exposes the scaled score; @@ -318,17 +326,21 @@ prompt row. When no quote fails, estimated and submitted work agree. Storage shortage can change which cuts fit the work budget, so the estimate and quoted selection can differ in either direction. If the quoted work differs from the winning estimate, an -ordinary prefill or mixed plan advances toward the quoted cut up to the catalog -maximum and uses the smallest catalog capacity covering that work, with duration -and value recomputed. Mixed plans resize only the prompt capacity among shapes +ordinary mixed plan—or a pure prefill plan with `age_price == 0` or required +terminal completion—advances toward the quoted cut up to the catalog maximum, +whereas an age-priced non-terminal prefill caps growth at the winning +candidate's capacity; both paths use the smallest eligible catalog capacity +covering that work (restricting `deferred_prefill` requests to +`TERMINAL_PREFILL` capacities), with duration and value recomputed. Mixed plans +resize only the prompt capacity among shapes with the same batch capacity and decode width; decode lanes retain their token counts. If a required lookup is unavailable, it retains the winning candidate and clips work to that candidate's capacity. Refresh and discovery plans retain their capacities and clip work to fit. Atomic image spans, feature windows, and prompt length also restrict logical work. A graph with 64 useful prompt tokens earns 64 prompt units and at most one output token, regardless of physical capacity. -Apart from the natural-fit restriction on unmeasured pure prefill graphs -described below, candidate scoring has no smallest-fitting-shape filter, +Apart from the unmeasured pure prefill discovery and interpolated exploration +rules described below, candidate scoring has no smallest-fitting-shape filter, duration ceiling, forced oldest-request filter, or per-chunk prefill deadline or lateness penalty in the common `-T/2 * sum c_j` waiting sum (waiting prompts with remaining output budget participate only through the positive first-output @@ -343,9 +355,13 @@ penultimate chunk leaving at most the tail-protection window, while earlier chunks run `PREFILL`. Committing a non-terminal `PREFILL` chunk at a capacity present in the terminal catalog marks the request as holding deferred continuation state until a `TERMINAL_PREFILL` chunk completes. While deferred -state is active, the scheduler excludes the request from `MIXED` graphs and -suppresses checkpoint and early-retirement snapshot capture so incomplete -continuation state is never published. Checkpoint cut budgeting prices +state is active, the scheduler excludes the request from `MIXED` graphs and from +prefill capacities absent from `TERMINAL_PREFILL`, and suppresses checkpoint and +early-retirement snapshot capture so incomplete continuation state is never +published. While active age-priced streams exist, requests whose remaining work +fits inside the largest terminal capacity still allow legal non-terminal +`PREFILL` chunks rather than requiring one monolithic `TERMINAL_PREFILL` step. +Checkpoint cut budgeting prices non-terminal and terminal chunks using their separate measured durations with sibling fallback when only one operation is measured. @@ -478,12 +494,25 @@ Host dispatch, completion delivery, and polling time do not enter a graph's cost Missing or zero device intervals neither change an estimate nor make it fresh. Pure prefill exploration restricts unmeasured graphs (`PREFILL`, -`TERMINAL_PREFILL`, and `SCORED_PREFILL`) to the natural-fit capacity: the -smallest registered catalog capacity that achieves the maximum single-step -token work through the next checkpoint cut, atomic span, or prompt endpoint -(respecting terminal-completion requirements). Smaller unmeasured prefill -shapes do not preempt larger fitting graphs during cold discovery, and larger -padded unmeasured shapes that consume no additional tokens are excluded. +`TERMINAL_PREFILL`, and `SCORED_PREFILL`) to the natural-fit capacity when no +active age-priced streams exist: the smallest registered catalog capacity that +achieves the maximum single-step token work through the next checkpoint cut, +atomic span, or prompt endpoint (respecting terminal-completion requirements). +Smaller unmeasured prefill shapes do not preempt larger fitting graphs during +cold discovery, and larger padded unmeasured shapes that consume no additional +tokens are excluded. When active age-priced streams (decoding, resume, or +terminal cleanup) exist and a measured sibling (`PREFILL` or `TERMINAL_PREFILL`) +or strictly larger measured peer plus a positive lower floor (a smaller measured +prefill peer or the fastest measured decode step) is available, unmeasured +pure-prefill capacities up to the natural fit compete by `ValueRate` using that +positive interpolated GPU estimate instead of zero-duration discovery priority. +Their first execution still drains the queue (`!is_fresh`), commits as +`TimingOrigin::Discovery` without earning refresh credit, and records the actual +GPU replay duration in `ActionCosts`. On `TERMINAL_PREFILL` catalogs, requests +whose remaining work fits inside the largest terminal capacity still allow +legal non-terminal `PREFILL` chunks leaving more than the tail-protection window +while active age-priced streams exist, while keeping non-terminal-catalog shapes +excluded whenever `deferred_prefill` is active. Measured prefill graphs of every capacity remain eligible according to their observed costs and funded timing refresh. @@ -620,7 +649,9 @@ owned through their last submitted fence. 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, +land on a checkpoint cut, and only when no active age-priced decoding, resume, +or terminal-cleanup stream exists so active decoders re-compete with actual +completion feedback after every prefill chunk. 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 @@ -640,11 +671,11 @@ estimates retained for dispatch ranking. Pricing skips unmeasured capacities that consume no additional tokens over a smaller capacity, and unmeasured capacities other than the chunk's pricing capacity: the smallest catalog capacity covering the tokens remaining before the chunk's limit, falling back -to the largest catalog capacity when none does. Pure prefill dispatch discovers -only the natural-fit capacity, and an atomic span can make the natural fit -smaller than the pricing capacity. An unmeasured pricing capacity that consumes -additional tokens leaves the prefill cost unknown, applying the unknown-cost -anchor and extra-cut rules in +to the largest catalog capacity when none does. Pure prefill dispatch follows +the natural-fit exploration limits in [Duration estimates](#duration-estimates), +and an atomic span can make the natural fit smaller than the pricing capacity. +An unmeasured pricing capacity that consumes additional tokens leaves the +prefill cost unknown, applying the unknown-cost anchor and extra-cut rules in [exact endpoint capture](core-design.md#exact-endpoint-capture). Productive completed decode earns the same fraction of measured time for a distinct terminal capture. There is no fixed capture count or concurrency-based snapshot diff --git a/docs/scheduling-theory.md b/docs/scheduling-theory.md index 180e0d8ce..39571c615 100644 --- a/docs/scheduling-theory.md +++ b/docs/scheduling-theory.md @@ -92,9 +92,11 @@ preference from hardware cost or select a production default. All pure prefill, pure decode, and available mixed graphs compete on this score. No duration ceiling, prefill size preference, or breadth-before-depth rule -precedes it. A graph consuming 64 useful prompt tokens earns 64 prefill units -whether its capacity is 64 or 4096. Inactive rows and rejected drafts earn zero. -Completing prefill emits one first token, counted once in `D_i`. +precedes it (cold discovery of unmeasured pure-prefill shapes follows +[scheduling-runtime-design.md](scheduling-runtime-design.md#duration-estimates)). +A graph consuming 64 useful prompt tokens earns 64 prefill units whether its +capacity is 64 or 4096. Inactive rows and rejected drafts earn zero. Completing +prefill emits one first token, counted once in `D_i`. If conditional acceptance at draft position `j` is `q_ij`, a verification width `k` has expected output, before EOS truncation, @@ -557,6 +559,19 @@ earn or spend neither exploration allowance. Measured costs remain available aft This option varies initial discovery independently of the operational mean and subsequent remeasurement policy. +The `initial_discovery = "interpolated"` alternative preserves `native` discovery +whenever `age_price == 0` or no active decoding stream is resident. When +`age_price > 0` with active decoding streams, it estimates unmeasured pure-prefill +capacities at or below natural fit by linear interpolation between the nearest +measured smaller pure-prefill peer (or the fastest measured decode duration as a +zero-token floor) and the nearest strictly larger measured pure-prefill peer, +clamping non-monotonic timings to the larger peer. Interpolated unmeasured prefill +candidates compete on value rate without polluting measured service-price +normalizers, execute as bootstrap when selected (never displaced by funded stale +refresh and neither earning nor spending exploration allowance), and match the +Helios interpolated prefill-discovery rule in +[the scheduling runtime design](scheduling-runtime-design.md). + Funded policies start with zero credit. A valid ordinary completion earns `alpha / (1 - alpha)` times its elapsed duration, capped at 5 ms by default, with `alpha = 0.02`. A probe requires the full cap of credit, then pays its diff --git a/helios/README.md b/helios/README.md index b96e10e4e..41f91e8b7 100644 --- a/helios/README.md +++ b/helios/README.md @@ -282,8 +282,9 @@ subranges into a free host frame, enqueues asynchronous uploads and graph execution, records a production event, and queues the completion transfer on the copy stream behind that event. Omitted input ranges preserve device state. `poll` returns ordered `FrameCompletion` records after transfer completion and -then permits frame reuse. Only ordinary decode and complete speculative -generation can share the two-frame window; other operations drain it. A third +then permits frame reuse. Only ordinary decode, complete speculative generation, and non-terminal +`PREFILL` without active age-priced streams (or checkpoint and completion +barriers) can share the two-frame window; other operations drain it. A third submission receives backpressure; a grammar submission requires an empty window and blocks further submissions until its completion is consumed. The direct executor has no Python calls or per-step CUDA allocation. @@ -422,8 +423,12 @@ the cost becomes stale but remains available for selection. The next valid observation replaces the stale estimate. Tensor-parallel observations use the maximum positive rank interval, with measured embedding-readiness waits subtracted when available. Host delays and queue wait do not enter graph estimates. An -unmeasured candidate ranks ahead of every measured candidate; unmeasured -candidates compete among themselves by expected useful value. Both +unmeasured candidate with no duration estimate ranks ahead of every measured +candidate and competes with other indeterminate candidates by expected useful +value; when active age-priced streams exist and measured GPU timings provide a +sibling or bracketing estimate, unmeasured pure-prefill capacities up to the +natural fit instead compete by interpolated `ValueRate` while still draining on +their first execution. Both unmeasured and stale physical dispatches require an empty queue and completion before another submission. When multiple packed speculative shapes cover a `(batch, width)` duration lookup, Helios uses the minimum positive measured diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index e23c44914..c65da9953 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -659,6 +659,7 @@ pub struct RequestScheduler { speculative_catalog: Vec<(usize, Vec)>, prefill_catalog: Vec, terminal_prefill_catalog: Vec, + terminal_prefill_window: usize, scored_prefill_catalog: Vec, mixed_catalog: Vec<(usize, usize, usize)>, forecasts: rounds::Forecasts, @@ -753,6 +754,7 @@ impl RequestScheduler { speculative_catalog: Default::default(), prefill_catalog: prefill_capacities(limits.prefill_chunk_size).collect(), terminal_prefill_catalog: Vec::new(), + terminal_prefill_window: 0, scored_prefill_catalog: Vec::new(), mixed_catalog: Vec::new(), forecasts, @@ -803,6 +805,7 @@ impl RequestScheduler { ); } self.prefill_catalog = catalog; + self.recompute_terminal_prefill_window(); Ok(()) } @@ -837,23 +840,29 @@ impl RequestScheduler { ); } self.terminal_prefill_catalog = catalog; + self.recompute_terminal_prefill_window(); Ok(()) } + fn recompute_terminal_prefill_window(&mut self) { + self.terminal_prefill_window = if self.terminal_prefill_catalog.is_empty() { + 0 + } else { + self.prefill_catalog + .iter() + .copied() + .filter(|capacity| self.terminal_prefill_catalog.binary_search(capacity).is_err()) + .max() + .unwrap_or(0) + }; + } + pub(super) fn is_non_terminal_prefill(&self, kind: GraphKind, capacity: usize) -> bool { kind == GraphKind::Prefill && self.terminal_prefill_catalog.binary_search(&capacity).is_ok() } pub(super) fn terminal_prefill_window(&self) -> usize { - if self.terminal_prefill_catalog.is_empty() { - return 0; - } - self.prefill_catalog - .iter() - .copied() - .filter(|capacity| self.terminal_prefill_catalog.binary_search(capacity).is_err()) - .max() - .unwrap_or(0) + self.terminal_prefill_window } pub(super) fn prefill_cursor(request: &LiveRequest) -> usize { @@ -890,7 +899,7 @@ impl RequestScheduler { let needs_terminal = end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window); if self.terminal_prefill_catalog.binary_search(&capacity).is_err() { - return if request.deferred_prefill && needs_terminal { + return if request.deferred_prefill { GraphKind::TerminalPrefill } else { GraphKind::Prefill @@ -948,6 +957,70 @@ impl RequestScheduler { .is_ok() } + /// Whether no legal non-terminal `Prefill` capacity can advance `request` from `start`. + /// Terminal-capable `Prefill` shapes absent from `terminal_prefill_catalog` remain legal + /// when `!request.deferred_prefill`, alongside terminal-catalog chunks that stop before + /// the tail-protection window and `next_stop`. + pub(super) fn prefill_must_complete_terminally_from( + &self, + request: &LiveRequest, + start: usize, + cut: Option, + ) -> bool { + if !self.prefill_requires_terminal_completion_from(request, start, cut) { + return false; + } + let catalog = if request.deferred_prefill { + &self.terminal_prefill_catalog + } else { + &self.prefill_catalog + }; + let limit = if request.deferred_prefill { 0 } else { self.terminal_prefill_window }; + for &capacity in catalog { + let work = self.prefill_work_from(request, start, capacity, cut); + if work == 0 { + continue; + } + if self.resolve_prefill_kind_from(request, start, capacity, work, cut) + == GraphKind::Prefill + { + return false; + } + if capacity >= limit { + return true; + } + } + true + } + + pub(super) fn has_active_age_priced_stream(&self) -> bool { + self.slots.iter().filter_map(|s| s.request.as_ref()).any(|r| { + if policy::terminal_cleanup(r) { + self.policy.terminal_age_price > 0.0 + } else { + self.policy.decode_age_price > 0.0 + && matches!(r.phase, RequestPhase::Decode | RequestPhase::Resume) + } + }) + } + + pub(super) fn prefill_requires_terminal_completion_for_age( + &self, + request: &LiveRequest, + cut: Option, + age_price: f64, + ) -> bool { + if age_price > 0.0 { + self.prefill_must_complete_terminally_from( + request, + Self::prefill_cursor(request), + cut, + ) + } else { + self.prefill_requires_terminal_completion(request, cut) + } + } + pub fn snapshot_slot(&self, snapshot: SnapshotId) -> StateSlotId { StateSlotId((1 + self.limits.max_active * self.execution_rows()) as u32 + snapshot.0) } @@ -1112,6 +1185,9 @@ impl RequestScheduler { } fn prefill_step_requires_feedback(&self, plan: &ScheduledPlan) -> bool { + if self.has_active_age_priced_stream() { + return true; + } if plan .checkpoint_plans .iter() diff --git a/helios/src/scheduler/cost.rs b/helios/src/scheduler/cost.rs index 023713477..c31539568 100644 --- a/helios/src/scheduler/cost.rs +++ b/helios/src/scheduler/cost.rs @@ -685,6 +685,93 @@ impl ActionCosts { self.prefill_entry(kind, capacity).flatten() } + /// Positive duration estimate for an unmeasured pure-prefill capacity derived + /// strictly from already-measured GPU durations: first a measured sibling + /// (`Prefill` <-> `TerminalPrefill`) at the same capacity, else linear + /// interpolation between the nearest measured smaller peer (or the fastest + /// measured decode step as a forward-pass floor) and the nearest measured + /// strictly larger peer. Returns `None` when no larger measured peer or + /// positive floor exists. + pub fn interpolated_prefill_duration( + &self, + kind: GraphKind, + capacity: usize, + work: usize, + start_position: u64, + ) -> Option { + let sibling = match kind { + GraphKind::Prefill => Some(GraphKind::TerminalPrefill), + GraphKind::TerminalPrefill => Some(GraphKind::Prefill), + GraphKind::ScoredPrefill => None, + _ => return None, + }; + if let Some(sib) = sibling + && let Some(pred) = self.prefill_predictor(sib, capacity) + { + return Some(pred.predict(work, start_position).max(1)); + } + let mut lo: Option<(usize, bool, u64)> = None; + let mut hi: Option<(usize, bool, u64)> = None; + let mut decode_floor: Option = None; + for (key, estimate) in &self.entries { + if estimate.nanos == 0 { + continue; + } + if matches!(key.kind, GraphKind::Decode | GraphKind::Speculative) { + decode_floor = Some(decode_floor.map_or(estimate.nanos, |f| f.min(estimate.nanos))); + continue; + } + if key.batch != 1 || key.tokens == capacity { + continue; + } + if key.kind != kind && Some(key.kind) != sibling { + continue; + } + let same_kind = key.kind == kind; + let upper = key.tokens > capacity; + let closer = |a: usize, b: usize| if upper { a < b } else { a > b }; + let target = if upper { &mut hi } else { &mut lo }; + if (*target).is_some_and(|(c, cur_same, _)| { + closer(c, key.tokens) || (key.tokens == c && cur_same && !same_kind) + }) { + continue; + } + let mut pred = estimate + .prefill + .as_ref() + .and_then(|model| model.predictor) + .unwrap_or_else(|| PrefillPredictor::constant(key.tokens, estimate.nanos)); + if !pred.has_deep_context() + && let Some(theta2) = self.borrowed_prefill_context_slope(key.kind, key.tokens) + { + pred = pred.with_borrowed_context_slope(theta2); + } + let full_ns = pred.predict(key.tokens, start_position); + if full_ns == 0 { + continue; + } + if (*target).is_none_or(|(c, cur_same, cur_ns)| { + closer(key.tokens, c) + || (key.tokens == c + && ((same_kind && !cur_same) || (same_kind == cur_same && full_ns < cur_ns))) + }) { + *target = Some((key.tokens, same_kind, full_ns)); + } + } + let (c_hi, _, t_hi) = hi?; + let (c_lo, t_lo) = match lo { + Some((c, _, t)) => (c, t), + None => (0, decode_floor?.min(t_hi)), + }; + if t_hi <= t_lo { + return Some(t_hi.max(1)); + } + let span = (c_hi - c_lo) as u128; + let offset = (capacity - c_lo) as u128; + let interp = u128::from(t_lo) + (u128::from(t_hi - t_lo) * offset) / span; + Some((interp.min(u128::from(u64::MAX)) as u64).max(1)) + } + fn borrowed_prefill_context_slope(&self, kind: GraphKind, capacity: usize) -> Option { let slot = prefill_kind_slot(kind)?; self.prefill_context_slopes[slot] @@ -1175,4 +1262,268 @@ mod tests { 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}"); } + + fn make_test_graph(name: &str, kind: GraphKind, batch: usize, cap: usize) -> GraphDescriptor { + GraphDescriptor { + name: name.into(), + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + } + + fn make_test_step(kind: GraphKind, batch: usize, cap: usize, tokens: usize) -> ScheduledStep { + use crate::scheduler::{RequestHandle, ScheduledLane}; + + ScheduledStep { + draft_tokens: 0, + kind, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + mixed: None, + lanes: vec![ScheduledLane { + request: RequestHandle { slot: 0, generation: 1 }, + start_position: 0, + tokens, + }], + requires_feedback: true, + } + } + + fn make_test_timing(ns: u64) -> crate::execution::ExecutionTiming { + let mut gpu_ns = [None; 16]; + gpu_ns[0] = Some(ns); + crate::execution::ExecutionTiming { gpu_ns, wall_ns: ns, queued: false, readiness: None } + } + + #[test] + fn interpolated_prefill_duration_uses_sibling_or_measured_peers() { + + let graphs = vec![ + make_test_graph("p2048", GraphKind::Prefill, 1, 2048), + make_test_graph("p4096", GraphKind::Prefill, 1, 4096), + make_test_graph("p16384", GraphKind::Prefill, 1, 16384), + make_test_graph("t2048", GraphKind::TerminalPrefill, 1, 2048), + make_test_graph("d1", GraphKind::Decode, 1, 1), + ]; + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + costs.advance_to(1_000_000_000, 30_000_000_000); + + // No measured peer or decode floor yet -> None. + assert_eq!(costs.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), None); + + // Measure 16384 (1302 ms) and decode floor (18 ms). + costs.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(1_302_000_000)); + assert_eq!(costs.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), None); + costs.observe(&make_test_step(GraphKind::Decode, 1, 1, 1), make_test_timing(18_000_000)); + let est_4k = costs.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0).unwrap(); + let expected_4k = 18_000_000 + (1_302_000_000 - 18_000_000) / 4; + assert_eq!(est_4k, expected_4k); + // Strictly lower throughput than 16384 so solo zero-age prefill still prefers 16384. + assert!(u128::from(est_4k) * 16384 > u128::from(1_302_000_000u64) * 4096); + + // Measuring sibling TerminalPrefill(2048) (240 ms) supplies both direct sibling fallback + // for Prefill(2048) and a tighter lower peer for Prefill(4096). + costs.observe(&make_test_step(GraphKind::TerminalPrefill, 1, 2048, 2048), make_test_timing(240_000_000)); + assert_eq!( + costs.interpolated_prefill_duration(GraphKind::Prefill, 2048, 2048, 0), + Some(240_000_000) + ); + let est_4k_peer = costs.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0).unwrap(); + let expected_4k_peer = 240_000_000 + (1_302_000_000 - 240_000_000) * 2048 / 14336; + assert_eq!(est_4k_peer, expected_4k_peer); + } + + #[test] + fn interpolated_prefill_duration_is_order_independent_for_same_kind_and_sibling() { + let build = |prefill_first: bool, with_lo: bool| -> ActionCosts { + let mut graphs = vec![ + make_test_graph("p4096", GraphKind::Prefill, 1, 4096), + make_test_graph("t4096", GraphKind::TerminalPrefill, 1, 4096), + make_test_graph("d1", GraphKind::Decode, 1, 1), + ]; + if prefill_first { + graphs.push(make_test_graph("p2048", GraphKind::Prefill, 1, 2048)); + graphs.push(make_test_graph("t2048", GraphKind::TerminalPrefill, 1, 2048)); + graphs.push(make_test_graph("p16384", GraphKind::Prefill, 1, 16384)); + graphs.push(make_test_graph("t16384", GraphKind::TerminalPrefill, 1, 16384)); + } else { + graphs.push(make_test_graph("t2048", GraphKind::TerminalPrefill, 1, 2048)); + graphs.push(make_test_graph("p2048", GraphKind::Prefill, 1, 2048)); + graphs.push(make_test_graph("t16384", GraphKind::TerminalPrefill, 1, 16384)); + graphs.push(make_test_graph("p16384", GraphKind::Prefill, 1, 16384)); + } + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + costs.advance_to(1_000_000_000, 30_000_000_000); + costs.observe(&make_test_step(GraphKind::Decode, 1, 1, 1), make_test_timing(18_000_000)); + costs.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(1_312_000_000)); + costs.observe( + &make_test_step(GraphKind::TerminalPrefill, 1, 16384, 16384), + make_test_timing(1_200_000_000), + ); + if with_lo { + costs.observe(&make_test_step(GraphKind::Prefill, 1, 2048, 2048), make_test_timing(250_000_000)); + costs.observe( + &make_test_step(GraphKind::TerminalPrefill, 1, 2048, 2048), + make_test_timing(210_000_000), + ); + } + costs + }; + + // Upper peer only (decode floor): same-kind must strictly beat faster sibling regardless + // of GraphDescriptor registration order. + let pf_no_lo = build(true, false); + let tf_no_lo = build(false, false); + assert_eq!( + pf_no_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + Some(341_500_000) + ); + assert_eq!( + pf_no_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + tf_no_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0) + ); + assert_eq!( + pf_no_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0), + Some(313_500_000) + ); + assert_eq!( + pf_no_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0), + tf_no_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0) + ); + + // Both lower and upper peers present with faster siblings at both boundaries. + let pf_with_lo = build(true, true); + let tf_with_lo = build(false, true); + let expected_p = 250_000_000 + (1_312_000_000 - 250_000_000) * 2048 / 14336; + let expected_t = 210_000_000 + (1_200_000_000 - 210_000_000) * 2048 / 14336; + assert_eq!( + pf_with_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + Some(expected_p) + ); + assert_eq!( + pf_with_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + tf_with_lo.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0) + ); + assert_eq!( + pf_with_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0), + Some(expected_t) + ); + assert_eq!( + pf_with_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0), + tf_with_lo.interpolated_prefill_duration(GraphKind::TerminalPrefill, 4096, 4096, 0) + ); + } + + #[test] + fn interpolated_prefill_duration_isolates_scored_prefill_and_clamps_non_monotonic_timings() { + // ScoredPrefill must never borrow same-capacity or peer timings from Prefill/TerminalPrefill. + let scored_graphs = vec![ + make_test_graph("p2048", GraphKind::Prefill, 1, 2048), + make_test_graph("t2048", GraphKind::TerminalPrefill, 1, 2048), + make_test_graph("p16384", GraphKind::Prefill, 1, 16384), + make_test_graph("t16384", GraphKind::TerminalPrefill, 1, 16384), + make_test_graph("s2048", GraphKind::ScoredPrefill, 1, 2048), + make_test_graph("s4096", GraphKind::ScoredPrefill, 1, 4096), + make_test_graph("s16384", GraphKind::ScoredPrefill, 1, 16384), + make_test_graph("d1", GraphKind::Decode, 1, 1), + ]; + let mut costs = ActionCosts::prepared(&scored_graphs, 1).unwrap(); + costs.advance_to(1_000_000_000, 30_000_000_000); + costs.observe(&make_test_step(GraphKind::Decode, 1, 1, 1), make_test_timing(18_000_000)); + costs.observe(&make_test_step(GraphKind::Prefill, 1, 2048, 2048), make_test_timing(200_000_000)); + costs.observe(&make_test_step(GraphKind::TerminalPrefill, 1, 2048, 2048), make_test_timing(210_000_000)); + costs.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(1_300_000_000)); + costs.observe(&make_test_step(GraphKind::TerminalPrefill, 1, 16384, 16384), make_test_timing(1_310_000_000)); + assert_eq!(costs.interpolated_prefill_duration(GraphKind::ScoredPrefill, 2048, 2048, 0), None); + assert_eq!(costs.interpolated_prefill_duration(GraphKind::ScoredPrefill, 4096, 4096, 0), None); + + // Once ScoredPrefill(16384) is measured, ScoredPrefill(4096) interpolates from Decode floor + // to ScoredPrefill(16384) without borrowing Prefill(2048) as a lower peer. + costs.observe(&make_test_step(GraphKind::ScoredPrefill, 1, 16384, 16384), make_test_timing(1_600_000_000)); + let expected_scored = 18_000_000 + (1_600_000_000 - 18_000_000) * 4096 / 16384; + assert_eq!( + costs.interpolated_prefill_duration(GraphKind::ScoredPrefill, 4096, 4096, 0), + Some(expected_scored) + ); + + // Non-monotonic peer timings (t_hi < t_lo and t_hi == t_lo) clamp safely to t_hi. + let mono_graphs = vec![ + make_test_graph("p2048", GraphKind::Prefill, 1, 2048), + make_test_graph("p4096", GraphKind::Prefill, 1, 4096), + make_test_graph("p16384", GraphKind::Prefill, 1, 16384), + make_test_graph("d1", GraphKind::Decode, 1, 1), + ]; + let mut inverted = ActionCosts::prepared(&mono_graphs, 1).unwrap(); + inverted.advance_to(1_000_000_000, 30_000_000_000); + inverted.observe(&make_test_step(GraphKind::Prefill, 1, 2048, 2048), make_test_timing(500_000_000)); + inverted.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(300_000_000)); + assert_eq!( + inverted.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + Some(300_000_000) + ); + + let mut equal_peers = ActionCosts::prepared(&mono_graphs, 1).unwrap(); + equal_peers.advance_to(1_000_000_000, 30_000_000_000); + equal_peers.observe(&make_test_step(GraphKind::Prefill, 1, 2048, 2048), make_test_timing(300_000_000)); + equal_peers.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(300_000_000)); + assert_eq!( + equal_peers.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + Some(300_000_000) + ); + + // Decode floor exceeding t_hi clamps cleanly to t_hi without underflow. + let mut high_floor = ActionCosts::prepared(&mono_graphs, 1).unwrap(); + high_floor.advance_to(1_000_000_000, 30_000_000_000); + high_floor.observe(&make_test_step(GraphKind::Decode, 1, 1, 1), make_test_timing(400_000_000)); + high_floor.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(250_000_000)); + assert_eq!( + high_floor.interpolated_prefill_duration(GraphKind::Prefill, 4096, 4096, 0), + Some(250_000_000) + ); + } + + #[test] + fn interpolated_prefill_duration_excludes_resume_from_decode_floor() { + let graphs = vec![ + make_test_graph("p128", GraphKind::Prefill, 1, 128), + make_test_graph("p16384", GraphKind::Prefill, 1, 16384), + make_test_graph("r1", GraphKind::Resume, 1, 1), + make_test_graph("d1", GraphKind::Decode, 1, 1), + make_test_graph("s1", GraphKind::Speculative, 1, 2), + ]; + let mut costs = ActionCosts::prepared(&graphs, 1).unwrap(); + costs.advance_to(1_000_000_000, 30_000_000_000); + costs.observe(&make_test_step(GraphKind::Prefill, 1, 16384, 16384), make_test_timing(225_000_000)); + costs.observe(&make_test_step(GraphKind::Resume, 1, 1, 1), make_test_timing(500_000)); + + // Resume runs only vocabulary projection and sampling; it must not supply a forward-pass floor. + assert_eq!(costs.interpolated_prefill_duration(GraphKind::Prefill, 128, 128, 0), None); + + // Once Decode is measured, interpolation uses the Decode floor rather than Resume. + costs.observe(&make_test_step(GraphKind::Decode, 1, 1, 1), make_test_timing(18_000_000)); + let expected_decode = 18_000_000 + (225_000_000 - 18_000_000) * 128 / 16384; + assert_eq!( + costs.interpolated_prefill_duration(GraphKind::Prefill, 128, 128, 0), + Some(expected_decode) + ); + + // Speculative steps also represent full forward passes and participate in the floor. + costs.observe(&make_test_step(GraphKind::Speculative, 1, 2, 2), make_test_timing(15_000_000)); + let expected_spec = 15_000_000 + (225_000_000 - 15_000_000) * 128 / 16384; + assert_eq!( + costs.interpolated_prefill_duration(GraphKind::Prefill, 128, 128, 0), + Some(expected_spec) + ); + } } diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index 8295ffb71..f693af5b5 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -86,6 +86,15 @@ impl RequestAccounting { } } +#[derive(Clone, Copy, Default)] +struct PrefillSlotPlan { + ready: bool, + cut: Option, + terminal_only: bool, + nat_fit_ready: bool, + nat_fit: Option, +} + #[derive(Clone, Copy)] pub(super) struct Candidate { pub draft_tokens: usize, @@ -359,19 +368,9 @@ 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 - } + fn prefill_catalog_for_terminal(&self, kind: GraphKind, terminal_only: bool) -> &[usize] { + self.prefill_catalog(if kind == GraphKind::ScoredPrefill { kind } + else if terminal_only { GraphKind::TerminalPrefill } else { GraphKind::Prefill }) } pub(super) fn prefill_work(&self, request: &LiveRequest, capacity: usize) -> usize { @@ -407,13 +406,13 @@ impl RequestScheduler { /// prefill work through `cut`, respecting atomic spans and terminal completion. /// Unmeasured pure prefill graphs only participate in cold discovery at this /// capacity so smaller unmeasured shapes do not preempt larger fitting graphs. - fn natural_fit_prefill_capacity( + fn natural_fit_prefill_capacity_for_terminal( &self, request: &LiveRequest, catalog: &[usize], cut: Option, + terminal_only: bool, ) -> Option { - let terminal_only = self.prefill_requires_terminal_completion(request, cut); let mut best: Option<(usize, usize)> = None; for &capacity in catalog { let work = self.prefill_work_through(request, capacity, cut); @@ -460,17 +459,23 @@ impl RequestScheduler { }) } - /// Whether a completed prefill stopped at an armed interior `RetentionRole::Anchor` - /// cut on a prompt that otherwise fit in one eligible prefill graph, so the wait - /// clock should carry across the forced split and boundary snapshot. + /// Whether a completed prefill chunk should carry `first_output_wait_ns` forward + /// rather than resetting it on progress. /// - /// We intentionally do not require `prefill < step.token_capacity`: once an anchor - /// caps work across every larger capacity, the scheduler always chooses the smallest - /// covering bucket, so `prefill == step.token_capacity` is expected whenever an - /// anchor coincides with a catalog capacity. When a `TerminalPrefill` chunk clears - /// `deferred_prefill` while landing on an interior anchor, `fits_single_prefill_from` - /// runs against the pre-completion `deferred_prefill` state so it checks the - /// terminal prefill catalog. + /// Preserves the wait clock in two cases: + /// (1) an armed interior `RetentionRole::Anchor` cut whose pre-chunk remainder + /// `[request.consumed_tokens, request.prompt_tokens)` fits in one eligible prefill + /// graph (carries across the forced split and boundary snapshot; we intentionally + /// do not require `prefill < step.token_capacity` because an anchor caps larger + /// capacities to the same work, and when `TerminalPrefill` clears `deferred_prefill` + /// at an interior anchor, `fits_single_prefill_from` runs against the pre-completion + /// `deferred_prefill` state so it checks the terminal prefill catalog), and + /// (2) an age-priced non-terminal `Prefill` chunk without a checkpoint capture + /// under an active age-priced stream (`decode_age_price > 0.0`) whose full uncached + /// prompt `[request.admission_reused_tokens, request.prompt_tokens)` fit in one + /// eligible prefill graph, including subsequent chunks while `deferred_prefill` is + /// set. Multi-chunk prompts exceeding max capacity at admission keep resetting on + /// chunk progress so their tail cannot jump to a large `TerminalPrefill`. pub(super) fn preserves_first_output_wait( &self, kind: GraphKind, @@ -480,18 +485,66 @@ impl RequestScheduler { prefill: u64, output: u32, ) -> bool { - kind.is_prefill() + let base_ok = kind.is_prefill() && record.status != 3 && !finished && prefill > 0 && output == 0 - && !(request.deferred_prefill && kind != GraphKind::TerminalPrefill) - && (record.consumed_tokens as usize) < request.prompt_tokens + && (record.consumed_tokens as usize) < request.prompt_tokens; + let anchor_split = !(request.deferred_prefill && kind != GraphKind::TerminalPrefill) && request.checkpoint_capture.is_some_and(|capture| { capture.role == RetentionRole::Anchor && capture.endpoint == record.consumed_tokens as u64 }) - && self.fits_single_prefill_from(request, request.consumed_tokens as usize) + && self.fits_single_prefill_from(request, request.consumed_tokens as usize); + let age_priced_chunk = request.checkpoint_capture.is_none() + && kind == GraphKind::Prefill + && self.policy.decode_age_price > 0.0 + && self.has_active_age_priced_stream() + && self.fits_single_prefill_from(request, request.admission_reused_tokens as usize); + base_ok && (anchor_split || age_priced_chunk) + } + + fn prefill_slot_state(&self, plan: &mut PrefillSlotPlan, request: &LiveRequest, age_price: f64) -> (Option, bool) { + if !plan.ready { + plan.cut = self.estimated_checkpoint_cut(request); + plan.terminal_only = self.prefill_requires_terminal_completion_for_age(request, plan.cut, age_price); + plan.ready = true; + } + (plan.cut, plan.terminal_only) + } + + #[allow(clippy::too_many_arguments)] + fn prefill_candidate_ns( + &self, plan: &mut PrefillSlotPlan, request: &LiveRequest, kind: GraphKind, capacity: usize, + work: usize, age_price: f64, predictor: Option, + last_interp: &mut Option<(usize, u64, Option)>, + ) -> Option { + if let Some(p) = predictor { + return Some(p.predict(work, request.scheduled_consumed)); + } + if !plan.nat_fit_ready { + let catalog = self.prefill_catalog_for_terminal(kind, plan.terminal_only); + plan.nat_fit = self.natural_fit_prefill_capacity_for_terminal(request, catalog, plan.cut, plan.terminal_only); + plan.nat_fit_ready = true; + } + if age_price > 0.0 && plan.nat_fit.is_some_and(|nat| capacity <= nat) { + let interp = match *last_interp { + Some((w, pos, res)) if w == work && pos == request.scheduled_consumed => res, + _ => { + let res = self.costs.interpolated_prefill_duration(kind, capacity, work, request.scheduled_consumed); + *last_interp = Some((work, request.scheduled_consumed, res)); + res + } + }; + if let Some(ns) = interp { return Some(ns); } + } + (plan.nat_fit == Some(capacity)).then_some(0) + } + + fn is_unmeasured_candidate(&self, candidate: Candidate) -> bool { + candidate.rate.duration_ns == 0 + || self.costs.observation(candidate.cost_key()).and_then(|(_, observed, _)| observed).is_none() } pub fn submission_window_available(&self, duration_ns: u64) -> bool { @@ -819,7 +872,7 @@ impl RequestScheduler { if r.consumed_tokens < r.prompt_tokens as u64 { 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 catalog = self.prefill_catalog_for_terminal(r.prefill_kind(), terminal_only); let mut natural_fit = None; for &capacity in catalog { let work = self.prefill_work_through(r, capacity, cut); @@ -832,9 +885,14 @@ impl RequestScheduler { } 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)) - != Some(capacity) + && *natural_fit.get_or_insert_with(|| { + self.natural_fit_prefill_capacity_for_terminal( + r, + catalog, + cut, + terminal_only, + ) + }) != Some(capacity) { continue; } @@ -1005,6 +1063,7 @@ impl RequestScheduler { ) { return None; } + let mut prefill_plans = [PrefillSlotPlan::default(); REQUEST_LANES]; let mask = first_offers .iter() .fold(0, |mask, (slot, _)| mask | (1 << slot)); @@ -1030,11 +1089,10 @@ impl RequestScheduler { 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) { + let mut last_interp: Option<(usize, u64, Option)> = None; + for slot in bits(mask) { + let request = self.slots[slot].request.as_ref().unwrap(); + if terminal_cleanup(request) { continue; } let Some(promoted_kind) = self.following_kind(request, kind) else { @@ -1048,23 +1106,19 @@ impl RequestScheduler { if !matches_kind { continue; } - let cut = self.estimated_checkpoint_cut(request); + let (cut, terminal_only) = self.prefill_slot_state(&mut prefill_plans[slot], request, age_price); + if following == GraphKind::Prefill && terminal_only { continue; } 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)) + if work == 0 || (matches!(following, GraphKind::Prefill | GraphKind::TerminalPrefill) + && self.resolve_prefill_kind(request, width, work, cut) != following) { continue; } - let ns = predictor.map_or(0, |p| p.predict(work, request.scheduled_consumed)); + let Some(ns) = self.prefill_candidate_ns( + &mut prefill_plans[slot], request, following, width, work, age_price, predictor, &mut last_interp, + ) else { + continue; + }; let horizon = if ns == 0 || duration_ns == 0 { 0 } else { @@ -1321,7 +1375,7 @@ impl RequestScheduler { self.lane_value_for_tokens_within(r, kind, tokens, 0, duration_ns, value) } - fn lane_value_for_tokens_within( + pub(super) fn lane_value_for_tokens_within( &self, r: &LiveRequest, kind: GraphKind, @@ -1331,12 +1385,28 @@ impl RequestScheduler { value: LaneValue, ) -> f64 { match kind { - GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => value - .prefill_within( - tokens, - r.initial_prefill_tokens(), - r.scheduled_consumed + tokens as u64 == r.prompt_tokens as u64, - ), + GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => { + let end = r.scheduled_consumed as usize + tokens; + let first_output = end == r.prompt_tokens; + let initial = r.initial_prefill_tokens(); + let mut val = value.prefill_within(tokens, initial, first_output); + if !first_output + && kind == GraphKind::TerminalPrefill + && r.deferred_prefill + && value.first_output_value > 0.0 + && tokens > 0 + && self.estimated_checkpoint_cut(r) == Some(end) + && self.fits_single_prefill_from(r, r.admission_reused_tokens as usize) + { + let reconciled = end.saturating_sub(r.prefix_tokens as usize); + if reconciled > tokens { + let old_frac = tokens as f64 / initial.max(tokens).max(1) as f64; + let new_frac = reconciled as f64 / initial.max(reconciled).max(1) as f64; + val += value.first_output_value * (new_frac - old_frac).max(0.0); + } + } + val + } GraphKind::Decode | GraphKind::Speculative => value.decode_within( self.expected_speculative_tokens(r, tokens), preceding_ns as f64 / 1e6, @@ -1349,6 +1419,44 @@ impl RequestScheduler { } } + #[allow(clippy::too_many_arguments)] + fn add_prefill_candidate( + &self, output: &mut Vec, kind: GraphKind, capacity: usize, mask: u64, + values: &[LaneValue; REQUEST_LANES], age_price: f64, prefill_plans: &mut [PrefillSlotPlan; REQUEST_LANES], + ) { + let Some(predictor) = self.costs.prefill_entry(kind, capacity) else { return; }; + let mut winner: Option<(usize, usize, u64, ValueRate)> = None; + let mut last_interp: Option<(usize, u64, Option)> = None; + for slot in bits(mask) { + let r = self.slots[slot].request.as_ref().unwrap(); + let (cut, terminal_only) = self.prefill_slot_state(&mut prefill_plans[slot], r, age_price); + if kind == GraphKind::Prefill && terminal_only { continue; } + let work = self.prefill_work_through(r, capacity, cut); + if work == 0 || self.resolve_prefill_kind(r, capacity, work, cut) != kind { continue; } + let Some(slot_ns) = self.prefill_candidate_ns( + &mut prefill_plans[slot], r, kind, capacity, work, age_price, predictor, &mut last_interp, + ) else { + continue; + }; + let rate = ValueRate::new(slot_ns, self.lane_value_for_tokens(r, kind, work, slot_ns, values[slot]), 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; }; + // `materialize` computes the authoritative `plan_requires_feedback` after + // checkpoint cuts and any prefill resizing are resolved. + output.push(Candidate { + host_lengths: None, draft_tokens: 0, packed_token_capacity: 0, kind, mask: 1u64 << slot, + batch: 1, capacity, prefill_capacity: 0, prefill_slot: None, work, duration_ns, rate, + feedback: !kind.pipelines(), + }); + } + fn add_candidate( &self, output: &mut Vec, @@ -1359,66 +1467,6 @@ impl RequestScheduler { values: &[LaneValue; REQUEST_LANES], age_price: f64, ) { - 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 - // so smaller unmeasured shapes do not preempt larger fitting graphs and - // larger padded shapes that consume no additional tokens are skipped. - if work == 0 - || resolved != kind - || (kind == GraphKind::Prefill - && self.prefill_requires_terminal_completion(r, cut)) - || (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; }; @@ -1486,6 +1534,7 @@ impl RequestScheduler { output.clear(); self.mixed_candidates(output, values, age_price, false); self.packed_round_candidates(output, values, age_price, false); + let mut prefill_plans = [PrefillSlotPlan::default(); REQUEST_LANES]; for kind in [ GraphKind::Prefill, GraphKind::TerminalPrefill, @@ -1519,7 +1568,9 @@ impl RequestScheduler { } if kind.is_prefill() { for &capacity in self.prefill_catalog(kind) { - self.add_candidate(output, kind, 1, capacity, mask, values, age_price); + self.add_prefill_candidate( + output, kind, capacity, mask, values, age_price, &mut prefill_plans, + ); } } else if kind == GraphKind::Vision { for &capacity in &self.capabilities.vision.patch_capacities { @@ -1528,9 +1579,7 @@ impl RequestScheduler { } else if kind == GraphKind::Speculative { for &(batch, ref widths) in &self.speculative_catalog { for &capacity in widths { - self.add_candidate( - output, kind, batch, capacity, mask, values, age_price, - ); + self.add_candidate(output, kind, batch, capacity, mask, values, age_price); } } } else { @@ -1670,7 +1719,7 @@ impl RequestScheduler { .then(b.mask.cmp(&a.mask)) }; let ordinary = *candidates[..ordinary_count].iter().max_by(|a, b| compare(a, b))?; - if ordinary.rate.duration_ns == 0 { + if self.is_unmeasured_candidate(ordinary) { return self.available_plan(ordinary, &values, age_price, log_scale, PlanOrigin::Discovery); } if self.refresh_ready() { @@ -1693,7 +1742,9 @@ impl RequestScheduler { let work = self.prefill_work_through(request, candidate.capacity, cut); if self.resolve_prefill_kind(request, candidate.capacity, work, cut) != GraphKind::Prefill - || self.prefill_requires_terminal_completion(request, cut) + || self.prefill_requires_terminal_completion_for_age( + request, cut, age_price, + ) { return false; } @@ -1741,7 +1792,9 @@ impl RequestScheduler { let kind_changed = candidate.kind != GraphKind::Mixed && (self.resolve_prefill_kind(request, capacity, actual_work, cut) != candidate.kind || (candidate.kind == GraphKind::Prefill - && self.prefill_requires_terminal_completion(request, cut))); + && self.prefill_requires_terminal_completion_for_age( + request, cut, age_price, + ))); if actual_work != work || kind_changed { if let Some(resized) = self.resize_prefill(candidate, request, cut, values, age_price) @@ -1782,8 +1835,18 @@ impl RequestScheduler { let prefill = catalog.filter(|&capacity| capacity >= work).min()?; (candidate.kind, candidate.capacity, prefill, work) } else { - let catalog = self.effective_prefill_catalog(request, request.prefill_kind(), cut); - let work = self.prefill_work_through(request, *catalog.last()?, cut); + let terminal_only = + self.prefill_requires_terminal_completion_for_age(request, cut, age_price); + let catalog = self.prefill_catalog_for_terminal( + request.prefill_kind(), + terminal_only || request.deferred_prefill, + ); + let max_capacity = if age_price > 0.0 && !terminal_only { + candidate.capacity.min(*catalog.last()?) + } else { + *catalog.last()? + }; + let work = self.prefill_work_through(request, max_capacity, cut); let capacity = *catalog.iter().find(|&&capacity| capacity >= work)?; let kind = self.resolve_prefill_kind(request, capacity, work, cut); (kind, capacity, 0, work) @@ -1919,8 +1982,11 @@ impl RequestScheduler { .fold(0, |a, b| a | b); let mut candidates = Vec::new(); if kind.is_prefill() { + let mut prefill_plans = [PrefillSlotPlan::default(); REQUEST_LANES]; for &capacity in self.prefill_catalog(kind) { - self.add_candidate(&mut candidates, kind, 1, capacity, mask, &values, age_price); + self.add_prefill_candidate( + &mut candidates, kind, capacity, mask, &values, age_price, &mut prefill_plans, + ); } } else { for &batch in self.costs.batches(kind) { @@ -1936,7 +2002,7 @@ impl RequestScheduler { .then(b.batch.cmp(&a.batch)) }) .expect("requested lifecycle operation must be feasible"); - let origin = if candidate.rate.duration_ns == 0 { PlanOrigin::Discovery } else { PlanOrigin::Ordinary }; + let origin = if self.is_unmeasured_candidate(candidate) { PlanOrigin::Discovery } else { PlanOrigin::Ordinary }; self.materialize(candidate, scale, origin) } } diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 9dec211fc..0fcab5b5c 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -5201,9 +5201,11 @@ fn mixed_graphs_excluded_for_deferred_prefill_and_prompt_logprobs() { complete(&mut s, &first, fence, 0, false); assert!(s.request(deferred).unwrap().deferred_prefill); - // service_rates must use TerminalPrefill(512) (40 ms => 513/40), not Mixed (1 ms => 513/1). + // Under an active age-priced decoder, deferred prefill with 512 tokens remaining can legally + // chunk via non-terminal Prefill(256) (leaving 256 > window 128; 5 ms => 256/5), while still + // excluding Mixed (1 ms => 513/1). let (deferred_rate, _) = s.service_rates(s.request(deferred).unwrap()); - let expected_deferred_rate = 513.0 / 40.0; + let expected_deferred_rate = 256.0 / 5.0; assert!( (deferred_rate.unwrap() - expected_deferred_rate).abs() < 1e-9, "deferred prefill service rate must exclude Mixed: got {deferred_rate:?}, expected {expected_deferred_rate}" @@ -5219,6 +5221,15 @@ fn mixed_graphs_excluded_for_deferred_prefill_and_prompt_logprobs() { .all(|candidate| candidate.prefill_slot != Some(deferred.slot as usize)), "deferred prefill request must not appear as a Mixed prefill lane" ); + + // Without active age-priced decoders, service_rates requires TerminalPrefill(512) (513/40). + s.cancel(decoder).unwrap(); + let (solo_deferred_rate, _) = s.service_rates(s.request(deferred).unwrap()); + let expected_solo_rate = 513.0 / 40.0; + assert!( + (solo_deferred_rate.unwrap() - expected_solo_rate).abs() < 1e-9, + "solo deferred prefill service rate must use TerminalPrefill(512): got {solo_deferred_rate:?}, expected {expected_solo_rate}" + ); } #[test] @@ -7507,3 +7518,1752 @@ fn terminal_prefill_clearing_deferred_state_at_interior_anchor_preserves_wait() "TerminalPrefill clearing deferred_prefill at interior Anchor must preserve wait clock" ); } + +#[test] +fn nonterminal_prefill_drains_when_active_decoders_exist_and_pipelines_when_idle() { + // With an active decoder under balanced policy (decode_age_price > 0), nonterminal + // Prefill must require completion feedback so decoders re-compete after every chunk. + let mut s = interactive_engine(2, false); + let decoder = add(&mut s, 1, 64, 128); + ready(&mut s, &[decoder]); + let prefill = add(&mut s, 2, 32768, 128); + initialize(&mut s, prefill); + let plan = s.phase_plan(GraphKind::Prefill, Some(prefill)); + assert_eq!((plan.kind, plan.token_capacity), (GraphKind::Prefill, 4096)); + assert!( + s.plan_requires_feedback(&plan), + "nonterminal prefill must drain when active age-priced decoders exist" + ); + let fence = Fence(s.submitted.0 + 1); + s.commit(&plan, fence).unwrap(); + assert!(s.plan().is_none(), "second frame must not queue ahead of active decoders"); + complete(&mut s, &plan, fence, 0, false); + + // Under throughput policy (decode_age_price == 0), nonterminal prefill still pipelines + // two deep even alongside an active decoder. + let mut tp = interactive_engine(2, false); + tp.configure_policy(PolicyConfig::throughput()).unwrap(); + let d = add(&mut tp, 1, 64, 128); + ready(&mut tp, &[d]); + let p = add(&mut tp, 2, 32768, 128); + initialize(&mut tp, p); + let p1 = tp.phase_plan(GraphKind::Prefill, Some(p)); + assert!(!tp.plan_requires_feedback(&p1)); + let f1 = Fence(tp.submitted.0 + 1); + tp.commit(&p1, f1).unwrap(); + let p2 = tp.phase_plan(GraphKind::Prefill, Some(p)); + assert!(!tp.plan_requires_feedback(&p2)); + let f2 = Fence(f1.0 + 1); + tp.commit(&p2, f2).unwrap(); + complete(&mut tp, &p1, f1, 0, false); + complete(&mut tp, &p2, f2, 0, false); +} + +#[test] +fn gb10_prefill_storm_unblocks_smaller_prefill_chunks_and_eliminates_one_second_stalls() { + use crate::execution::GraphDescriptor; + // Cold-start 16K TerminalPrefill catalog modeled after 4x GB10 measured timings: + // Prefill(128..16384), TerminalPrefill(256..16384), Decode(B=1..16). + let caps = [128usize, 256, 512, 1024, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 6144, 8192, 10240, 12288, 14336, 16384]; + let prefill_ns = |cap: usize| -> u64 { + let ms = match cap { + 128 => 45, + 256 => 65, + 512 => 98, + 1024 => 150, + 2048 => 227, + 4096 => 380, + 6144 => 534, + 8192 => 687, + 10240 => 841, + 12288 => 995, + 14336 => 1148, + 16384 => 1302, + _ => 1302, + }; + ms * MS + }; + let terminal_ns = |cap: usize| prefill_ns(cap) + 12 * MS; + let decode_ns = |batch: usize| -> u64 { + let ms = match batch { + 1 => 28, + 2 => 36, + 4 => 49, + 8 => 72, + 12 => 94, + 16 => 108, + _ => 108, + }; + ms * MS + }; + + let mut s = RequestScheduler::new( + [1; 32], + SchedulerLimits { + max_active: 16, + request_slots: 16, + max_sequence_tokens: 65_536, + prefill_chunk_size: 16_384, + pages: 16_384, + snapshots: 256, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let mut graphs = vec![ + GraphDescriptor { + name: "init-16".into(), + kind: GraphKind::Init, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1, + batch_capacity: 16, + token_capacity: 1, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }, + GraphDescriptor { + name: "snap-16".into(), + kind: GraphKind::Snapshot, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 2, + batch_capacity: 16, + token_capacity: 1, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }, + ]; + for &b in &[1usize, 2, 4, 8, 12, 16] { + graphs.push(GraphDescriptor { + name: format!("decode-{b}"), + kind: GraphKind::Decode, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 10 + b, + batch_capacity: b, + token_capacity: 1, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + for &c in &caps { + graphs.push(GraphDescriptor { + name: format!("prefill-{c}"), + kind: GraphKind::Prefill, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 100 + c, + batch_capacity: 1, + token_capacity: c, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + for &c in &term_caps { + graphs.push(GraphDescriptor { + name: format!("terminal-prefill-{c}"), + kind: GraphKind::TerminalPrefill, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 1000 + c, + batch_capacity: 1, + token_capacity: c, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + }); + } + // Start completely cold (all estimated_duration_ns == 0) except Init/Snapshot/Decode/Prefill(16384), + // matching the state right after a single cold long prompt has measured Prefill(16384). + s.graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 16, 1, MS); + set_cost(&mut s, GraphKind::Snapshot, 16, 1, 2 * MS); + for &b in &[1usize, 2, 4, 8, 12, 16] { + set_cost(&mut s, GraphKind::Decode, b, 1, decode_ns(b)); + } + set_cost(&mut s, GraphKind::Prefill, 1, 16384, prefill_ns(16384)); + + // Admit 12 active decoders and 2 heavy 28K cold prompts (Prefill(256..14336) and + // TerminalPrefill(256..16384) are ALL still unmeasured!). + let mut decoders = Vec::new(); + for i in 0..12u32 { + let h = add(&mut s, 10 + i, 512, 256); + decoders.push(h); + } + ready(&mut s, &decoders); + let now = s.now_ns; + for &h in &decoders { + let r = s.request_mut(h).unwrap(); + r.accounting.last_output_ns = Some(now); + } + let heavy0 = add(&mut s, 100, 28_000, 32); + let heavy1 = add(&mut s, 101, 24_000, 32); + initialize(&mut s, heavy0); + initialize(&mut s, heavy1); + + let mut post_warmup_prefill_caps = Vec::new(); + let mut max_decode_gap_ns = 0u64; + let mut last_decode_ns = [s.now_ns; 12]; + let mut steps = 0usize; + while (s.request(heavy0).is_ok_and(|r| r.phase == RequestPhase::Prefill) + || s.request(heavy1).is_ok_and(|r| r.phase == RequestPhase::Prefill)) + && steps < 600 + { + steps += 1; + let plan = s.plan().unwrap(); + // Every nonterminal prefill step must drain while active decoders exist. + if plan.kind == GraphKind::Prefill { + assert!(s.plan_requires_feedback(&plan)); + } + // Deferred prefill invariant: Prefill(128) must never execute while deferred_prefill is set. + if plan.kind == GraphKind::Prefill && plan.token_capacity == 128 { + let req = s.request(plan.lanes[0].request).unwrap(); + assert!(!req.deferred_prefill, "Prefill(128) must not run while deferred_prefill is set"); + } + let dur_ns = match plan.kind { + GraphKind::Prefill => prefill_ns(plan.token_capacity), + GraphKind::TerminalPrefill => terminal_ns(plan.token_capacity), + GraphKind::Decode => decode_ns(plan.batch_capacity), + GraphKind::Snapshot => 2 * MS, + _ => MS, + }; + if plan.kind.is_prefill() { + post_warmup_prefill_caps.push((plan.kind, plan.token_capacity)); + } + let fence = Fence(s.submitted.0 + 1); + s.commit(&plan, fence).unwrap(); + s.advance_to(s.now_ns + dur_ns).unwrap(); + let emitted = if plan.kind.is_prefill() { + let lane = &plan.lanes[0]; + let req = s.request(lane.request).unwrap(); + usize::from(lane.start_position + lane.tokens as u64 == req.prompt_tokens as u64) + } else if plan.kind == GraphKind::Decode { + 1 + } else { + 0 + }; + complete_timed(&mut s, &plan, fence, emitted, false, gpu_time(dur_ns)); + if plan.kind == GraphKind::Decode { + for lane in &plan.lanes { + s.published_output(lane.request, fence).unwrap(); + if let Some(pos) = decoders.iter().position(|&h| h == lane.request) { + max_decode_gap_ns = max_decode_gap_ns.max(s.now_ns - last_decode_ns[pos]); + last_decode_ns[pos] = s.now_ns; + } + } + } + } + assert!(!s.request(heavy0).is_ok_and(|r| r.phase == RequestPhase::Prefill)); + assert!(!s.request(heavy1).is_ok_and(|r| r.phase == RequestPhase::Prefill)); + assert!(!s.request(heavy0).is_ok_and(|r| r.deferred_prefill)); + assert!(!s.request(heavy1).is_ok_and(|r| r.deferred_prefill)); + // Must discover and use smaller prefill capacities rather than locking onto 16384/14336. + assert!( + post_warmup_prefill_caps.iter().any(|&(k, cap)| k == GraphKind::Prefill && cap <= 4096), + "expected smaller non-terminal prefill chunks under 12 active decoders: {post_warmup_prefill_caps:?}" + ); + assert!( + post_warmup_prefill_caps.iter().all(|&(_, cap)| cap <= 8192), + "unexpected >8K prefill stall under 12 active decoders: {post_warmup_prefill_caps:?}" + ); + assert!( + max_decode_gap_ns < 1000 * MS, + "max decode gap must stay below 1000 ms (got {} ms); prefills={post_warmup_prefill_caps:?}", + max_decode_gap_ns / MS + ); +} + +#[test] +fn continuation_candidate_excludes_oversized_padded_unmeasured_prefill() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096, 8192, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 8192, 16384]; + let build = |measure_sibling_8k: bool| -> f64 { + let mut s = RequestScheduler::new( + [2; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 32_768, + prefill_chunk_size: 16_384, + pages: 4_096, + snapshots: 64, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 18 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + set_cost(&mut s, GraphKind::TerminalPrefill, 1, 1024, 400 * MS); + if measure_sibling_8k { + set_cost(&mut s, GraphKind::Prefill, 1, 8192, 100 * MS); + } + + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 800, 64); + let init_plan = s.phase_plan(GraphKind::Init, Some(prompt)); + assert_eq!(init_plan.kind, GraphKind::Init); + init_plan.selection_value_rate() + }; + + let without_oversized_sibling = build(false); + let with_oversized_sibling = build(true); + assert_eq!( + with_oversized_sibling.to_bits(), + without_oversized_sibling.to_bits(), + "oversized unmeasured TerminalPrefill(8192) above nat_fit=1024 must not inflate Init continuation score" + ); +} + +#[test] +fn resize_prefill_caps_age_priced_chunk_when_checkpoint_cut_drops() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096, 8192, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 8192, 16384]; + let mut s = RequestScheduler::new( + [3; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 32_768, + prefill_chunk_size: 16_384, + pages: 4_096, + snapshots: 2, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 28 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + for &c in &caps { + let ms = match c { + 128 => 45, + 256 => 65, + 512 => 98, + 1024 => 150, + 2048 => 227, + 4096 => 380, + 8192 => 687, + _ => 1302, + }; + set_cost(&mut s, GraphKind::Prefill, 1, c, ms * MS); + } + for &c in &term_caps { + let ms = match c { + 256 => 77, + 512 => 110, + 1024 => 162, + 2048 => 239, + 4096 => 392, + 8192 => 699, + _ => 1314, + }; + set_cost(&mut s, GraphKind::TerminalPrefill, 1, c, ms * MS); + } + + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let heavy = add(&mut s, 2, 24_000, 64); + s.request_mut(heavy).unwrap().message_boundaries = vec![2048, 24_000]; + initialize(&mut s, heavy); + // Exhaust free snapshots so checkpoint_cut returns None when available_plan resolves the cut. + s.free_snapshots.clear(); + let (values, age_price, scale) = s.lane_values(s.window_remaining().unwrap()); + assert!(age_price > 0.0); + let slot = heavy.slot as usize; + let candidate = Candidate { + host_lengths: None, + draft_tokens: 0, + packed_token_capacity: 0, + kind: GraphKind::TerminalPrefill, + mask: 1u64 << slot, + batch: 1, + capacity: 2048, + prefill_capacity: 0, + prefill_slot: None, + work: 2048, + duration_ns: 239 * MS, + rate: ValueRate::new(239 * MS, 1.0, age_price), + feedback: true, + }; + let plan = s + .available_plan(candidate, &values, age_price, scale, PlanOrigin::Ordinary) + .unwrap(); + assert_eq!(plan.kind, GraphKind::Prefill); + assert!( + plan.token_capacity <= 2048 && plan.lanes[0].tokens <= 2048, + "dropped checkpoint cut under age_price > 0 must not expand 2048 chunk to {} ({} ms)", + plan.token_capacity, + plan.estimated_duration_ns() / MS + ); + assert!(plan.estimated_duration_ns() < 500 * MS); +} + +#[test] +fn deferred_prefill_never_selects_non_terminal_catalog_capacity_when_needs_terminal_false() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096]; + let term_caps = [256usize, 512, 1024, 2048, 4096]; + let mut s = RequestScheduler::new( + [4; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 16_384, + prefill_chunk_size: 4096, + pages: 2048, + snapshots: 64, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 500 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + // Price Prefill(128) far cheaper than 256..=4096 so it would dominate ValueRate if allowed + // while deferred_prefill == true and needs_terminal == false (remaining = 4096). + set_cost(&mut s, GraphKind::Prefill, 1, 128, MS); + for &c in &term_caps { + set_cost(&mut s, GraphKind::Prefill, 1, c, 500 * MS); + set_cost(&mut s, GraphKind::TerminalPrefill, 1, c, 500 * MS); + } + + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 4352, 64); + initialize(&mut s, prompt); + // Simulate prior non-terminal chunk leaving remaining = 4096 > window (128) with deferred_prefill. + { + let r = s.request_mut(prompt).unwrap(); + r.consumed_tokens = 256; + r.scheduled_consumed = 256; + r.deferred_prefill = true; + } + let plan = s.phase_plan(GraphKind::Prefill, Some(prompt)); + assert_ne!( + plan.token_capacity, 128, + "non-terminal-catalog capacity 128 must never be selected while deferred_prefill is set" + ); + assert!(plan.token_capacity >= 256); + // Also verify ordinary s.plan() (with decoder age_price > 0) never picks Prefill(128). + let (values, age_price, _) = s.lane_values(s.window_remaining().unwrap()); + assert!(age_price > 0.0); + let mut candidates = Vec::new(); + s.candidates(&mut candidates, &values, age_price); + assert!( + !candidates.iter().any(|c| c.kind == GraphKind::Prefill && c.capacity == 128), + "Prefill(128) candidate must be excluded while deferred_prefill is set" + ); +} + +#[test] +fn resize_prefill_uses_terminal_catalog_under_deferred_prefill_and_atomic_span() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096, 8192, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 8192, 16384]; + let mut s = RequestScheduler::new( + [5; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 32_768, + prefill_chunk_size: 16_384, + pages: 4_096, + snapshots: 2, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 28 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + for &c in &caps { + set_cost(&mut s, GraphKind::Prefill, 1, c, (c as u64 / 4).max(40) * MS); + } + for &c in &term_caps { + set_cost(&mut s, GraphKind::TerminalPrefill, 1, c, ((c as u64 / 4).max(40) + 12) * MS); + } + + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let heavy = add(&mut s, 2, 20_000, 64); + // Span [2176..18500] (len 16324 <= prefill_chunk_size 16384) clamps work from start=2048 + // to 128 tokens for both capacity=256 and max_capacity=16384 (2048 + 16384 = 18432 < 18500). + s.set_prefill_spans(heavy, &[2176..18_500]).unwrap(); + s.request_mut(heavy).unwrap().message_boundaries = vec![2176, 20_000]; + initialize(&mut s, heavy); + { + let r = s.request_mut(heavy).unwrap(); + r.consumed_tokens = 2048; + r.scheduled_consumed = 2048; + r.deferred_prefill = true; + } + // Exhaust free snapshots so checkpoint_cut returns None, leaving 128 tokens before atomic span + // [2176..19000]. resize_prefill must pick capacity 256 from terminal_prefill_catalog (Prefill) + // instead of 128 (unregistered in TerminalPrefill) and falling through to stale TerminalPrefill. + s.free_snapshots.clear(); + let (values, age_price, scale) = s.lane_values(s.window_remaining().unwrap()); + assert!(age_price > 0.0); + let slot = heavy.slot as usize; + let candidate = Candidate { + host_lengths: None, + draft_tokens: 0, + packed_token_capacity: 0, + kind: GraphKind::TerminalPrefill, + mask: 1u64 << slot, + batch: 1, + capacity: 256, + prefill_capacity: 0, + prefill_slot: None, + work: 128, + duration_ns: 76 * MS, + rate: ValueRate::new(76 * MS, 1.0, age_price), + feedback: true, + }; + let plan = s + .available_plan(candidate, &values, age_price, scale, PlanOrigin::Ordinary) + .unwrap(); + assert_eq!( + (plan.kind, plan.token_capacity, plan.lanes[0].tokens), + (GraphKind::Prefill, 256, 128), + "resize_prefill under deferred_prefill + atomic span must resize to Prefill(256, work=128)" + ); + // Also verify zero-age solo path resizes cleanly to Prefill(256, work=128). + let solo_plan = s + .available_plan(candidate, &values, 0.0, scale, PlanOrigin::Ordinary) + .unwrap(); + assert_eq!( + (solo_plan.kind, solo_plan.token_capacity, solo_plan.lanes[0].tokens), + (GraphKind::Prefill, 256, 128) + ); +} + +#[test] +fn service_rates_falls_back_to_measured_prefill_when_terminal_unmeasured_under_active_decoders() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096, 8192, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 8192, 16384]; + let make_sched = |terminal_catalog: &[usize]| -> RequestScheduler { + let mut s = RequestScheduler::new( + [6; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 32_768, + prefill_chunk_size: 16_384, + pages: 4_096, + snapshots: 64, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(terminal_catalog).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in terminal_catalog.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 18 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + // Measure Prefill(128) and Prefill(2048); leave all TerminalPrefill shapes unmeasured. + set_cost(&mut s, GraphKind::Prefill, 1, 128, 40 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 2048, 200 * MS); + s + }; + + // Without active decoders, remaining 4096 <= max_terminal requires TerminalPrefill -> None. + let mut solo = make_sched(&term_caps); + let solo_prompt = add(&mut solo, 1, 4096, 64); + initialize(&mut solo, solo_prompt); + assert_eq!(solo.service_rates(solo.request(solo_prompt).unwrap()).0, None); + + // With an active age-priced decoder, service_rates falls back to measured Prefill(2048). + let mut s = make_sched(&term_caps); + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 4096, 64); + initialize(&mut s, prompt); + let rate = s + .service_rates(s.request(prompt).unwrap()) + .0 + .expect("measured Prefill(2048) must provide fallback token_rate when TerminalPrefill is unmeasured"); + assert!((rate - (2048.0 / 200.0)).abs() < 1e-6, "unexpected fallback rate {rate}"); + + // With !deferred_prefill and 128 absent from term_caps, Prefill(128) remains legal for a + // 256-token prompt, so prefill_must_complete_terminally_from is false and fallback uses 128. + let short_prompt = add(&mut s, 3, 256, 64); + initialize(&mut s, short_prompt); + assert!(!s.prefill_must_complete_terminally_from(s.request(short_prompt).unwrap(), 0, None)); + let short_rate = s + .service_rates(s.request(short_prompt).unwrap()) + .0 + .expect("measured Prefill(128) absent from term_caps must supply fallback rate when !deferred_prefill"); + assert!((short_rate - (128.0 / 40.0)).abs() < 1e-6, "unexpected short rate {short_rate}"); + + // With deferred_prefill = true, Prefill(128) is excluded and prefill_must_complete_terminally_from + // returns true, suppressing the fallback even though Prefill(128) and Prefill(2048) are measured. + s.request_mut(short_prompt).unwrap().deferred_prefill = true; + assert!(s.prefill_must_complete_terminally_from(s.request(short_prompt).unwrap(), 0, None)); + assert_eq!(s.service_rates(s.request(short_prompt).unwrap()).0, None); + + // When term_caps covers every prefill capacity starting at 128 (window = 0), a 128-token + // prompt has no legal non-terminal Prefill chunk, so prefill_must_complete_terminally_from + // is true -> None. + let mut s_full_term = make_sched(&caps); + let dec2 = add(&mut s_full_term, 1, 256, 128); + ready(&mut s_full_term, &[dec2]); + let term_only_prompt = add(&mut s_full_term, 2, 128, 64); + initialize(&mut s_full_term, term_only_prompt); + assert!(s_full_term.prefill_must_complete_terminally_from( + s_full_term.request(term_only_prompt).unwrap(), + 0, + None + )); + assert_eq!(s_full_term.service_rates(s_full_term.request(term_only_prompt).unwrap()).0, None); +} + +#[test] +fn service_rates_prefers_faster_feasible_prefill_over_slower_measured_terminal_under_active_decoders() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024, 2048, 4096, 8192, 16384]; + let term_caps = [256usize, 512, 1024, 2048, 4096, 8192, 16384]; + let make_sched = || -> RequestScheduler { + let mut s = RequestScheduler::new( + [6; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 32_768, + prefill_chunk_size: 16_384, + pages: 4_096, + snapshots: 64, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 18 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + // Measure a slower padded TerminalPrefill(16384) alongside faster non-terminal Prefill shapes. + set_cost(&mut s, GraphKind::TerminalPrefill, 1, 16384, 1_000 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 4096, 200 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 128, 20 * MS); + s + }; + + // Active age-priced decoder (!deferred_prefill): 8192-token prompt can legally chunk via + // Prefill(4096) (20.48 tok/ms), which must beat slower measured TerminalPrefill(16384) (8.193 tok/ms). + let mut s = make_sched(); + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 8192, 64); + initialize(&mut s, prompt); + let rate = s + .service_rates(s.request(prompt).unwrap()) + .0 + .expect("service_rates must return the faster feasible Prefill(4096) rate"); + assert!( + (rate - (4096.0 / 200.0)).abs() < 1e-6, + "expected faster feasible Prefill(4096) rate 20.48, got {rate}" + ); + + // For a 256-token prompt with 128 absent from term_caps: !deferred_prefill allows Prefill(128) + // (6.4 tok/ms > 0.257 tok/ms), while deferred_prefill = true excludes Prefill(128) and uses + // only measured TerminalPrefill(16384) (257 / 1000 = 0.257 tok/ms). + let short_prompt = add(&mut s, 3, 256, 64); + initialize(&mut s, short_prompt); + let short_rate = s.service_rates(s.request(short_prompt).unwrap()).0.unwrap(); + assert!( + (short_rate - (128.0 / 20.0)).abs() < 1e-6, + "expected feasible Prefill(128) rate 6.4, got {short_rate}" + ); + s.request_mut(short_prompt).unwrap().deferred_prefill = true; + let deferred_rate = s.service_rates(s.request(short_prompt).unwrap()).0.unwrap(); + assert!( + (deferred_rate - (257.0 / 1000.0)).abs() < 1e-6, + "deferred_prefill must exclude Prefill(128) and use TerminalPrefill(16384) rate 0.257, got {deferred_rate}" + ); + + // Solo prompt (no active age-priced streams) uses prefill_requires_terminal_completion_from + // and therefore skips non-terminal Prefill(4096), returning TerminalPrefill(16384) (8.193 tok/ms). + let mut solo = make_sched(); + let solo_prompt = add(&mut solo, 1, 8192, 64); + initialize(&mut solo, solo_prompt); + let solo_rate = solo.service_rates(solo.request(solo_prompt).unwrap()).0.unwrap(); + assert!( + (solo_rate - (8193.0 / 1000.0)).abs() < 1e-6, + "solo prompt must use TerminalPrefill(16384) rate 8.193, got {solo_rate}" + ); + + // Active Decode under PolicyConfig::throughput() (decode_age_price == 0.0) has no active + // age-priced stream and also uses prefill_requires_terminal_completion_from (8.193 tok/ms). + let mut tp = make_sched(); + tp.configure_policy(PolicyConfig::throughput()).unwrap(); + let tp_dec = add(&mut tp, 1, 256, 128); + ready(&mut tp, &[tp_dec]); + let tp_prompt = add(&mut tp, 2, 8192, 64); + initialize(&mut tp, tp_prompt); + assert!(!tp.has_active_age_priced_stream()); + let tp_rate = tp.service_rates(tp.request(tp_prompt).unwrap()).0.unwrap(); + assert!( + (tp_rate - (8193.0 / 1000.0)).abs() < 1e-6, + "zero-age decoder must use TerminalPrefill(16384) rate 8.193, got {tp_rate}" + ); +} + +#[test] +fn has_active_age_priced_stream_covers_resume_and_terminal_cleanup_branches() { + // 1. RequestPhase::Resume with decode_age_price > 0 drains nonterminal Prefill; + // under throughput (decode_age_price == 0), nonterminal Prefill pipelines. + let mut s_bal = interactive_engine(2, false); + let resuming = add(&mut s_bal, 1, 64, 128); + initialize(&mut s_bal, resuming); + { + let r = s_bal.request_mut(resuming).unwrap(); + r.phase = RequestPhase::Resume; + r.consumed_tokens = 64; + r.scheduled_consumed = 64; + r.generated_tokens = 0; + } + let prefill = add(&mut s_bal, 2, 32768, 128); + initialize(&mut s_bal, prefill); + assert!(s_bal.has_active_age_priced_stream()); + let plan = s_bal.phase_plan(GraphKind::Prefill, Some(prefill)); + assert!( + s_bal.plan_requires_feedback(&plan), + "nonterminal Prefill must drain when an active Resume stream is age-priced" + ); + + // Solo prefill and active Decode under throughput (decode_age_price == 0) keep two-frame + // pipelining without a terminal_cleanup stream. + let mut s_tp_solo = interactive_engine(2, false); + s_tp_solo.configure_policy(PolicyConfig::throughput()).unwrap(); + let solo_tp = add(&mut s_tp_solo, 1, 32768, 128); + initialize(&mut s_tp_solo, solo_tp); + assert!(!s_tp_solo.has_active_age_priced_stream()); + let plan_solo_tp = s_tp_solo.phase_plan(GraphKind::Prefill, Some(solo_tp)); + assert!(!s_tp_solo.plan_requires_feedback(&plan_solo_tp)); + + let mut s_tp_dec = interactive_engine(2, false); + s_tp_dec.configure_policy(PolicyConfig::throughput()).unwrap(); + let decoding_tp = add(&mut s_tp_dec, 1, 64, 128); + ready(&mut s_tp_dec, &[decoding_tp]); + let prefill_dec_tp = add(&mut s_tp_dec, 2, 32768, 128); + initialize(&mut s_tp_dec, prefill_dec_tp); + assert!(!s_tp_dec.has_active_age_priced_stream()); + let plan_dec_tp = s_tp_dec.phase_plan(GraphKind::Prefill, Some(prefill_dec_tp)); + assert!(!s_tp_dec.plan_requires_feedback(&plan_dec_tp)); + + let mut s_tp = interactive_engine(2, false); + s_tp.configure_policy(PolicyConfig::throughput()).unwrap(); + let resuming_tp = add(&mut s_tp, 1, 64, 128); + initialize(&mut s_tp, resuming_tp); + { + let r = s_tp.request_mut(resuming_tp).unwrap(); + r.phase = RequestPhase::Resume; + r.consumed_tokens = 64; + r.scheduled_consumed = 64; + r.generated_tokens = 0; + } + let prefill_tp = add(&mut s_tp, 2, 32768, 128); + initialize(&mut s_tp, prefill_tp); + assert!(!s_tp.has_active_age_priced_stream()); + let plan_tp = s_tp.phase_plan(GraphKind::Prefill, Some(prefill_tp)); + assert!(!s_tp.plan_requires_feedback(&plan_tp)); + + // 2. policy::terminal_cleanup(r) with terminal_age_price > 0 drains nonterminal Prefill even + // when decode_age_price == 0; zeroing terminal_age_price restores pipelining. + let mut t = interactive_engine(2, false); + t.configure_policy(PolicyConfig::throughput()).unwrap(); + assert_eq!(t.policy.decode_age_price, 0.0); + assert!(t.policy.terminal_age_price > 0.0); + let cleaning = add(&mut t, 1, 64, 1); + initialize(&mut t, cleaning); + let t_now = t.now_ns; + { + let r = t.request_mut(cleaning).unwrap(); + r.phase = RequestPhase::Snapshot; + r.boundary_capture = None; + r.accounting.terminal_since_ns = Some(t_now); + } + assert!(super::policy::terminal_cleanup(t.request(cleaning).unwrap())); + let prefill_t = add(&mut t, 2, 32768, 128); + initialize(&mut t, prefill_t); + assert!(t.has_active_age_priced_stream()); + let plan_t = t.phase_plan(GraphKind::Prefill, Some(prefill_t)); + assert!( + t.plan_requires_feedback(&plan_t), + "nonterminal Prefill must drain when a terminal-cleanup stream is age-priced" + ); + + let mut t_zero = interactive_engine(2, false); + t_zero + .configure_policy(PolicyConfig { terminal_age_price: 0.0, ..PolicyConfig::throughput() }) + .unwrap(); + let cleaning_z = add(&mut t_zero, 1, 64, 1); + initialize(&mut t_zero, cleaning_z); + let tz_now = t_zero.now_ns; + { + let r = t_zero.request_mut(cleaning_z).unwrap(); + r.phase = RequestPhase::Snapshot; + r.boundary_capture = None; + r.accounting.terminal_since_ns = Some(tz_now); + } + let prefill_z = add(&mut t_zero, 2, 32768, 128); + initialize(&mut t_zero, prefill_z); + assert!(!t_zero.has_active_age_priced_stream()); + let plan_z = t_zero.phase_plan(GraphKind::Prefill, Some(prefill_z)); + assert!(!t_zero.plan_requires_feedback(&plan_z)); +} + +#[test] +fn add_candidate_excludes_oversized_unmeasured_terminal_prefill_above_prefill_nat_fit() { + use crate::execution::GraphDescriptor; + + let caps = [128usize, 256, 512, 1024]; + let term_caps = [256usize, 512, 1024]; + let mut s = RequestScheduler::new( + [7; 32], + SchedulerLimits { + max_active: 4, + request_slots: 4, + max_sequence_tokens: 8_192, + prefill_chunk_size: 1_024, + pages: 1_024, + snapshots: 64, + }, + SchedulerCapabilities { + completion_token_capacity: 1, + vocabulary: 1024, + page_tokens: 128, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.prefill_graphs(&caps).unwrap(); + s.terminal_prefill_graphs(&term_caps).unwrap(); + let make = |name: String, kind: GraphKind, batch: usize, cap: usize, handle: usize| { + GraphDescriptor { + name, + kind, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle, + batch_capacity: batch, + token_capacity: cap, + packed_token_capacity: 0, + prefill_capacity: 0, + estimated_duration_ns: 0, + input_bindings: vec![], + tuned_bindings: vec![], + } + }; + let mut graphs = vec![ + make("init-1".into(), GraphKind::Init, 1, 1, 1), + make("decode-1".into(), GraphKind::Decode, 1, 1, 2), + make("snap-1".into(), GraphKind::Snapshot, 1, 1, 3), + ]; + for (i, &c) in caps.iter().enumerate() { + graphs.push(make(format!("p-{c}"), GraphKind::Prefill, 1, c, 100 + i)); + } + for (i, &c) in term_caps.iter().enumerate() { + graphs.push(make(format!("t-{c}"), GraphKind::TerminalPrefill, 1, c, 200 + i)); + } + s.measured_graph_durations(&graphs).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 500 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 2 * MS); + // Measure Prefill(128) at 50 ms and sibling Prefill(256) at 1 ms, leaving all TerminalPrefill + // shapes unmeasured. For a 128-token prompt, nat_fit is 128 (GraphKind::Prefill) while + // oversized capacity 256 resolves to GraphKind::TerminalPrefill (which prune_padding cannot + // prune against Prefill(128) because kinds differ). + set_cost(&mut s, GraphKind::Prefill, 1, 128, 50 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 256, MS); + + let decoder = add(&mut s, 1, 256, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 128, 64); + initialize(&mut s, prompt); + + let (values, age_price, _) = s.lane_values(s.window_remaining().unwrap()); + assert!(age_price > 0.0); + let mut candidates = Vec::new(); + s.candidates(&mut candidates, &values, age_price); + assert!( + !candidates.iter().any(|c| c.kind == GraphKind::TerminalPrefill && c.capacity > 128), + "oversized unmeasured TerminalPrefill > nat_fit=128 must be excluded in add_candidate" + ); + let plan = s.plan().unwrap(); + assert_eq!( + (plan.kind, plan.token_capacity, plan.lanes[0].tokens), + (GraphKind::Prefill, 128, 128) + ); +} + +#[test] +fn interpolated_unmeasured_prefill_returns_discovery_even_when_refresh_or_acceptance_ready() { + let mut s = RequestScheduler::new( + [7; 32], + SchedulerLimits { + max_active: 2, + request_slots: 2, + max_sequence_tokens: 8_192, + prefill_chunk_size: 4_096, + pages: 1_024, + snapshots: 256, + }, + SchedulerCapabilities { + completion_token_capacity: 16, + vocabulary: 1024, + page_tokens: 64, + vision: crate::model::VisionCapabilities::disabled(), + draft_pages_per_request: 0, + completion_inputs: vec![], + speculative_allocations: vec![], + state_rows_per_request: None, + }, + ) + .unwrap(); + s.enable_speculation(&[1, 8]).unwrap(); + let mut graphs = super::tests::duration_graphs(2); + graphs.retain(|g| { + if g.kind == GraphKind::Prefill { + matches!(g.token_capacity, 64 | 512 | 4_096) + } else if g.kind == GraphKind::Speculative { + matches!(g.token_capacity, 1 | 8) + } else { + true + } + }); + for g in &mut graphs { + g.estimated_duration_ns = if g.kind == GraphKind::Prefill && g.token_capacity == 512 { + 0 + } else { + 20 * MS + }; + } + s.prefill_graphs(&[64, 512, 4_096]).unwrap(); + s.measured_graph_durations(&graphs).unwrap(); + + // Measure Prefill(64) before TTL advance so it is a feasible stale refresh target. + set_cost(&mut s, GraphKind::Prefill, 1, 64, 20 * MS); + s.advance_to(s.now_ns + s.policy.estimate_ttl_ns).unwrap(); + set_cost(&mut s, GraphKind::Init, 1, 1, MS); + set_cost(&mut s, GraphKind::Decode, 2, 1, 200 * MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 200 * MS); + set_cost(&mut s, GraphKind::Speculative, 1, 1, 200 * MS); + set_cost(&mut s, GraphKind::Speculative, 1, 8, 50 * MS); + set_cost(&mut s, GraphKind::Speculative, 2, 1, 200 * MS); + set_cost(&mut s, GraphKind::Speculative, 2, 8, 200 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 4_096, 1_000 * MS); + assert!(!s.costs.is_fresh(cost::Key { drafts: 0, kind: GraphKind::Prefill, batch: 1, tokens: 64, prefill: 0, packed: 0 })); + assert!(s + .costs + .observation(cost::Key { drafts: 0, kind: GraphKind::Prefill, batch: 1, tokens: 512, prefill: 0, packed: 0 }) + .and_then(|(_, observed, _)| observed) + .is_none()); + + let decoder = add(&mut s, 1, 64, 128); + ready(&mut s, &[decoder]); + let prompt = add(&mut s, 2, 4_096, 64); + initialize(&mut s, prompt); + + + let (values, age_price, _) = s.lane_values(s.window_remaining().unwrap()); + assert!(age_price > 0.0); + + // Precondition: interpolated Prefill(512) has positive duration, wins ordinary selection, + // and acceptance_probe would fire if select_plan() failed to detect ordinary_unmeasured. + let mut candidates = Vec::new(); + s.candidates(&mut candidates, &values, age_price); + let ordinary_count = s.prune_padding(&mut candidates); + let interp_512 = candidates[..ordinary_count] + .iter() + .copied() + .find(|c| c.kind == GraphKind::Prefill && c.capacity == 512) + .expect("interpolated Prefill(512) candidate must be generated"); + assert!(interp_512.rate.duration_ns > 0); + assert!( + s.acceptance_probe(interp_512, &values, age_price).is_some(), + "precondition: acceptance_probe must return Some so this test catches AcceptanceStart leaks" + ); + + // Case 1: refresh_ready() == true with feasible stale Prefill(64) must NOT displace Discovery. + s.refresh.credit_ns = refresh::CREDIT_CAP_NS; + s.refresh.acceptance_credit_ns = 0.0; + assert!(s.refresh_ready()); + let plan_refresh = s.plan().unwrap(); + assert_eq!( + (plan_refresh.kind, plan_refresh.token_capacity, plan_refresh.origin), + (GraphKind::Prefill, 512, PlanOrigin::Discovery), + "unmeasured interpolated Prefill(512) must return PlanOrigin::Discovery, not RefreshStart or Ordinary" + ); + + // Case 2: acceptance_ready() == true with active acceptance_probe must NOT leak AcceptanceStart. + s.refresh.credit_ns = 0.0; + s.refresh.acceptance_credit_ns = refresh::CREDIT_CAP_NS; + assert!(s.refresh.acceptance_ready()); + let plan_accept = s.plan().unwrap(); + assert_eq!( + (plan_accept.kind, plan_accept.token_capacity, plan_accept.origin), + (GraphKind::Prefill, 512, PlanOrigin::Discovery), + "unmeasured interpolated Prefill(512) must return PlanOrigin::Discovery, not AcceptanceStart or Ordinary" + ); + + // Case 3: #[cfg(test)] phase_plan must also classify interpolated unmeasured prefill as Discovery. + let phase = s.phase_plan(GraphKind::Prefill, Some(prompt)); + assert_eq!( + (phase.kind, phase.token_capacity, phase.origin), + (GraphKind::Prefill, 512, PlanOrigin::Discovery), + "phase_plan must also mark interpolated unmeasured Prefill as PlanOrigin::Discovery" + ); +} + +#[test] +fn first_output_wait_preserved_across_age_priced_non_terminal_prefill_chunks() { + let make_scheduler = |policy: PolicyConfig| { + let mut s = prefill_catalog_engine( + SchedulerLimits { + max_active: 8, + request_slots: 8, + max_sequence_tokens: 8192, + prefill_chunk_size: 2048, + pages: 4096, + snapshots: 256, + }, + &[128, 256, 512, 1024, 2048], + &[256, 512, 1024, 2048], + true, + |cap| match cap { + 128 => 3 * MS, + 256 => 5 * MS, + 512 => 10 * MS, + 1024 => 80 * MS, + 2048 => 160 * MS, + _ => 200 * MS, + }, + |cap| match cap { + 256 => 20 * MS, + 512 => 40 * MS, + 1024 => 90 * MS, + 2048 => 180 * MS, + _ => 220 * MS, + }, + ); + s.configure_policy(policy).unwrap(); + set_cost(&mut s, GraphKind::Decode, 1, 1, 2 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 1 * MS); + s + }; + + // 1. Prompt fitting in TERMINAL_PREFILL (1024 <= 2048) under active age-priced decoder + // preserves first_output_wait_ns across chunk 0 (!deferred_prefill -> sets deferred_prefill) + // and chunk 1 (deferred_prefill == true, remaining suffix still fits in TERMINAL_PREFILL). + let mut s = make_scheduler(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }); + assert!(s.policy.decode_age_price > 0.0); + let dec = add(&mut s, 1, 64, 1024); + ready(&mut s, &[dec]); + assert!(s.has_active_age_priced_stream()); + + let short = add(&mut s, 2, 1024, 64); + let short_arrival = s.now_ns; + initialize(&mut s, short); + s.advance_to(short_arrival + 100 * MS).unwrap(); + + // Chunk 0: non-terminal Prefill(512) (512 remaining > window 128). + let c0 = s.phase_plan(GraphKind::Prefill, Some(short)); + assert_eq!(c0.kind, GraphKind::Prefill); + assert!(c0.lanes[0].tokens > 0 && c0.lanes[0].tokens < 1024); + assert!(!s.request(short).unwrap().deferred_prefill); + let f0 = Fence(s.submitted.0 + 1); + s.commit(&c0, f0).unwrap(); + assert!(s.request(short).unwrap().deferred_prefill); + assert!(s.request(short).unwrap().checkpoint_capture.is_none()); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let rec0 = completion_records(&s, &c0, f0, 0); + s.complete(f0, &rec0, gpu_time(10 * MS)).unwrap(); + let req0 = s.request(short).unwrap(); + assert_eq!(req0.accounting.first_output_wait_ns, short_arrival); + assert!(req0.accounting.last_progress_ns > short_arrival); + assert!(req0.deferred_prefill); + let consumed_after_c0 = req0.consumed_tokens as usize; + assert!(consumed_after_c0 > 0 && consumed_after_c0 < 1024); + + // Chunk 1: second non-terminal Prefill chunk while deferred_prefill == true. + s.advance_to(s.now_ns + 50 * MS).unwrap(); + let c1 = s.phase_plan(GraphKind::Prefill, Some(short)); + assert_eq!(c1.kind, GraphKind::Prefill); + assert!(consumed_after_c0 + c1.lanes[0].tokens < 1024); + let f1 = Fence(s.submitted.0 + 1); + s.commit(&c1, f1).unwrap(); + assert!(s.request(short).unwrap().deferred_prefill); + assert!(s.request(short).unwrap().checkpoint_capture.is_none()); + s.advance_to(s.now_ns + 5 * MS).unwrap(); + let rec1 = completion_records(&s, &c1, f1, 0); + s.complete(f1, &rec1, gpu_time(5 * MS)).unwrap(); + let req1 = s.request(short).unwrap(); + assert_eq!(req1.accounting.first_output_wait_ns, short_arrival); + assert!(req1.deferred_prefill); + + // 2. Prompt exceeding max_terminal at admission (3072 > 2048) resets first_output_wait_ns + // on every non-terminal Prefill chunk, including once its remaining suffix drops <= 2048. + let long = add(&mut s, 3, 3072, 64); + let long_arrival = s.now_ns; + initialize(&mut s, long); + s.advance_to(long_arrival + 100 * MS).unwrap(); + for _ in 0..3 { + let lp = s.phase_plan(GraphKind::Prefill, Some(long)); + assert_eq!(lp.kind, GraphKind::Prefill); + let lf = Fence(s.submitted.0 + 1); + s.commit(&lp, lf).unwrap(); + assert!(s.request(long).unwrap().checkpoint_capture.is_none()); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let lr = completion_records(&s, &lp, lf, 0); + s.complete(lf, &lr, gpu_time(10 * MS)).unwrap(); + assert_eq!( + s.request(long).unwrap().accounting.first_output_wait_ns, + s.now_ns + ); + } + let long_rem = 3072 - s.request(long).unwrap().consumed_tokens as usize; + assert!(long_rem <= 2048 && long_rem > 0, "expected remaining suffix <= max_terminal, got {long_rem}"); + + // 3. RetentionRole::Message checkpoint split (checkpoint_capture.is_some(), role != Anchor) + // resets first_output_wait_ns even under an active age-priced decoder on a single-graph + // prompt. Uses a plain PREFILL engine where Prefill can arm boundary checkpoint captures. + let mut plain = interactive_engine(4, false); + plain.prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + plain.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }).unwrap(); + set_cost(&mut plain, GraphKind::Prefill, 1, 64, 5 * MS); + set_cost(&mut plain, GraphKind::Prefill, 1, 128, 7 * MS); + set_cost(&mut plain, GraphKind::Prefill, 1, 256, 12 * MS); + set_cost(&mut plain, GraphKind::Prefill, 1, 512, 24 * MS); + set_cost(&mut plain, GraphKind::Prefill, 1, 4096, 80 * MS); + set_cost(&mut plain, GraphKind::Snapshot, 1, 1, 1 * MS); + let plain_dec = add(&mut plain, 1, 64, 1024); + ready(&mut plain, &[plain_dec]); + assert!(plain.policy.decode_age_price > 0.0 && plain.has_active_age_priced_stream()); + let msg = plain + .admit(RequestSpec { + prompt: vec![55; 204], + message_boundaries: vec![128, 202], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let msg_arrival = plain.now_ns; + initialize(&mut plain, msg); + plain.advance_to(msg_arrival + 100 * MS).unwrap(); + let msg_plan = plain.phase_plan(GraphKind::Prefill, Some(msg)); + assert_eq!(msg_plan.kind, GraphKind::Prefill); + assert_eq!(msg_plan.lanes[0].tokens, 128); + let msg_fence = Fence(plain.submitted.0 + 1); + plain.commit(&msg_plan, msg_fence).unwrap(); + assert_eq!( + plain.request(msg).unwrap().checkpoint_capture.map(|c| (c.role, c.endpoint)), + Some((RetentionRole::Message, 128)) + ); + plain.advance_to(plain.now_ns + 7 * MS).unwrap(); + let msg_rec = completion_records(&plain, &msg_plan, msg_fence, 0); + plain.complete(msg_fence, &msg_rec, gpu_time(7 * MS)).unwrap(); + assert_eq!( + plain.request(msg).unwrap().accounting.first_output_wait_ns, + plain.now_ns + ); + + // 4. PolicyConfig::throughput() (decode_age_price == 0.0) resets first_output_wait_ns + // on non-terminal Prefill chunks even when an active terminal-cleanup stream makes + // has_active_age_priced_stream() true. + let mut tp = make_scheduler(PolicyConfig::throughput()); + assert_eq!(tp.policy.decode_age_price, 0.0); + assert!(tp.policy.terminal_age_price > 0.0); + let cleaning = add(&mut tp, 1, 64, 1); + initialize(&mut tp, cleaning); + let cleaning_now = tp.now_ns; + { + let r = tp.request_mut(cleaning).unwrap(); + r.phase = RequestPhase::Snapshot; + r.boundary_capture = None; + r.accounting.terminal_since_ns = Some(cleaning_now); + } + assert!(super::policy::terminal_cleanup(tp.request(cleaning).unwrap())); + assert!(tp.has_active_age_priced_stream()); + + let tp_prompt = add(&mut tp, 2, 1024, 64); + let tp_arrival = tp.now_ns; + initialize(&mut tp, tp_prompt); + tp.advance_to(tp_arrival + 100 * MS).unwrap(); + let tp_plan = tp.phase_plan(GraphKind::Prefill, Some(tp_prompt)); + assert_eq!(tp_plan.kind, GraphKind::Prefill); + assert!(tp_plan.lanes[0].tokens > 0 && tp_plan.lanes[0].tokens < 1024); + let tp_fence = Fence(tp.submitted.0 + 1); + tp.commit(&tp_plan, tp_fence).unwrap(); + assert!(tp.request(tp_prompt).unwrap().checkpoint_capture.is_none()); + tp.advance_to(tp.now_ns + 10 * MS).unwrap(); + let tp_rec = completion_records(&tp, &tp_plan, tp_fence, 0); + tp.complete(tp_fence, &tp_rec, gpu_time(10 * MS)).unwrap(); + assert_eq!( + tp.request(tp_prompt).unwrap().accounting.first_output_wait_ns, + tp.now_ns + ); +} + +#[test] +fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() { + let mut s = prefill_catalog_engine( + SchedulerLimits { + max_active: 8, + request_slots: 8, + max_sequence_tokens: 8192, + prefill_chunk_size: 2048, + pages: 4096, + snapshots: 256, + }, + &[128, 256, 512, 1024, 2048], + &[256, 512, 1024, 2048], + true, + |cap| match cap { + 128 => 5 * MS, + 256 => 8 * MS, + 512 => 10 * MS, + 1024 => 40 * MS, + 2048 => 120 * MS, + _ => 200 * MS, + }, + |cap| match cap { + 256 => 10 * MS, + 512 => 18 * MS, + 1024 => 45 * MS, + 2048 => 130 * MS, + _ => 200 * MS, + }, + ); + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }) + .unwrap(); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 1 * MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 10 * MS); + + let decoder = add(&mut s, 1, 64, 1024); + ready(&mut s, &[decoder]); + + // Case 1: Single-prefill-eligible prompt (1536 <= max_terminal=2048) with interior + // RetentionRole::Anchor at 1534 (prompt_tokens - 2). After running non-terminal + // Prefill(512) chunks (deferred_prefill = true), the completing TerminalPrefill(512) + // landing on cut=1534 (tokens=510) credits first_output_value across the reconciled + // segment (1534 - 0) / 1536 without inflating prefill_token * 510, beating both a + // smaller non-terminal Prefill(256) chunk and the active decoder under waiting age. + let single = s + .admit(RequestSpec { + prompt: vec![11; 1536], + message_boundaries: vec![1534], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let arrival = s.now_ns; + initialize(&mut s, single); + s.advance_to(arrival + 50 * MS).unwrap(); + + while 1534 - s.request(single).unwrap().consumed_tokens as usize > 512 { + let px = s.phase_plan(GraphKind::Prefill, Some(single)); + assert_eq!(px.kind, GraphKind::Prefill); + assert_eq!(px.token_capacity, 512); + let fx = Fence(s.submitted.0 + 1); + s.commit(&px, fx).unwrap(); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let rx = completion_records(&s, &px, fx, 0); + s.complete(fx, &rx, gpu_time(10 * MS)).unwrap(); + } + + // Step the active decoder steadily for 1,000 ms so the decoder stays at + // steady-state delivery fairness while `single` accumulates waiting age. + for _ in 0..100 { + let dp = s.phase_plan(GraphKind::Decode, None); + assert_eq!(dp.kind, GraphKind::Decode); + let df = Fence(s.submitted.0 + 1); + s.commit(&dp, df).unwrap(); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let dr = completion_records(&s, &dp, df, 1); + s.complete(df, &dr, gpu_time(10 * MS)).unwrap(); + } + { + let _scope = s.checkpoint_planning_scope(); + let req = s.request(single).unwrap(); + let consumed = req.consumed_tokens as usize; + let to_cut = 1534 - consumed; + assert!(req.deferred_prefill); + assert_eq!(consumed, 1024); + assert_eq!(to_cut, 510); + assert_eq!(req.prefix_tokens, 0); + assert_eq!(s.estimated_checkpoint_cut(req), Some(1534)); + assert!(s.fits_single_prefill_from(req, req.admission_reused_tokens as usize)); + + let (values, _, _) = s.lane_values(s.window_remaining().unwrap()); + let val = values[req.handle.slot as usize]; + assert!(val.first_output_value > 0.0); + + let boosted = s.lane_value_for_tokens_within( + req, + GraphKind::TerminalPrefill, + to_cut, + 0, + 18 * MS, + val, + ); + let expected_boosted = + val.prefill_token * to_cut as f64 + val.first_output_value * (1534.0 / 1536.0); + let unboosted = val.prefill_within(to_cut, req.initial_prefill_tokens(), false); + assert!( + (boosted - expected_boosted).abs() < 1e-9, + "expected reconciled credit {expected_boosted}, got {boosted}" + ); + assert!( + boosted > unboosted + 0.5 * val.first_output_value, + "reconciled credit must exceed chunk-only credit ({boosted} vs {unboosted})" + ); + + // Case 3: Non-terminal Prefill chunk stopping strictly before cut (end < 1534) + // must NOT receive the reconciled boost. + let non_terminal_val = s.lane_value_for_tokens_within( + req, + GraphKind::Prefill, + 256, + 0, + 8 * MS, + val, + ); + let expected_partial = + val.prefill_within(256, req.initial_prefill_tokens(), false); + assert!( + (non_terminal_val - expected_partial).abs() < 1e-9, + "non-terminal Prefill before cut must not receive reconciled boost: {non_terminal_val} vs {expected_partial}" + ); + } + + // Verify real planner selects TerminalPrefill(512) landing on cut=1534 over Prefill(256) + // and over the active decoder under waiting age. + let chosen = s.plan().unwrap(); + assert_eq!(chosen.kind, GraphKind::TerminalPrefill); + assert_eq!(chosen.token_capacity, 512); + assert_eq!(chosen.lanes[0].request, single); + assert_eq!(chosen.lanes[0].tokens, 510); + + // Case 2: Multi-chunk prompt exceeding max_terminal at admission (3072 > 2048) with + // interior RetentionRole::Anchor at 3070 must NOT receive the reconciled boost even + // after deferred_prefill == true and remaining tokens drop <= max_terminal. + let multi = s + .admit(RequestSpec { + prompt: vec![22; 3072], + message_boundaries: vec![3070], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + initialize(&mut s, multi); + while 3070 - s.request(multi).unwrap().consumed_tokens as usize > 512 { + let pm = s.phase_plan(GraphKind::Prefill, Some(multi)); + assert_eq!(pm.kind, GraphKind::Prefill); + let fm = Fence(s.submitted.0 + 1); + s.commit(&pm, fm).unwrap(); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let rm = completion_records(&s, &pm, fm, 0); + s.complete(fm, &rm, gpu_time(10 * MS)).unwrap(); + } + s.advance_to(s.now_ns + 1200 * MS).unwrap(); + { + let _scope = s.checkpoint_planning_scope(); + let req = s.request(multi).unwrap(); + let to_cut = 3070 - req.consumed_tokens as usize; + assert!(req.deferred_prefill); + assert_eq!(s.estimated_checkpoint_cut(req), Some(3070)); + assert!(!s.fits_single_prefill_from(req, req.admission_reused_tokens as usize)); + let (values, _, _) = s.lane_values(s.window_remaining().unwrap()); + let val = values[req.handle.slot as usize]; + assert!(val.first_output_value > 0.0); + let actual = s.lane_value_for_tokens_within( + req, + GraphKind::TerminalPrefill, + to_cut, + 0, + 18 * MS, + val, + ); + let expected = val.prefill_within(to_cut, req.initial_prefill_tokens(), false); + assert!( + (actual - expected).abs() < 1e-9, + "multi-chunk prompt (> max_terminal at admission) must not get reconciled boost: {actual} vs {expected}" + ); + } + + // Case 4a: TerminalPrefill with !deferred_prefill stopping at interior cut=1534 is unchanged. + let fresh_cut = s + .admit(RequestSpec { + prompt: vec![33; 1536], + message_boundaries: vec![1534], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + initialize(&mut s, fresh_cut); + s.advance_to(s.now_ns + 500 * MS).unwrap(); + { + let _scope = s.checkpoint_planning_scope(); + let req = s.request(fresh_cut).unwrap(); + assert!(!req.deferred_prefill); + assert_eq!(s.estimated_checkpoint_cut(req), Some(1534)); + let (values, _, _) = s.lane_values(s.window_remaining().unwrap()); + let val = values[req.handle.slot as usize]; + assert!(val.first_output_value > 0.0); + let actual = s.lane_value_for_tokens_within( + req, + GraphKind::TerminalPrefill, + 1534, + 0, + 130 * MS, + val, + ); + let expected = val.prefill_within(1534, req.initial_prefill_tokens(), false); + assert!( + (actual - expected).abs() < 1e-9, + "!deferred_prefill TerminalPrefill at cut must remain unchanged: {actual} vs {expected}" + ); + } + + // Case 4b: Deferred TerminalPrefill reaching prompt_tokens (first_output == true, no interior cut) + // is unchanged and already credits full 1.0 * first_output_value + output_token. + let no_cut = add(&mut s, 44, 1536, 64); + initialize(&mut s, no_cut); + let pn = s.phase_plan(GraphKind::Prefill, Some(no_cut)); + assert_eq!(pn.kind, GraphKind::Prefill); + let fn0 = Fence(s.submitted.0 + 1); + s.commit(&pn, fn0).unwrap(); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let rn0 = completion_records(&s, &pn, fn0, 0); + s.complete(fn0, &rn0, gpu_time(10 * MS)).unwrap(); + s.advance_to(s.now_ns + 500 * MS).unwrap(); + { + let _scope = s.checkpoint_planning_scope(); + let req = s.request(no_cut).unwrap(); + let remaining = req.prompt_tokens - req.consumed_tokens as usize; + assert!(req.deferred_prefill); + assert!(s.estimated_checkpoint_cut(req).is_none_or(|cut| cut == req.prompt_tokens)); + let (values, _, _) = s.lane_values(s.window_remaining().unwrap()); + let val = values[req.handle.slot as usize]; + assert!(val.first_output_value > 0.0); + let actual = s.lane_value_for_tokens_within( + req, + GraphKind::TerminalPrefill, + remaining, + 0, + 45 * MS, + val, + ); + let expected = val.prefill_within(remaining, req.initial_prefill_tokens(), true); + assert!( + (actual - expected).abs() < 1e-9, + "first_output == true TerminalPrefill must remain unchanged: {actual} vs {expected}" + ); + } +} diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index dfe404364..c923c5f8e 100644 --- a/helios/src/scheduler/service.rs +++ b/helios/src/scheduler/service.rs @@ -294,7 +294,11 @@ impl RequestScheduler { } else { &self.prefill_catalog }; - let terminal_only = self.prefill_requires_terminal_completion_from(request, start, cut); + let terminal_only = if self.has_active_age_priced_stream() { + self.prefill_must_complete_terminally_from(request, start, cut) + } else { + self.prefill_requires_terminal_completion_from(request, start, cut) + }; for &capacity in catalog { let work = self.prefill_work_from(request, start, capacity, cut); if work == 0 { diff --git a/scripts/scheduling_sim/learning.py b/scripts/scheduling_sim/learning.py index 24bef6b5c..a2aea2958 100644 --- a/scripts/scheduling_sim/learning.py +++ b/scripts/scheduling_sim/learning.py @@ -433,7 +433,7 @@ def parser(): help="targeted probe peer-delay budget in request-ms; omitted disables the bound") result.add_argument("--harm-alpha", dest="harm_alpha", type=float, help="targeted peer-delay credit fraction; omitted disables peer-delay financing") - result.add_argument("--initial-discovery", choices=("productive", "native")) + result.add_argument("--initial-discovery", choices=("productive", "native", "interpolated")) result.add_argument("--mean-estimator", choices=("arithmetic", "ema")) result.add_argument("--partial-blocks", action="store_true", default=None, help="condition timing uncertainty on fractional unfinished blocks") diff --git a/scripts/scheduling_sim/learning_policy.py b/scripts/scheduling_sim/learning_policy.py index 3ce8b06c5..af99086aa 100644 --- a/scripts/scheduling_sim/learning_policy.py +++ b/scripts/scheduling_sim/learning_policy.py @@ -77,8 +77,8 @@ def __post_init__(self): raise ValueError("peer service-delay fraction must be in [0, 1)") if self.harm_alpha is not None and self.probe_harm_ms is not None: raise ValueError("hard and funded peer service-delay controls are mutually exclusive") - if self.initial_discovery not in ("productive", "native"): - raise ValueError("initial discovery must be productive or native") + if self.initial_discovery not in ("productive", "native", "interpolated"): + raise ValueError("initial discovery must be productive, native, or interpolated") if self.mean_estimator not in ("arithmetic", "ema"): raise ValueError("operational mean must be arithmetic or ema") if type(self.partial_blocks) is not bool: @@ -196,17 +196,58 @@ def _actions(self, views: list[View], costs: dict[str, float | None], result.append(action) return result + def _natural_fit_prefill_capacity(self, remaining: int) -> int | None: + best = None + for graph in self.catalog: + if graph.prefill_capacity and not graph.decode_capacity: + work = min(remaining, graph.prefill_capacity) + if work and (best is None or work > best[0] or (work == best[0] and graph.prefill_capacity < best[1])): + best = (work, graph.prefill_capacity) + return best[1] if best is not None else None + + def _interpolated_prefill_duration(self, target: GraphSpec, means: dict[str, float | None]) -> float | None: + if not target.prefill_capacity or target.decode_capacity: + return None + lo = hi = decode_floor = None + for graph in self.catalog: + duration = means[graph.name] + if duration is None or duration <= 0: + continue + if graph.decode_capacity and not graph.prefill_capacity: + decode_floor = duration if decode_floor is None else min(decode_floor, duration) + continue + if not graph.prefill_capacity or graph.decode_capacity or graph.prefill_capacity == target.prefill_capacity: + continue + cap = graph.prefill_capacity + if cap > target.prefill_capacity: + if hi is None or cap < hi[0] or (cap == hi[0] and duration < hi[1]): + hi = (cap, duration) + elif lo is None or cap > lo[0] or (cap == lo[0] and duration < lo[1]): + lo = (cap, duration) + if hi is None: + return None + c_hi, t_hi = hi + if lo is not None: + c_lo, t_lo = lo + elif decode_floor is not None: + c_lo, t_lo = 0, min(decode_floor, t_hi) + else: + return None + if t_hi <= t_lo: + return t_hi + return t_lo + (t_hi - t_lo) * (target.prefill_capacity - c_lo) / (c_hi - c_lo) + def _rank_key(self, action: Action, clocks: dict[str, float]): return (-self.utility.score(action), action.graph.duration_ms, - min(clocks[l.name] for l in action.lanes), + min(clocks[lane.name] for lane in action.lanes), action.graph.prefill_capacity + action.graph.decode_capacity * action.graph.width, - action.graph.name, tuple(l.name for l in action.lanes)) + action.graph.name, tuple(lane.name for lane in action.lanes)) def _bootstrap_key(self, action: Action, clocks: dict[str, float]): return (-sum(self._unknown_lane_value(lane) for lane in action.lanes), - min(clocks[l.name] for l in action.lanes), + min(clocks[lane.name] for lane in action.lanes), action.graph.prefill_capacity + action.graph.decode_capacity * action.graph.width, - action.graph.name, tuple(l.name for l in action.lanes)) + action.graph.name, tuple(lane.name for lane in action.lanes)) def _ensure_estimates(self, names: set[str], means: dict[str, float | None], incumbent: Action | None): @@ -232,7 +273,8 @@ def choose(self, views: list[View], now_ms: float) -> Decision: if not isfinite(now_ms) or now_ms < self._now_ms: raise ValueError("learning scheduler clock must be finite and monotonic") means = self._means(now_ms) - native_discovery = (self.config.initial_discovery == "native" + interpolated_discovery = self.config.initial_discovery == "interpolated" + native_discovery = (self.config.initial_discovery in ("native", "interpolated") or self.config.policy == "retained-refresh") graphs = tuple(self._graph(g, means[g.name]) for g in self.catalog) self.utility.prepare(views, graphs, now_ms, @@ -252,9 +294,43 @@ def choose(self, views: list[View], now_ms: float) -> Decision: targeted = {} unknown = [a for a in actions if means[a.graph.name] is None] native_unknown = [] + interpolated: dict[str, float] = {} + interpolated_actions: list[Action] = [] + active_age_price = (interpolated_discovery + and self.utility.config.age_price > 0.0 + and bool(self.utility.ages)) if native_discovery: - native_unknown = [a for a in self._actions(views, means) - if means[a.graph.name] is None and not self.estimates[a.graph.name].count] + raw_native = [a for a in self._actions(views, means) + if means[a.graph.name] is None and not self.estimates[a.graph.name].count] + if active_age_price: + nat_fit = {v.name: self._natural_fit_prefill_capacity(v.remaining_prefill) + for v in views if v.remaining_prefill} + raw_native_names = {a.graph.name for a in raw_native} + for graph in self.catalog: + if graph.name in raw_native_names and graph.prefill_capacity and not graph.decode_capacity: + estimate = self._interpolated_prefill_duration(graph, means) + if estimate is not None: + interpolated[graph.name] = estimate + for action in raw_native: + graph = action.graph + if graph.prefill_capacity and not graph.decode_capacity: + if graph.name in interpolated: + continue + if graph.prefill_capacity != nat_fit.get(action.lanes[0].name): + continue + native_unknown.append(action) + if interpolated: + interp_graphs = tuple(self._graph(g, interpolated[g.name]) + for g in self.catalog if g.name in interpolated) + interpolated_actions = [ + action for action in candidates(views, interp_graphs, self.value, + lane_value=self.utility.action_lane_value) + if action.graph.prefill_capacity <= (nat_fit.get(action.lanes[0].name) or 0) + ] + else: + native_unknown = raw_native + best_scored = (min(measured + interpolated_actions, key=lambda a: self._rank_key(a, clocks)) + if (measured or interpolated_actions) else None) soft_harm = self.config.policy == "targeted" and self.config.harm_alpha is not None phases = {"prefill" if lane.prefill else "decode" for lane in incumbent.lanes} if incumbent else set() unfunded_phases = sorted(phase for phase in phases if self.harm_credit_ms[phase] < HARM_CAP_MS) @@ -271,6 +347,9 @@ def choose(self, views: list[View], now_ms: float) -> Decision: elif native_unknown: selected = min(native_unknown, key=lambda a: self._bootstrap_key(a, clocks)) category, reason = "bootstrap", "initial_unknown_graph" + elif best_scored is not None and best_scored.graph.name in interpolated: + selected = best_scored + category, reason = "bootstrap", "interpolated_prefill_discovery" elif self.config.policy == "retained-refresh": selected = incumbent stale = [action for action in measured if action.graph.name != incumbent.graph.name @@ -298,16 +377,20 @@ def choose(self, views: list[View], now_ms: float) -> Decision: selected, reason = incumbent, "incumbent" else: category = "probe" - score = (sum(self._unknown_lane_value(lane) for lane in selected.lanes) - if means[selected.graph.name] is None and not sampled - else self.utility.score(selected)) + priced = (means[selected.graph.name] is not None + or selected.graph.name in sampled + or selected.graph.name in interpolated) + score = (self.utility.score(selected) if priced + else sum(self._unknown_lane_value(lane) for lane in selected.lanes)) metadata = {"now_ms": now_ms, "opportunity": opportunity, "opportunity_index": self.opportunities + int(opportunity), "balance_before_ms": self.credit_ms, "mean_costs_ms": means, "sampled_costs_ms": sampled, "log_scale": self.utility.log_scale, "incumbent_graph": incumbent.graph.name if incumbent else None, "incumbent_score": self.utility.score(incumbent) if incumbent else None, - "score_kind": "unknown_value" if means[selected.graph.name] is None and not sampled else "value_rate"} + "score_kind": "value_rate" if priced else "unknown_value"} + if interpolated: + metadata["interpolated_costs_ms"] = interpolated if self.config.policy == "targeted": metadata["targeted"] = {"occupied_ms": self._occupied_ms, "refresh_busy_ms": self.config.refresh_busy_ms, **targeted} @@ -700,7 +783,7 @@ def snapshot(self) -> dict: "balances_ms": dict(self.harm_credit_ms), "ordinary_lane_request_ms": dict(self.harm_ordinary_ms), "charged_request_ms": dict(self.harm_charged_ms)} - if self.config.initial_discovery == "native" or self.config.policy == "retained-refresh": + if self.config.initial_discovery in ("native", "interpolated") or self.config.policy == "retained-refresh": result["initial_discovery_count"] = self.bootstrap_count result["initial_discovery_ms"] = self.bootstrap_ms return result diff --git a/scripts/scheduling_sim/workloads.py b/scripts/scheduling_sim/workloads.py index 2536259c8..b2ae84d83 100644 --- a/scripts/scheduling_sim/workloads.py +++ b/scripts/scheduling_sim/workloads.py @@ -53,3 +53,54 @@ def decode(name, accepted=7, output=128, **kwargs): "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)], } + + +def gb10_catalog(max_chunk: int = 16_384) -> tuple[Graph, ...]: + """Synthetic 16K prefill and speculative decode timings modeled after 4x GB10 TP4.""" + prefill_ms = { + 128: 45.0, + 256: 65.0, + 512: 98.0, + 1024: 150.0, + 2048: 227.0, + 4096: 380.0, + 6144: 534.0, + 8192: 687.0, + 10240: 841.0, + 12288: 995.0, + 14336: 1148.0, + 16384: 1302.0, + } + graphs = [ + Graph(f"prefill-{cap}", duration_ms, prefill_capacity=cap) + for cap, duration_ms in prefill_ms.items() + if cap <= max_chunk + ] + decode_ms = { + 1: {1: 18.0, 3: 28.0, 4: 32.0, 8: 48.0}, + 2: {1: 22.0, 3: 36.0, 4: 41.0, 8: 62.0}, + 4: {1: 28.0, 3: 49.0, 4: 56.0, 8: 84.0}, + 8: {1: 42.0, 3: 72.0, 4: 82.0, 8: 120.0}, + 12: {1: 58.0, 3: 94.0, 4: 108.0, 8: 158.0}, + 16: {1: 72.0, 3: 108.0, 4: 124.0, 8: 182.0}, + } + for batch, widths in decode_ms.items(): + for width, duration_ms in widths.items(): + graphs.append(Graph(f"decode-b{batch}-w{width}", duration_ms, + decode_capacity=batch, width=width)) + return tuple(graphs) + + +def prefill_storm_gb10() -> list[Request]: + """Twelve active interactive decode streams contending with four 24K-30K cold prompts.""" + acc = (0.736,) * 7 + decoders = [ + Request(f"interactive-{i}", 0, 340, acceptance=acc, max_new_tokens=512) + for i in range(12) + ] + heavy_prompts = (24_000, 26_000, 28_000, 30_000) + prefillers = [ + Request(f"heavy-{i}", prompt, 96, arrival_ms=200.0 * i, acceptance=acc, max_new_tokens=256) + for i, prompt in enumerate(heavy_prompts) + ] + return decoders + prefillers diff --git a/tests/test_scheduling_learning_experiments.py b/tests/test_scheduling_learning_experiments.py index 639129c1a..bd56da234 100644 --- a/tests/test_scheduling_learning_experiments.py +++ b/tests/test_scheduling_learning_experiments.py @@ -758,3 +758,21 @@ def test_retained_refresh_defaults_to_retaining_idle_credit_and_validate_rejects with pytest.raises(SystemExit) as error: main(["--preset", "validate", "--configs", str(tmp_path / "unused.json"), "--retain-idle-credit"]) assert error.value.code == 2 + + +def test_interpolated_initial_discovery_cli_and_validate_rejection(tmp_path): + from scripts.scheduling_sim.learning import build_configurations, configuration_id, main, parser + from scripts.scheduling_sim.learning_policy import PolicyConfig + + cfg = build_configurations(parser().parse_args([ + "--policies", "retained-refresh", "--alpha", "0.002", "--initial-discovery", "interpolated", + ]), PolicyConfig)[-1] + assert cfg.config.initial_discovery == "interpolated" + assert cfg.id == "retained-refresh:funded:cumulative:alpha=0.002:initial_discovery=interpolated" + assert configuration_id(PolicyConfig(policy="retained-refresh", alpha=0.002)) == ( + "retained-refresh:funded:cumulative:alpha=0.002" + ) + with pytest.raises(SystemExit) as error: + main(["--preset", "validate", "--configs", str(tmp_path / "unused.json"), + "--initial-discovery", "interpolated"]) + assert error.value.code == 2 diff --git a/tests/test_scheduling_learning_policy.py b/tests/test_scheduling_learning_policy.py index c4fa7deaf..1aa58b0e9 100644 --- a/tests/test_scheduling_learning_policy.py +++ b/tests/test_scheduling_learning_policy.py @@ -1578,3 +1578,142 @@ def test_retained_refresh_retain_idle_credit_recovers_across_short_bursts_withou assert probed[:2] == ["large", "small"] assert large_reexpired_before_small assert s.choose([view("p", 65_536)], now).action.graph.name == "small" + + + +def test_interpolated_prefill_discovery_prices_smaller_shapes_under_active_age_price(): + graphs = ( + GraphSpec("prefill-256", prefill_capacity=256), + GraphSpec("prefill-512", prefill_capacity=512), + GraphSpec("prefill-2048", prefill_capacity=2048), + GraphSpec("prefill-4096", prefill_capacity=4096), + GraphSpec("prefill-16384", prefill_capacity=16384), + GraphSpec("decode-4", decode_capacity=4), + ) + s = scheduler("retained-refresh", catalog=graphs, initial_discovery="interpolated", alpha=0.002) + # Without a larger measured prefill peer or decode floor, interpolation returns None. + assert s._interpolated_prefill_duration(graphs[2], s._means(0)) is None + seed(s, "prefill-16384", 1302.0) + assert s._interpolated_prefill_duration(graphs[2], s._means(0)) is None + seed(s, "decode-4", 28.0) + # Linear interpolation from decode floor (0, 28) to prefill-16384 (16384, 1302). + assert s._interpolated_prefill_duration(graphs[3], s._means(0)) == pytest.approx( + 28.0 + (1302.0 - 28.0) * 4096 / 16384 + ) + decs = [View(f"dec-{i}", 0, 128, (0.0,) * 7, last_service_ms=0.0) for i in range(4)] + prompt = View("prompt", 24_000, 64, (0.0,) * 7, last_service_ms=0.0) + # Baseline native discovery immediately preempts decode with unknown-first bootstrap; + # interpolated discovery lets ordinary decode serve active streams first. + native = scheduler("retained-refresh", catalog=graphs, initial_discovery="native", alpha=0.002) + seed(native, "prefill-16384", 1302.0) + seed(native, "decode-4", 28.0) + assert native.choose(decs + [prompt], 0.0).category == "bootstrap" + first = s.choose(decs + [prompt], 0.0) + assert first.category == "ordinary" + assert first.action.graph.name == "decode-4" + assert "prefill-2048" in first.metadata["interpolated_costs_ms"] + # Step decode until prompt fairness rises; interpolated smaller prefill beats the 1302 ms + # 16384 chunk and launches as bootstrap without spending or earning exploration credit. + now = 0.0 + chosen = None + for op in range(1, 25): + decision = s.choose(decs + [prompt], now) + if decision.reason == "interpolated_prefill_discovery": + chosen = decision + break + now = finish(s, decision, 28.0, op) + decs = [View(v.name, 0, v.output_budget - 1, v.acceptance, last_service_ms=now) for v in decs] + assert chosen is not None + assert chosen.category == "bootstrap" + assert chosen.estimate_ms is None + assert chosen.metadata["score_kind"] == "value_rate" + assert chosen.action.graph.prefill_capacity < 16384 + credit_before = s.credit_ms + finish(s, chosen, 227.0, 99) + assert s.credit_ms == credit_before + assert s.probe_ms == 0.0 + assert s.bootstrap_count == 1 + assert s.snapshot()["initial_discovery_count"] == 1 + + +def test_interpolated_prefill_discovery_blocks_refresh_displacement_padding_and_nonmonotonic(): + graphs = ( + GraphSpec("prefill-512", prefill_capacity=512), + GraphSpec("prefill-2048", prefill_capacity=2048), + GraphSpec("prefill-4096", prefill_capacity=4096), + GraphSpec("prefill-16384", prefill_capacity=16384), + GraphSpec("decode-4", decode_capacity=4), + ) + s = scheduler("retained-refresh", catalog=graphs, initial_discovery="interpolated", alpha=0.002) + # Seed stale prefill-16384 and fresh decode-4; once prompt wins via interpolation while full + # refresh credit is available, bootstrap must return directly without stale-refresh displacement. + seed(s, "prefill-16384", 1302.0, end=0.0) + seed(s, "decode-4", 28.0, end=40_000.0) + decs = [View(f"dec-{i}", 0, 128, (0.0,) * 7, last_service_ms=40_000.0) for i in range(4)] + prompt = View("prompt", 24_000, 64, (0.0,) * 7, last_service_ms=40_000.0) + now = 40_000.0 + for op in range(1, 25): + s.credit_ms = 0.0 if op < 15 else s.config.credit_cap_ms + decision = s.choose(decs + [prompt], now) + if decision.action.graph.prefill_capacity: + assert decision.category == "bootstrap" + assert decision.reason == "interpolated_prefill_discovery" + assert decision.action.graph.prefill_capacity < 16384 + break + now = finish(s, decision, 28.0, op) + decs = [View(v.name, 0, v.output_budget - 1, v.acceptance, last_service_ms=now) for v in decs] + else: + raise AssertionError("interpolated prefill discovery did not trigger") + + # Oversized padded unmeasured prefill (> nat_fit) is never interpolated or selected. + s_pad = scheduler("retained-refresh", catalog=graphs, initial_discovery="interpolated") + seed(s_pad, "prefill-512", 500.0) + seed(s_pad, "prefill-16384", 600.0) + seed(s_pad, "decode-4", 28.0) + short_views = [View("dec", 0, 128, (0.0,) * 7, last_service_ms=0.0), + View("short", 512, 64, (0.0,) * 7, last_service_ms=0.0)] + d_pad = s_pad.choose(short_views, 0.0) + assert d_pad.action.graph.prefill_capacity <= 512 + + # Non-monotonic measured peer timings (t_lo > t_hi) clamp safely to t_hi. + s_inv = scheduler("retained-refresh", catalog=graphs, initial_discovery="interpolated") + seed(s_inv, "prefill-512", 500.0) + seed(s_inv, "prefill-16384", 300.0) + assert s_inv._interpolated_prefill_duration(graphs[2], s_inv._means(0)) == 300.0 + + +def test_interpolated_prefill_discovery_preserves_native_baseline_when_zero_age_or_solo(): + graphs = ( + GraphSpec("prefill-256", prefill_capacity=256), + GraphSpec("prefill-2048", prefill_capacity=2048), + GraphSpec("prefill-16384", prefill_capacity=16384), + GraphSpec("decode-1", decode_capacity=1), + ) + # 1. age_price == 0.0 with active decoders strictly matches baseline native discovery. + zero_age = UtilityConfig(16, 4, 100, 0.0, "service") + native_zero = LearningScheduler(Value(64), zero_age, graphs, + PolicyConfig(policy="retained-refresh", initial_discovery="native"), seed=7) + interp_zero = LearningScheduler(Value(64), zero_age, graphs, + PolicyConfig(policy="retained-refresh", initial_discovery="interpolated"), seed=7) + for sched in (native_zero, interp_zero): + seed(sched, "prefill-16384", 1302.0) + seed(sched, "decode-1", 18.0) + views = [View("dec", 0, 128, (0.0,) * 7, last_service_ms=0.0), + View("prompt", 24_000, 64, (0.0,) * 7, last_service_ms=0.0)] + d_nat, d_int = native_zero.choose(views, 100.0), interp_zero.choose(views, 100.0) + assert d_nat.action == d_int.action + assert d_nat.category == d_int.category == "bootstrap" + assert d_nat.reason == d_int.reason == "initial_unknown_graph" + assert d_nat.score == d_int.score + + # 2. Solo prefill (age_price > 0, no active decoders) strictly matches baseline native discovery. + native_solo = scheduler("retained-refresh", catalog=graphs, initial_discovery="native") + interp_solo = scheduler("retained-refresh", catalog=graphs, initial_discovery="interpolated") + for sched in (native_solo, interp_solo): + seed(sched, "prefill-16384", 1302.0) + seed(sched, "decode-1", 18.0) + solo_views = [View("prompt", 24_000, 64, (0.0,) * 7, last_service_ms=0.0)] + s_nat, s_int = native_solo.choose(solo_views, 0.0), interp_solo.choose(solo_views, 0.0) + assert s_nat.action == s_int.action + assert s_nat.category == s_int.category == "bootstrap" + assert s_nat.reason == s_int.reason == "initial_unknown_graph" diff --git a/tests/test_scheduling_utility.py b/tests/test_scheduling_utility.py index d041f2a2d..4df35830b 100644 --- a/tests/test_scheduling_utility.py +++ b/tests/test_scheduling_utility.py @@ -12,7 +12,7 @@ from scripts.scheduling_sim.model import Action, Graph, Lane, Request, Value, View, expected_output from scripts.scheduling_sim.simulator import run from scripts.scheduling_sim.utility import ServicePrice, UtilityConfig, UtilityScheduler -from scripts.scheduling_sim.workloads import catalog, workloads +from scripts.scheduling_sim.workloads import catalog, gb10_catalog, prefill_storm_gb10, workloads def scheduler(*, beta=64, token=4, delivery=4, age=0, adaptation=100): @@ -533,3 +533,26 @@ def test_coalescing_surplus_vanishes_at_saturated_batch_and_single_token_budget( 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) + + +def test_gb10_prefill_storm_decode_age_pricing_avoids_one_second_stalls(): + graphs = gb10_catalog() + requests = prefill_storm_gb10() + balanced = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + throughput = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.0, "service")) + res_bal = run(requests, graphs, Value(64), scheduler=balanced, horizon_ms=30_000) + res_tp = run(requests, graphs, Value(64), scheduler=throughput, horizon_ms=30_000) + assert res_tp.summary["max_output_gap_ms"] > 1000.0 + assert res_bal.summary["max_output_gap_ms"] < 800.0 + assert res_bal.summary["max_output_gap_ms"] < res_tp.summary["max_output_gap_ms"] * 0.6 + first_interactive_done = min( + row["completion_ms"] + for row in res_bal.requests + if row["name"].startswith("interactive-") and row["completion_ms"] is not None + ) + contended_prefill_caps = { + e["prefill_capacity"] + for e in res_bal.trace + if e["prefill_capacity"] and e["start_ms"] < first_interactive_done + } + assert contended_prefill_caps and max(contended_prefill_caps) <= 4096 diff --git a/verification/helios-lifecycle/check.py b/verification/helios-lifecycle/check.py index 0c3bbdf47..5f59ec497 100644 --- a/verification/helios-lifecycle/check.py +++ b/verification/helios-lifecycle/check.py @@ -527,7 +527,7 @@ def run_aux(test): check_mutations(cargo, ROOT / "helios/src/scheduler.rs", CHECKS[7][1], [ ("deferred prefill small cut bypass", " if self.terminal_prefill_catalog.binary_search(&capacity).is_err() {\n" - " return if request.deferred_prefill && needs_terminal {\n" + " return if request.deferred_prefill {\n" " GraphKind::TerminalPrefill\n" " } else {\n" " GraphKind::Prefill\n"