From 5bf90854a648ac5970e5368e1ab21a38b6aa2615 Mon Sep 17 00:00:00 2001 From: yatesdr <6937857+yatesdr@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:25:31 -0500 Subject: [PATCH] helios/scheduler: price first-output waiting age on incumbent decode rounds Under the balanced scheduler policy (`decode_age_price = 0.1`), active decoding streams accumulate waiting-age utility scaled by their batch-feasible excluded wait while prompts waiting for their first output accumulate none. When a returning or newly arrived prompt competes against a large active decode cohort on a model without mixed prefill-decode graphs (for example, 8 to 16 concurrent decoders on DeepSeek-V4.1-Flash or Qwen3.8-Flash-Next), the prompt stalls for multiple seconds waiting for its token-service fairness price to climb high enough to displace a full-batch decode round. When an interior conversation-anchor checkpoint splits a single-chunk prompt into a main chunk, a boundary snapshot, and a short tail, the prompt incurs that wait twice because progress resets its waiting state while its service price drops on the first chunk. This change closes the asymmetry inside the shared Helios scheduler and the Python utility reference simulator without adding configuration flags, CLI options, model branches, new graph kinds, or `ServicePrice` exemptions: - `helios/src/scheduler/service.rs`: Extend delivery-reference selection with `delivery_references_and_decode_batch`, returning the fastest pure incumbent `Decode` or `Speculative` round's work-time `b_served * T_dec` (in stream-ms, excluding `Mixed` graphs and returning `0.0` when no measured decoder is active). For fixed-width packed speculative rounds, evaluate each measured packed shape's token budget directly so feasible batch capacity and per-slot delivery references are exact and slot-order invariant under heterogeneous verification lengths. - `helios/src/scheduler/utility.rs` and `helios/src/scheduler/policy.rs`: Add `LaneValue::first_output_value` and `LaneValue::prefill_within`. When `decode_age_price > 0.0` and `b_served * T_dec > 0.0`, each waiting prompt with `max_new_tokens > 0` receives waiting-age credit `decode_age_price * (b_served * T_dec) * age_ms * frac`, multiplying `decode_age_price * unit` before scaling by `b_served * T_dec * age_ms` to avoid premature overflow or `inf * 0 = NaN` under large finite prices. `frac = 1.0` when the step completes the prompt and `frac = work / initial_prefill` on partial chunks. The credit flows through prerequisite and two-stage continuation scoring (`Init`, `Restore`, `Vision`, `Snapshot`) without adding waiting prompts to the common `-T/2 * sum c_j` waiting-penalty sum. - `helios/src/scheduler.rs` and `helios/src/server/runtime.rs`: Track `RequestAccounting::first_output_wait_ns`. Preserve it across a prefill stopped at an armed interior `RetentionRole::Anchor` cut when the prompt otherwise fit in a single eligible prefill graph (including when the anchor coincides with the chosen chunk capacity or when a `TerminalPrefill` chunk clears `deferred_prefill` while landing on an interior anchor), while continuing to charge all measured token service truthfully in `observe_service`. Fold `readmitted_output_ns: Option` into `set_arrival` so admission timestamp assignment has no call-order hazard. Carry `Carried::last_output_ns` across preemption and forced-reasoning readmission, recording host-published forced-close timestamps when `close_reasoning` advances `publications` and taking the latest of graph and host publication timestamps. - `scripts/scheduling_sim/utility.py`, tests, and docs: Mirror the pure-decode zero-knob formula in `UtilityScheduler`, add Rust and Python unit tests for inertness, `b_served * T_dec` scaling, `Mixed` exclusion, packed speculative feasibility and slot-order invariance, large finite `decode_age_price` overflow/NaN safety, anchor-vs-message cut boundaries, multi-chunk `TerminalPrefill` deferred-state anchor preservation, pipelined prefill wait projection, forced-reasoning-close readmission (with and without prior graph publication), balanced burst coalescing, and oversubscribed/small-batch adversarial bursts, and reconcile `docs/scheduling-theory.md`, `docs/scheduling-utility.md`, and `docs/scheduling-runtime-design.md`. Result: - Paired zero-re-export `flare run` A/B on 4x DGX Spark GB10 (SM121, DeepSeek-V4.1-Flash-1017 TP4, `--scheduler-policy balanced`, zero errors): - Returning agent + K=8 decoders: TTFT p50 `2,812 -> 1,025 ms` (-63.5%), turns/min `13.21 -> 21.77` (+64.8%), bg gap p95/p99 `168.1 -> 151.0` / `334.1 -> 328.3 ms`. - Returning agent + K=16 decoders: TTFT p50 `5,265 -> 894 ms` (-83.0%), turns/min `8.75 -> 18.00` (+105.7%), bg gap p95 `211.1 -> 184.0 ms`, p99 `368.4 -> 463.5 ms`. - C=12 simultaneous burst: max TTFT `7,177 -> 5,416 ms` (-24.5%), gap p99 `183.9 -> 158.3 ms`. - Paired 4-visit ABAB returning-agent suite (closed 8x8, cold, single, sustained, burst at K=16): `closed` 6/6 gates (`73 -> 127` valid turns, +74%, TTFT p50 `6,493 -> 1,933 ms`, `step_cost` `0.840 -> 0.611`), `cold` 4/4 parity, `single` TTFT p50 `3,301 -> 590 ms` (-82%), `sustained` 26/26 valid (vs 24/26 on main, completing the 28K long return that main timed out), `burst` TTFT p50 `6,381 -> 1,668 ms` with higher p99/max gap (`376 -> 493 ms`, `426 -> 995 ms`). - `--scheduler-policy throughput` control (K=16): parity. - Paired zero-re-export `flare run` A/B on 2x DGX Spark GB10 (SM121, Qwen3.8-Flash-Next TP2, hybrid Mamba/GatedDeltaNet + Attention, zero errors): - Standalone prefill 8K/32K exact parity (+0.1%); batched decode C=1..32 parity to +6.5%; 45 s fixed-window returning agent + K=16 bg: TTFT p50 `4,324 -> 868 ms` (-79.9%), turns `9 -> 22` (+136%), streamed bg throughput `237.1 -> 234.1 ch/s` (-1.3% parity), bg gap p99 `334.5 -> 410.5 ms`; 35 s throughput control exact parity (`2,540 vs 2,539 ms`). Supporting evidence and limitations: - Rust (`--release`, Linux): `helios` (`runtime-core,server` lib: 1,783 passed), `flare` (253 passed), `flare-cli` (241 passed), `heliopause` `cargo check` (0 new warnings). - Python: `pytest tests/test_scheduling*.py` (830 passed); `scheduling_sim` matches baseline traces identically across all 21 workloads at `age_price = 0.0`, while under `balanced` max TTFT and makespan improve on `burst_eight`, `burst_eight_8k`, and `sixteen_prefills` with modest increases in `max_output_gap_ms` and `decode_age_area_ms2`. - TLA+ lifecycle conformance (`verification/helios-lifecycle/check.py`, TLA+ 1.7.4): 10/10 TLC models, 8/8 observed Rust trace checks (594,065 transitions), 12/12 auxiliary conformance tests passed. - Limitations: Gated template tests requiring `FLARE_TEST_TEMPLATE_DIR` (blocked locally by gated Hugging Face repo 401 in `prepare_templates.py`), `native-serving.yml`, and `kani` proofs were not run locally. Co-authored-by: logprobz <321553542+logprobz@users.noreply.github.com> Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b --- docs/scheduling-runtime-design.md | 22 +- docs/scheduling-theory.md | 7 +- docs/scheduling-utility.md | 37 ++ helios/src/scheduler.rs | 52 ++- helios/src/scheduler/policy.rs | 141 +++++- helios/src/scheduler/policy_tests.rs | 523 ++++++++++++++++++++++- helios/src/scheduler/service.rs | 139 +++++- helios/src/scheduler/utility.rs | 23 +- helios/src/server/runtime.rs | 26 +- helios/src/server/runtime/phase_tests.rs | 95 ++++ scripts/scheduling_sim/utility.py | 30 +- tests/test_scheduling_utility.py | 146 ++++++- 12 files changed, 1154 insertions(+), 87 deletions(-) diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index c1eb542e4..1adb19266 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -231,7 +231,9 @@ active decoder waiting age. The surplus is valued at intrinsic vanishes when active decode capacity is already saturated or when a queued prefiller cannot enter decode (`max_new_tokens == 1`). -Only decoding requests have a delivery coordinate or output-age cost. Normalized +Only decoding requests have a delivery coordinate or join the common +`-T/2 * sum c_j` output-age penalty; waiting prompts with remaining output budget +participate through the first-output waiting-age credit below. Normalized service prices follow the entropy-dual update in `scheduling-utility.md`. When a prefilling request's maximum feasible token rate changes between chunks (for example from a faster intermediate `PREFILL` chunk to a slower @@ -264,10 +266,20 @@ For a ready inference graph, selection maximizes ```text (sum of expected priced token and delivery service - + sum over served decoders of c_i*sigma_i*(A_i+T)) / T + + sum over served decoders of c_i*sigma_i*(A_i+T) + + sum over served waiting prompts of decode_age_price*(b_served*T_dec)*A_first*frac) / T - T/2 * sum over active decoders of c_i. ``` +Here `b_served * T_dec` is the fastest pure incumbent `Decode` or `Speculative` +round's work-time in stream-milliseconds (excluding `Mixed` graphs, and zero when +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. + All values in one decision share a positive scaling factor to keep large prices representable. `ScheduledPlan::selection_value_rate()` exposes the scaled score; `selection_log_scale()` exposes the logarithm of that factor. An unknown duration @@ -315,8 +327,10 @@ and prompt length also restrict logical work. A graph with 64 useful prompt toke 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, -duration ceiling, forced oldest-request filter, or per-chunk prefill lateness -cost. +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 +waiting-age credit above). When a prepared model registers `TERMINAL_PREFILL` graphs for a subset of aligned prefill capacities, Helios infers the tail-protection window as the diff --git a/docs/scheduling-theory.md b/docs/scheduling-theory.md index 2e2d8407a..180e0d8ce 100644 --- a/docs/scheduling-theory.md +++ b/docs/scheduling-theory.md @@ -847,8 +847,11 @@ or authorize retuning on heldout seeds. The ongoing policy uses separate intrinsic output value, token fairness, delivery fairness, and decode-age coefficients. Their concrete defaults and units are specified in the [native design](scheduling-runtime-design.md). -First-token waiting has no independent age penalty: prompt work competes by -its useful progress and token-service price. A burst earns its accepted token +Waiting prompts with remaining output budget do not carry a delivery coordinate +or join the common `-T/2 * sum c_j` waiting penalty; when `decode_age_price > 0` +and active decoders are present, they instead receive a first-output waiting-age +credit scaled by the incumbent decode round work-time `b_served * T_dec` (see +[scheduling-utility.md](scheduling-utility.md)). A burst earns its accepted token volume and one delivery. The delivery reference accounts for feasible batching; changing a rate normalizer preserves marginal service prices across phases. Helios adds a value and an age price for terminal retirement, which the diff --git a/docs/scheduling-utility.md b/docs/scheduling-utility.md index 0ebf35c2c..dca9b5f8d 100644 --- a/docs/scheduling-utility.md +++ b/docs/scheduling-utility.md @@ -284,6 +284,43 @@ oversubscribed decode batch (`K > b`) trades round duration against the waiting cost of its excluded peers. No duration filter, preferred chunk size, or request-count branch is involved. +### First-output waiting age against active decoders + +When `decode_age_price > 0` and at least one measured active decoder exists, +prompts waiting to produce their first output (`consumed_tokens < prompt_tokens` +and `max_new_tokens > 0`) receive a first-output waiting-age credit scaled by +the incumbent decode cohort's fastest round work-time `b_served * T_dec` +(where `b_served = min(batch_capacity, K_dec)` and `T_dec` is the measured +duration in milliseconds of the decode or speculative graph minimizing +`T_dec / b_served`): + +```text +first_output_credit = decode_age_price * (b_served * T_dec) * A_first * frac. +``` + +Here `A_first` is elapsed milliseconds since the prompt's first-output wait +clock (`first_output_wait_ns`, initialized at arrival, advanced on committed +progress, projected across any queued in-flight prefill submission, and +anchored to the most recent output publication across preemption/readmission, +including host-published forced reasoning closure). +On a step that completes the prompt (`scheduled_consumed + work == prompt_tokens`), +`frac = 1`. On a non-finishing prefill chunk, `frac = work / initial_prefill`, +matching coalescing's fixed-denominator amortization so partial chunks remain +linear in `work` and never favor smaller inefficient capacities. Because the +credit uses pure waiting age `A_first`, omits waiting prompts from the common +`-T/2 * sum c_j` waiting-penalty sum, and excludes `Mixed` graphs from the +incumbent pure-decode reference `(b_served, T_dec)`, it vanishes at `A_first = 0` +and stays bounded under oversubscribed (`K > B`) and small-batch (`B = 1`) bursts +because `b_served` counts only incumbent decoders. +When a prefill stops at an armed interior `RetentionRole::Anchor` cut on a +prompt that otherwise fit in a single eligible prefill graph, `first_output_wait_ns` +is preserved across the forced split and boundary snapshot (even when the anchor +endpoint coincides with the chosen graph capacity, since the anchor caps larger +buckets to the same work) while `ServicePrice` +continues to charge all measured token service truthfully. Under +`decode_age_price = 0`, zero active decoders, or score-only `prompt_logprobs` +(`max_new_tokens = 0`), the term evaluates to zero. + For a fixed physical graph, the excluded-stream cost depends on its duration, not cohort membership. Its best cohort therefore contains the largest additive lane values. Rust uses a bounded array to select these lanes; it does not diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 9f4f20988..7d73f063e 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -348,6 +348,11 @@ impl LiveRequest { pub fn reused_prompt_tokens(&self) -> u64 { self.admission_reused_tokens } + pub(super) fn initial_prefill_tokens(&self) -> usize { + self.prompt_tokens + .saturating_sub(self.admission_reused_tokens as usize) + .max(1) + } pub fn snapshot_destination(&self) -> SnapshotId { self.boundary_capture .map(|c| c.snapshot) @@ -2669,10 +2674,7 @@ impl RequestScheduler { let mut window_snapshots = Vec::new(); for (row, lane) in step.lanes.iter().enumerate() { let kind = step.lane_kind(row); - let Ok(request) = self.request_mut(lane.request) else { - continue; - }; - request.pending -= 1; + let record = &records[lane.request.slot as usize]; if matches!( kind, GraphKind::Init @@ -2680,7 +2682,10 @@ impl RequestScheduler { | GraphKind::Snapshot | GraphKind::Vision ) { - let record = &records[lane.request.slot as usize]; + let Ok(request) = self.request_mut(lane.request) else { + continue; + }; + request.pending -= 1; if record.status == 3 { request.error_code = Some(record.error_code); request.terminal_snapshot_ready = false; @@ -2708,10 +2713,29 @@ impl RequestScheduler { } continue; } - let record = &records[lane.request.slot as usize]; - let finished = - record.status == 3 || ((record.status >= 2 || record.generated_tokens == request.max_new_tokens as i64) - && record.consumed_tokens >= request.prompt_tokens as i64); + let (finished, prefill, output, preserve_first_output_wait) = + match self.request(lane.request) { + Ok(request) => { + let finished = record.status == 3 + || ((record.status >= 2 + || record.generated_tokens == request.max_new_tokens as i64) + && record.consumed_tokens >= request.prompt_tokens as i64); + let prefill = if kind.is_prefill() { + record.consumed_tokens as u64 - request.consumed_tokens + } else { + 0 + }; + let output = + (record.generated_tokens - request.generated_tokens as i64) as u32; + let preserve = self.preserves_first_output_wait( + kind, request, record, finished, prefill, output, + ); + (finished, prefill, output, preserve) + } + Err(_) => continue, + }; + let request = self.request_mut(lane.request).unwrap(); + request.pending -= 1; if matches!(kind, GraphKind::Speculative) && record.status != 3 { @@ -2750,14 +2774,10 @@ impl RequestScheduler { if record.status == 3 { request.error_code = Some(record.error_code); } - let prefill = if kind.is_prefill() { - record.consumed_tokens as u64 - request.consumed_tokens - } else { - 0 - }; - let output = (record.generated_tokens - request.generated_tokens as i64) as u32; if record.status != 3 { - request.accounting.credit(prefill, output, now_ns); + request + .accounting + .credit(prefill, output, now_ns, preserve_first_output_wait); useful_tokens[lane.request.slot as usize] = prefill + u64::from(output); } if kind == GraphKind::TerminalPrefill && record.status != 3 { diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index 3c849a552..8295ffb71 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -56,6 +56,7 @@ impl PolicyConfig { pub struct RequestAccounting { pub arrival_ns: u64, pub last_progress_ns: u64, + pub first_output_wait_ns: u64, pub last_output_ns: Option, pub terminal_since_ns: Option, pub last_output_fence: Option, @@ -67,11 +68,20 @@ pub struct RequestAccounting { } impl RequestAccounting { - pub(super) fn credit(&mut self, prefill: u64, output: u32, now: u64) { + pub(super) fn credit( + &mut self, + prefill: u64, + output: u32, + now: u64, + preserve_first_output_wait: bool, + ) { self.committed_prefill_tokens += prefill; self.committed_output_tokens += u64::from(output); if prefill != 0 || output != 0 { self.last_progress_ns = now; + if !preserve_first_output_wait { + self.first_output_wait_ns = now; + } } } } @@ -246,14 +256,24 @@ impl RequestScheduler { Ok(()) } - pub fn set_arrival(&mut self, handle: RequestHandle, arrival_ns: u64) -> Result<()> { + pub fn set_arrival( + &mut self, + handle: RequestHandle, + arrival_ns: u64, + readmitted_output_ns: Option, + ) -> Result<()> { let request = self.request(handle)?; - if arrival_ns > self.now_ns || request.last_use != Fence(0) { + if arrival_ns > self.now_ns + || readmitted_output_ns.is_some_and(|wait_ns| wait_ns > self.now_ns) + || request.last_use != Fence(0) + { return Err("arrival must precede admission and be assigned before dispatch".into()); } let request = self.slots[handle.slot as usize].request.as_mut().unwrap(); request.accounting.arrival_ns = arrival_ns; request.accounting.last_progress_ns = arrival_ns; + request.accounting.first_output_wait_ns = + readmitted_output_ns.map_or(arrival_ns, |wait_ns| wait_ns.max(arrival_ns)); Ok(()) } @@ -284,6 +304,7 @@ impl RequestScheduler { RequestAccounting { arrival_ns: self.now_ns, last_progress_ns: self.now_ns, + first_output_wait_ns: self.now_ns, ..Default::default() } } @@ -413,6 +434,66 @@ impl RequestScheduler { best.map(|(capacity, _)| capacity) } + /// Whether `[start, request.prompt_tokens)` fits in a single eligible prefill + /// graph when no checkpoint cut is imposed. + pub(super) fn fits_single_prefill_from(&self, request: &LiveRequest, start: usize) -> bool { + if request.prefill_limit() != request.prompt_tokens || start >= request.prompt_tokens { + return false; + } + let remaining = request.prompt_tokens - start; + let terminal_only = self.prefill_requires_terminal_completion_from(request, start, None); + let catalog = self.prefill_catalog(if request.prompt_logprobs { + GraphKind::ScoredPrefill + } else if terminal_only { + GraphKind::TerminalPrefill + } else { + GraphKind::Prefill + }); + catalog.iter().copied().any(|capacity| { + let work = self.prefill_work_from(request, start, capacity, None); + if work != remaining { + return false; + } + let resolved = self.resolve_prefill_kind_from(request, start, capacity, work, None); + !(terminal_only && resolved == GraphKind::Prefill) + && self.costs.prefill_entry(resolved, capacity).is_some() + }) + } + + /// 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. + /// + /// 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. + pub(super) fn preserves_first_output_wait( + &self, + kind: GraphKind, + request: &LiveRequest, + record: &CompletionRecord, + finished: bool, + prefill: u64, + output: u32, + ) -> bool { + 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 + && 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) + } + pub fn submission_window_available(&self, duration_ns: u64) -> bool { self.submissions.len() < 2 && !self.submissions.values().any(|s| s.requires_feedback) @@ -473,10 +554,7 @@ impl RequestScheduler { } } } else if !r.prompt_logprobs && r.scheduled_consumed < r.prompt_tokens as u64 { - let initial_prefill = r - .prompt_tokens - .saturating_sub(r.admission_reused_tokens as usize) - .max(1); + let initial_prefill = r.initial_prefill_tokens(); let post_prefill = (r.max_new_tokens as usize) .min(self.limits.max_sequence_tokens.saturating_sub(r.prompt_tokens)) .saturating_sub(1); @@ -624,7 +702,8 @@ impl RequestScheduler { .map(|r| self.service_rates(r)) .unwrap_or_default() }); - let references = self.delivery_references(&rates.map(|(_, d)| d)); + let (references, incumbent_decode_batch_ms) = + self.delivery_references_and_decode_batch(&rates.map(|(_, d)| d)); let mut scale = 0.0f64 .max(self.policy.output_token_value.ln()) .max(self.policy.decode_age_price.ln()) @@ -678,6 +757,32 @@ impl RequestScheduler { .unwrap_or_else(|| r.accounting.last_output_ns.unwrap_or(r.accounting.last_progress_ns)); values[slot].age_ms = self.now_ns.saturating_add(window_ns) .saturating_sub(last_delivery) as f64 / 1e6; + } else if r.consumed_tokens < r.prompt_tokens as u64 + && r.max_new_tokens > 0 + && self.policy.decode_age_price > 0.0 + && incumbent_decode_batch_ms > 0.0 + { + let wait_start = self + .submissions + .values() + .filter(|submission| { + submission.lanes.iter().enumerate().any(|(row, lane)| { + lane.request == r.handle && submission.lane_kind(row).is_prefill() + }) + }) + .map(|submission| submission.expected_finish_ns) + .max() + .unwrap_or(r.accounting.first_output_wait_ns); + let age_ms = self + .now_ns + .saturating_add(window_ns) + .saturating_sub(wait_start) as f64 + / 1e6; + values[slot].first_output_value = if age_ms > 0.0 { + incumbent_decode_batch_ms * age_ms + } else { + 0.0 + }; } scale = scale .max(token_log[slot]) @@ -685,6 +790,7 @@ impl RequestScheduler { .max(coalesce_log[slot]); } let unit = (-scale).exp(); + let scaled_decode_age_price = self.policy.decode_age_price * unit; let mut age_price = 0.0; for (slot, value) in values.iter_mut().enumerate() { value.prefill_token = @@ -694,6 +800,9 @@ impl RequestScheduler { value.delivery = (delivery_log[slot] - scale).exp(); value.terminal *= unit; value.age_price *= unit; + if value.first_output_value > 0.0 { + value.first_output_value *= scaled_decode_age_price; + } age_price += value.age_price; } (values, age_price, scale) @@ -731,8 +840,9 @@ impl RequestScheduler { } consider( ns, - value.prefill( + value.prefill_within( work, + r.initial_prefill_tokens(), r.scheduled_consumed + work as u64 == r.prompt_tokens as u64, ), ); @@ -783,8 +893,9 @@ impl RequestScheduler { if work > 0 { consider( ns, - value.prefill( + value.prefill_within( work, + r.initial_prefill_tokens(), r.scheduled_consumed + work as u64 == r.prompt_tokens as u64, ), ); @@ -1220,10 +1331,12 @@ impl RequestScheduler { value: LaneValue, ) -> f64 { match kind { - GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => value.prefill( - tokens, - r.scheduled_consumed + tokens as u64 == r.prompt_tokens as u64, - ), + 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::Decode | GraphKind::Speculative => value.decode_within( self.expected_speculative_tokens(r, tokens), preceding_ns as f64 / 1e6, diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 3f5b62cee..99d58599f 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -6791,7 +6791,7 @@ fn simultaneous_burst_coalesces_prefills_into_full_decode_batches() { }) .is_err()); - let run_burst = |coalescing_horizon_tokens: f64| { + let run_burst = |coalescing_horizon_tokens: f64, staggered: bool| { let mut s = interactive_engine(8, false); s.prefill_graphs(&[512, 1024, 2048, 4096]).unwrap(); s.configure_policy(PolicyConfig { @@ -6807,7 +6807,21 @@ fn simultaneous_burst_coalesces_prefills_into_full_decode_batches() { set_cost(&mut s, GraphKind::Decode, 2, 1, 30 * MS); set_cost(&mut s, GraphKind::Decode, 4, 1, 37 * MS); set_cost(&mut s, GraphKind::Decode, 8, 1, 48_500_000); - let handles: Vec<_> = (1..=4).map(|id| add(&mut s, id, 512, 128)).collect(); + let mut handles = vec![add(&mut s, 1, 512, 128)]; + if staggered { + // Advance request 1 into Decode so requests 2..4 arrive with zero waiting age, + // isolating coalescing's immediate zero-age batch-efficiency incentive. + while s.request(handles[0]).unwrap().phase != RequestPhase::Decode { + step(&mut s, 0); + } + for id in 2..=4 { + handles.push(add(&mut s, id, 512, 128)); + } + } else { + for id in 2..=4 { + handles.push(add(&mut s, id, 512, 128)); + } + } let mut sub_batch_decodes = 0usize; let mut full_batch_decodes = 0usize; for _ in 0..400 { @@ -6826,14 +6840,27 @@ fn simultaneous_burst_coalesces_prefills_into_full_decode_batches() { (sub_batch_decodes, full_batch_decodes, s.now_ns) }; - let (base_sub, _, base_ns) = run_burst(0.0); - let (coal_sub, coal_full, coal_ns) = run_burst(PolicyConfig::default().coalescing_horizon_tokens); + // On staggered zero-age arrivals behind an active B=1 decoder, coalescing independently + // eliminates sub-batch decode fragmentation before waiting age builds up. + let (stag_base_sub, _, stag_base_ns) = run_burst(0.0, true); + let (stag_coal_sub, stag_coal_full, stag_coal_ns) = + run_burst(PolicyConfig::default().coalescing_horizon_tokens, true); assert!( - base_sub > coal_sub && coal_sub == 0, - "expected coalescing to eliminate sub-batch decode fragmentation: base_sub={base_sub}, coal_sub={coal_sub}" + stag_base_sub > stag_coal_sub && stag_coal_sub == 0, + "expected coalescing to eliminate sub-batch decode fragmentation on zero-age arrivals: base_sub={stag_base_sub}, coal_sub={stag_coal_sub}" ); - assert!(coal_full >= 120, "expected full B=4 decode rounds, got {coal_full}"); - assert!(coal_ns < base_ns, "coalesced burst makespan {coal_ns} should beat baseline {base_ns}"); + assert!(stag_coal_full >= 120, "expected full B=4 decode rounds, got {stag_coal_full}"); + assert!(stag_coal_ns < stag_base_ns, "coalesced burst makespan {stag_coal_ns} should beat baseline {stag_base_ns}"); + + // On simultaneous arrivals, default balanced policy keeps zero sub-batch fragmentation + // and coalescing does not regress makespan or sub-batch rounds vs coalescing-off. + let (sim_base_sub, _, sim_base_ns) = run_burst(0.0, false); + let (sim_coal_sub, sim_coal_full, sim_coal_ns) = + run_burst(PolicyConfig::default().coalescing_horizon_tokens, false); + assert_eq!(sim_coal_sub, 0, "expected zero sub-batch fragmentation on simultaneous burst"); + assert!(sim_coal_sub <= sim_base_sub); + assert!(sim_coal_ns <= sim_base_ns); + assert!(sim_coal_full >= 120, "expected full B=4 decode rounds, got {sim_coal_full}"); } #[test] @@ -6930,3 +6957,483 @@ fn unmeasured_terminal_prefill_discovery_uses_terminal_catalog_and_mixed_respect let expected_opt = super::rounds::forecast_tokens(&m.powered_curve(req, true), 8); assert!((opt - expected_opt).abs() < 1e-12, "opt={opt} != expected={expected_opt}"); } + +#[test] +fn first_output_wait_pricing_is_inert_for_throughput_zero_decoders_and_score_only() { + // 1. Throughput policy (`decode_age_price == 0.0`) leaves `first_output_value == 0.0`. + let mut tp = interactive_engine(4, false); + tp.configure_policy(PolicyConfig::throughput()).unwrap(); + let d = add(&mut tp, 1, 64, 1024); + ready(&mut tp, &[d]); + let p = add(&mut tp, 2, 204, 128); + initialize(&mut tp, p); + tp.advance_to(tp.now_ns + 500 * MS).unwrap(); + let (values, _, _) = tp.lane_values(0); + assert_eq!(values[p.slot as usize].first_output_value, 0.0); + + // 2. Zero active decoders leaves `first_output_value == 0.0` even under balanced policy. + let mut no_dec = interactive_engine(4, false); + let p_only = add(&mut no_dec, 1, 204, 128); + initialize(&mut no_dec, p_only); + no_dec.advance_to(no_dec.now_ns + 500 * MS).unwrap(); + let (values, _, _) = no_dec.lane_values(0); + assert_eq!(values[p_only.slot as usize].first_output_value, 0.0); + + // 3. Score-only `prompt_logprobs` (`max_new_tokens == 0`) leaves `first_output_value == 0.0`. + let mut scored = interactive_engine(4, false); + scored.scored_prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + let dec = add(&mut scored, 1, 64, 1024); + ready(&mut scored, &[dec]); + let score_only = scored + .admit(RequestSpec { + prompt: vec![7; 128], + message_boundaries: vec![128], + conditioning: vec![], + max_new_tokens: 0, + grammar_constrained: false, + prompt_logprobs: true, + growable_output: false, + }) + .unwrap(); + initialize(&mut scored, score_only); + scored.advance_to(scored.now_ns + 500 * MS).unwrap(); + let (values, _, _) = scored.lane_values(0); + assert_eq!(values[score_only.slot as usize].first_output_value, 0.0); +} + +#[test] +fn first_output_wait_scales_by_incumbent_decode_batch_and_chunk_fraction() { + // Max decode batch is 2; admit 4 decoders (oversubscribed K=4 > B=2) to confirm + // scaling uses `b_served * T_dec = 2 * T_dec`, not `K_total`. + let mut s = interactive_engine(6, false); + set_cost(&mut s, GraphKind::Decode, 1, 1, 10 * MS); + set_cost(&mut s, GraphKind::Decode, 2, 1, 12 * MS); + set_cost(&mut s, GraphKind::Decode, 4, 1, 40 * MS); + let decoders: Vec<_> = (0..4).map(|i| add(&mut s, i + 1, 64, 1024)).collect(); + ready(&mut s, &decoders); + let p = add(&mut s, 9, 512, 128); + initialize(&mut s, p); + let wait_start = s.request(p).unwrap().accounting.first_output_wait_ns; + s.advance_to(wait_start + 200 * MS).unwrap(); + + let (values, age_price, scale) = s.lane_values(0); + let unscaled = values[p.slot as usize].first_output_value * scale.exp(); + // Fastest decode per-delivery round is B=2 at 12 ms (6 ms/delivery) -> b_served * T_dec = 24.0. + // c_d = 0.1, age_ms = 200.0 -> expected = 0.1 * 24.0 * 200.0 = 480.0. + assert!( + (unscaled - 480.0).abs() < 1e-6, + "expected unscaled first_output_value=480.0, got {unscaled}" + ); + // Waiting prompt is not added to the common waiting-cost sum `age_price`. + assert_eq!(values[p.slot as usize].age_price, 0.0); + let expected_age_sum = decoders + .iter() + .map(|d| values[d.slot as usize].age_price) + .sum::(); + assert!((age_price - expected_age_sum).abs() < 1e-12); + + // Partial chunk receives `work / initial_prefill` (128/512 = 0.25); finishing receives 1.0. + let v = values[p.slot as usize]; + let base_partial = v.prefill_token * 128.0; + let base_finish = v.prefill_token * 512.0 + v.output_token; + assert!((v.prefill_within(128, 512, false) - (base_partial + 0.25 * v.first_output_value)).abs() < 1e-12); + assert!((v.prefill_within(512, 512, true) - (base_finish + v.first_output_value)).abs() < 1e-12); +} + +#[test] +fn forced_anchor_cut_preserves_first_output_wait_clock_without_exempting_service_price() { + let mut s = interactive_engine(4, false); + s.prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + set_cost(&mut s, GraphKind::Prefill, 1, 64, 5 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 128, 7 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 256, 10 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 4096, 80 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 1 * MS); + + let dec = add(&mut s, 1, 64, 1024); + ready(&mut s, &[dec]); + + // Returning prompt with 204 tokens (fits in single P256) and interior anchor at 202. + let handle = s + .admit(RequestSpec { + prompt: vec![42; 204], + message_boundaries: vec![202], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let arrival_ns = s.now_ns; + initialize(&mut s, handle); + s.advance_to(arrival_ns + 100 * MS).unwrap(); + + // Run first prefill chunk stopped at the armed RetentionRole::Anchor (202). + let plan = s.phase_plan(GraphKind::Prefill, Some(handle)); + assert_eq!(plan.lanes[0].tokens, 202); + let fence = Fence(s.submitted.0 + 1); + s.commit(&plan, fence).unwrap(); + assert_eq!( + s.request(handle).unwrap().checkpoint_capture.map(|c| (c.role, c.endpoint)), + Some((RetentionRole::Anchor, 202)) + ); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let records = completion_records(&s, &plan, fence, 0); + s.complete(fence, &records, gpu_time(10 * MS)).unwrap(); + + let req = s.request(handle).unwrap(); + // Wait clock preserved across forced anchor cut, while ServicePrice is still charged truthfully. + assert_eq!(req.accounting.first_output_wait_ns, arrival_ns); + assert!(req.accounting.last_progress_ns > arrival_ns); + assert!(req.accounting.service.tokens.is_some()); + assert_eq!(req.phase, RequestPhase::Snapshot); + + // Executing the Snapshot preserves the wait clock for the 2-token tail. + let snap = s.phase_plan(GraphKind::Snapshot, Some(handle)); + let snap_fence = Fence(s.submitted.0 + 1); + s.commit(&snap, snap_fence).unwrap(); + s.advance_to(s.now_ns + 1 * MS).unwrap(); + let snap_records = completion_records(&s, &snap, snap_fence, 0); + s.complete(snap_fence, &snap_records, gpu_time(1 * MS)).unwrap(); + assert_eq!(s.request(handle).unwrap().accounting.first_output_wait_ns, arrival_ns); + + // By contrast, a multi-chunk prompt exceeding max capacity (5120 > 4096) resets wait clock. + let long = s + .admit(RequestSpec { + prompt: vec![99; 5120], + message_boundaries: vec![4096, 5120], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let long_arrival = s.now_ns; + initialize(&mut s, long); + let chunk = s.phase_plan(GraphKind::Prefill, Some(long)); + assert!(chunk.lanes[0].tokens > 0 && chunk.lanes[0].tokens < 5120); + let chunk_fence = Fence(s.submitted.0 + 1); + s.commit(&chunk, chunk_fence).unwrap(); + s.advance_to(long_arrival + 50 * MS).unwrap(); + let chunk_records = completion_records(&s, &chunk, chunk_fence, 0); + s.complete(chunk_fence, &chunk_records, gpu_time(80 * MS)).unwrap(); + assert_eq!( + s.request(long).unwrap().accounting.first_output_wait_ns, + s.now_ns + ); +} + +#[test] +fn readmitted_first_output_wait_clamps_to_last_output_not_stale_arrival() { + let mut s = interactive_engine(4, false); + let dec = add(&mut s, 1, 64, 1024); + ready(&mut s, &[dec]); + s.advance_to(s.now_ns + 10_000 * MS).unwrap(); + let now = s.now_ns; + let handle = add(&mut s, 2, 128, 64); + // Original request arrived 5 s ago, but last emitted output only 40 ms ago before preemption. + s.set_arrival(handle, now - 5_000 * MS, Some(now - 40 * MS)).unwrap(); + initialize(&mut s, handle); + assert_eq!(s.request(handle).unwrap().accounting.arrival_ns, now - 5_000 * MS); + assert_eq!(s.request(handle).unwrap().accounting.first_output_wait_ns, now - 40 * MS); +} + +#[test] +fn first_output_wait_large_finite_decode_age_price_avoids_overflow_and_nan() { + let mut s = interactive_engine(4, false); + s.configure_policy(PolicyConfig { + decode_age_price: 1e305, + ..Default::default() + }) + .unwrap(); + set_cost(&mut s, GraphKind::Decode, 1, 1, 10 * MS); + let dec = add(&mut s, 1, 64, 1024); + ready(&mut s, &[dec]); + let p = add(&mut s, 2, 128, 64); + initialize(&mut s, p); + + // Zero waiting age with huge finite decode_age_price must be exact 0.0 (never inf * 0.0 = NaN). + let (values, _, _) = s.lane_values(0); + assert_eq!(values[p.slot as usize].first_output_value, 0.0); + + // Advance service history so log-scale is large enough for `decode_age_price * unit` to stay + // finite while unscaled `decode_age_price * batch_ms * age_ms` would overflow to +inf. + for _ in 0..4 { + let plan = s.phase_plan(GraphKind::Decode, Some(dec)); + let fence = Fence(s.submitted.0 + 1); + s.commit(&plan, fence).unwrap(); + s.advance_to(s.now_ns + 500 * MS).unwrap(); + let records = completion_records(&s, &plan, fence, 1); + s.complete(fence, &records, gpu_time(500 * MS)).unwrap(); + } + let (values, _, scale) = s.lane_values(0); + assert!(scale > 15.0, "expected large log-scale after stall, got {scale}"); + let fov = values[p.slot as usize].first_output_value; + assert!( + fov.is_finite() && fov > 0.0, + "expected finite positive first_output_value under large decode_age_price, got {fov}" + ); +} + +#[test] +fn first_output_wait_excludes_mixed_graphs_and_respects_packed_speculative_feasibility() { + // 1. Mixed graphs must not enter the incumbent pure-decode reference `b_served * T_dec`. + let mut m = mixed_engine(4, false, &[(4, 1, 256, 4 * MS)]); + set_cost(&mut m, GraphKind::Decode, 1, 1, 15 * MS); + set_cost(&mut m, GraphKind::Decode, 2, 1, 20 * MS); + set_cost(&mut m, GraphKind::Decode, 4, 1, 50 * MS); + let d1 = add(&mut m, 1, 64, 1024); + let d2 = add(&mut m, 2, 64, 1024); + ready(&mut m, &[d1, d2]); + let p = add(&mut m, 3, 128, 64); + initialize(&mut m, p); + let wait_start = m.request(p).unwrap().accounting.first_output_wait_ns; + m.advance_to(wait_start + 100 * MS).unwrap(); + let (values, _, scale) = m.lane_values(0); + let unscaled = values[p.slot as usize].first_output_value * scale.exp(); + // Pure Decode B=2 at 20 ms gives b_served * T_dec = 40.0 (not Mixed B=4 at 4 ms -> 8.0). + // Expected: 0.1 * 40.0 * 100.0 = 400.0. + assert!( + (unscaled - 400.0).abs() < 1e-6, + "expected pure-decode first_output_value=400.0 (excluding Mixed), got {unscaled}" + ); + + // 2. Fixed-width packed speculative feasibility: three lanes each needing 4 tokens fit + // individually in packed tokens=5, but only 1 lane fits simultaneously in tokens=5. + let mut packed = fixed_host_round_engine(4, 5); + let mut graphs = super::tests::duration_graphs(4); + graphs.retain(|g| g.kind != GraphKind::Speculative); + for (handle, tokens, duration_ns) in [(701, 5, 10 * MS), (702, 32, 20 * MS)] { + graphs.push(crate::execution::GraphDescriptor { + tuned_bindings: vec![], + confidence_width: 0, + name: format!("spec-b4-w8-t{tokens}"), + kind: GraphKind::Speculative, + sampling_mode: SamplingMode::General, + draft_tokens: 7, + handle, + batch_capacity: 4, + token_capacity: 8, + packed_token_capacity: tokens, + prefill_capacity: 0, + estimated_duration_ns: duration_ns, + input_bindings: vec![], + }); + } + packed.measured_graph_durations(&graphs).unwrap(); + let _dec = fixed_host_requests(&mut packed, &[4, 4, 4]); + let mut rates = [None; REQUEST_LANES]; + for (slot, entry) in packed.slots.iter().enumerate() { + rates[slot] = entry.request.as_ref().and_then(|r| packed.service_rates(r).1); + } + let (_, batch_ms) = packed.delivery_references_and_decode_batch(&rates); + // In tokens=5 (10 ms), only 1 lane of length 4 fits -> 10 ms/delivery. + // In tokens=32 (20 ms), all 3 lanes fit -> 20/3 = 6.67 ms/delivery -> b_served * T_dec = 60 ms. + assert!( + (batch_ms - 60.0).abs() < 1e-6, + "expected full packed shape to win with b_served * T_dec = 60.0, got {batch_ms}" + ); + + // 3. Slot-order invariance under heterogeneous fixed-width verification lengths ([8, 2, 3] vs [3, 2, 8]). + let measure_order = |tails: &[u32]| { + let mut s = fixed_host_round_engine(4, 5); + let handles = fixed_host_requests(&mut s, tails); + let mut rates = [None; REQUEST_LANES]; + for (slot, entry) in s.slots.iter().enumerate() { + rates[slot] = entry.request.as_ref().and_then(|r| s.service_rates(r).1); + } + let (refs, batch_ms) = s.delivery_references_and_decode_batch(&rates); + let by_tail: Vec<_> = tails + .iter() + .zip(handles.iter()) + .map(|(&t, h)| (t, refs[h.slot as usize])) + .collect(); + (by_tail, batch_ms) + }; + let (fwd, fwd_batch) = measure_order(&[8, 2, 3]); + let (rev, rev_batch) = measure_order(&[3, 2, 8]); + assert_eq!(fwd_batch, rev_batch, "incumbent_decode_batch_ms must be slot-order invariant"); + for &(tail, ref_fwd) in &fwd { + let ref_rev = rev.iter().find(|&&(t, _)| t == tail).unwrap().1; + assert_eq!(ref_fwd, ref_rev, "DeliveryReference for tail={tail} must be slot-order invariant"); + } + // In tokens=5 (1 ms), tails 2 and 3 fit together (2 lanes -> 0.5 ms/del), so b_served * T_dec = 2.0 ms. + assert!((fwd_batch - 2.0).abs() < 1e-6, "expected b_served * T_dec = 2.0, got {fwd_batch}"); +} + +#[test] +fn anchor_wait_preservation_at_bucket_capacity_and_reset_on_message_cut() { + let mut s = interactive_engine(4, false); + s.prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }) + .unwrap(); + set_cost(&mut s, GraphKind::Prefill, 1, 64, 5 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 128, 7 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 256, 12 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 512, 24 * MS); + set_cost(&mut s, GraphKind::Prefill, 1, 4096, 80 * MS); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 1 * MS); + + // 1. Anchor endpoint == selected chunk capacity (128): anchor caps P256 to 128 tokens, + // so scheduler picks P128 (token_capacity == prefill == 128) and preserves wait clock. + let anchor_eq = s + .admit(RequestSpec { + prompt: vec![11; 204], + message_boundaries: vec![128], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let arrival_a = s.now_ns; + initialize(&mut s, anchor_eq); + s.advance_to(arrival_a + 100 * MS).unwrap(); + let plan_a = s.phase_plan(GraphKind::Prefill, Some(anchor_eq)); + assert_eq!(plan_a.token_capacity, 128); + assert_eq!(plan_a.lanes[0].tokens, 128); + let fence_a = Fence(s.submitted.0 + 1); + s.commit(&plan_a, fence_a).unwrap(); + assert_eq!( + s.request(anchor_eq).unwrap().checkpoint_capture.map(|c| (c.role, c.endpoint)), + Some((RetentionRole::Anchor, 128)) + ); + s.advance_to(s.now_ns + 7 * MS).unwrap(); + let records_a = completion_records(&s, &plan_a, fence_a, 0); + s.complete(fence_a, &records_a, gpu_time(7 * MS)).unwrap(); + assert_eq!( + s.request(anchor_eq).unwrap().accounting.first_output_wait_ns, + arrival_a + ); + + // 2. Non-anchor RetentionRole::Message cut (128 < anchor 202) resets first_output_wait_ns. + let msg_cut = s + .admit(RequestSpec { + prompt: vec![22; 204], + message_boundaries: vec![128, 202], + conditioning: vec![], + max_new_tokens: 64, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + let arrival_m = s.now_ns; + initialize(&mut s, msg_cut); + s.advance_to(arrival_m + 100 * MS).unwrap(); + let plan_m = s.phase_plan(GraphKind::Prefill, Some(msg_cut)); + assert_eq!(plan_m.lanes[0].tokens, 128); + let fence_m = Fence(s.submitted.0 + 1); + s.commit(&plan_m, fence_m).unwrap(); + assert_eq!( + s.request(msg_cut).unwrap().checkpoint_capture.map(|c| (c.role, c.endpoint)), + Some((RetentionRole::Message, 128)) + ); + s.advance_to(s.now_ns + 7 * MS).unwrap(); + let records_m = completion_records(&s, &plan_m, fence_m, 0); + s.complete(fence_m, &records_m, gpu_time(7 * MS)).unwrap(); + assert_eq!( + s.request(msg_cut).unwrap().accounting.first_output_wait_ns, + s.now_ns + ); +} + +#[test] +fn first_output_wait_projects_across_pipelined_prefill_submission() { + let mut s = interactive_engine(4, false); + s.prefill_graphs(&[64, 128, 256, 512, 1024, 2048, 4096]).unwrap(); + set_cost(&mut s, GraphKind::Prefill, 1, 4096, 20 * MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 10 * MS); + + let dec = add(&mut s, 1, 64, 1024); + ready(&mut s, &[dec]); + let p = add(&mut s, 2, 5120, 64); + initialize(&mut s, p); + s.advance_to(s.now_ns + 500 * MS).unwrap(); + + // Before queueing, the waiting prompt has positive first-output waiting credit. + let (before, _, _) = s.lane_values(0); + assert!(before[p.slot as usize].first_output_value > 0.0); + + // Queue the first 4096-token prefill chunk (expected to finish at now + 20 ms). + let chunk = s.phase_plan(GraphKind::Prefill, Some(p)); + assert_eq!(chunk.lanes[0].tokens, 4096); + let fence = Fence(s.submitted.0 + 1); + s.commit(&chunk, fence).unwrap(); + + // Projecting the second pipelined frame at `window_ns = 20 ms` sees `wait_start` + // advanced to the queued prefill's `expected_finish_ns`, so projected wait age is 0. + let (projected, _, _) = s.lane_values(20 * MS); + assert_eq!(projected[p.slot as usize].first_output_value, 0.0); +} + +#[test] +fn terminal_prefill_clearing_deferred_state_at_interior_anchor_preserves_wait() { + let mut s = engine_with_terminal_prefill(&[256, 512]); + s.configure_policy(PolicyConfig { + checkpoint_extra_work_fraction: 0.5, + ..Default::default() + }) + .unwrap(); + set_cost(&mut s, GraphKind::Snapshot, 1, 1, 1 * MS); + + // 768-token prompt with interior Anchor at 700: + // Chunk 0 (0..512) runs non-terminal Prefill(512) and sets `deferred_prefill = true`. + // Chunk 1 (512..700) runs TerminalPrefill(256) stopped at the armed Anchor (700) on a + // remaining suffix (256 tokens) that otherwise fits in one TerminalPrefill(256). + let handle = s + .admit(RequestSpec { + prompt: vec![7; 768], + message_boundaries: vec![700], + conditioning: vec![], + max_new_tokens: 16, + grammar_constrained: false, + prompt_logprobs: false, + growable_output: false, + }) + .unwrap(); + initialize(&mut s, handle); + + let chunk0 = s.plan().unwrap(); + assert_eq!((chunk0.kind, chunk0.token_capacity, chunk0.lanes[0].tokens), (GraphKind::Prefill, 512, 512)); + let fence0 = Fence(s.submitted.0 + 1); + s.commit(&chunk0, fence0).unwrap(); + assert!(s.request(handle).unwrap().deferred_prefill); + s.advance_to(s.now_ns + 10 * MS).unwrap(); + let rec0 = completion_records(&s, &chunk0, fence0, 0); + s.complete(fence0, &rec0, gpu_time(10 * MS)).unwrap(); + let wait_after_chunk0 = s.request(handle).unwrap().accounting.first_output_wait_ns; + assert_eq!(wait_after_chunk0, s.now_ns); + assert!(s.request(handle).unwrap().deferred_prefill); + + // Wait 100 ms before running TerminalPrefill(256) stopped at interior Anchor 700. + s.advance_to(wait_after_chunk0 + 100 * MS).unwrap(); + let chunk1 = s.plan().unwrap(); + assert_eq!( + (chunk1.kind, chunk1.token_capacity, chunk1.lanes[0].tokens), + (GraphKind::TerminalPrefill, 256, 188) + ); + let fence1 = Fence(s.submitted.0 + 1); + s.commit(&chunk1, fence1).unwrap(); + assert_eq!( + s.request(handle).unwrap().checkpoint_capture.map(|c| (c.role, c.endpoint)), + Some((RetentionRole::Anchor, 700)) + ); + s.advance_to(s.now_ns + 12 * MS).unwrap(); + let rec1 = completion_records(&s, &chunk1, fence1, 0); + s.complete(fence1, &rec1, gpu_time(12 * MS)).unwrap(); + + let req = s.request(handle).unwrap(); + assert!(!req.deferred_prefill, "TerminalPrefill completion must clear deferred_prefill"); + assert_eq!(req.phase, RequestPhase::Snapshot); + assert_eq!( + req.accounting.first_output_wait_ns, wait_after_chunk0, + "TerminalPrefill clearing deferred_prefill at interior Anchor must preserve wait clock" + ); +} diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index c37121640..dfe404364 100644 --- a/helios/src/scheduler/service.rs +++ b/helios/src/scheduler/service.rs @@ -60,6 +60,16 @@ impl RequestScheduler { &self, rates: &[Option; REQUEST_LANES], ) -> [Option; REQUEST_LANES] { + self.delivery_references_and_decode_batch(rates).0 + } + + /// Computes batch-feasible delivery references for all delivery-eligible slots + /// together with the incumbent decode cohort's fastest round work-time + /// `b_served * T_dec` (in stream-ms, or `0.0` when no measured decoder is active). + pub(super) fn delivery_references_and_decode_batch( + &self, + rates: &[Option; REQUEST_LANES], + ) -> ([Option; REQUEST_LANES], f64) { let count = rates.iter().flatten().count() as f64; let mut references = rates.map(|r| { r.map(|r| DeliveryReference { @@ -67,6 +77,7 @@ impl RequestScheduler { served_share: (1.0 / count).min(1.0), }) }); + let mut best_decode = (f64::INFINITY, 0.0f64, 0u64); let family = |r: &LiveRequest| match r.phase { RequestPhase::Decode if self.speculative_widths.is_empty() => Some(GraphKind::Decode), RequestPhase::Decode => Some(GraphKind::Speculative), @@ -97,42 +108,123 @@ impl RequestScheduler { continue; } let mut best = [(f64::INFINITY, 0.0f64); REQUEST_LANES]; - let mut consider = |nanos: u64, batch: usize, eligible: u64| { - if nanos == 0 || eligible == 0 { + let update_slot = |best: &mut [(f64, f64); REQUEST_LANES], + slot: usize, + nanos: u64, + served: usize| { + if nanos == 0 || served == 0 { return; } - let served = batch.min(eligible.count_ones() as usize) as f64; + let served = served as f64; let cost = nanos as f64 / 1e6 / served; + if cost < best[slot].0 || (cost == best[slot].0 && served > best[slot].1) { + best[slot] = (cost, served); + } + }; + let mut consider_decode = |nanos: u64, served: usize| { + if !matches!(kind, GraphKind::Decode | GraphKind::Speculative) + || nanos == 0 + || served == 0 + { + return; + } + let served = served as f64; + let cost = nanos as f64 / 1e6 / served; + if cost < best_decode.0 || (cost == best_decode.0 && served > best_decode.1) { + best_decode = (cost, served, nanos); + } + }; + let consider = |best: &mut [(f64, f64); REQUEST_LANES], + nanos: u64, + batch: usize, + eligible: u64| { + let served = batch.min(eligible.count_ones() as usize); + if nanos == 0 || served == 0 { + return; + } for slot in policy::bits(eligible) { - if cost < best[slot].0 || (cost == best[slot].0 && served > best[slot].1) { - best[slot] = (cost, served); - } + update_slot(best, slot, nanos, served); } }; if matches!(kind, GraphKind::Speculative) { - for &(batch, ref widths) in &self.speculative_catalog { - for &width in widths { - let mut eligible = 0; - let mut nanos = None; + if self.speculative_fixed_width.is_some() { + let mut eligible_lanes = [(0usize, 0usize); REQUEST_LANES]; + let mut sorted_lengths = [0usize; REQUEST_LANES]; + for shape in self.costs.packed_round_shapes() { + if shape.nanos == 0 { + continue; + } + let ns = shape.nanos; + let mut n = 0usize; + let mut total_tokens = 0usize; for slot in policy::bits(mask) { - if let Some(ns) = self.speculative_duration( + let length = self.speculative_tokens( self.slots[slot].request.as_ref().unwrap(), - batch, - width, - ) { - eligible |= 1 << slot; - nanos = Some(ns); + shape.width, + ); + if shape.drafts + 1 >= length && shape.tokens >= length { + eligible_lanes[n] = (slot, length); + sorted_lengths[n] = length; + total_tokens += length; + n += 1; + } + } + if n == 0 { + continue; + } + if total_tokens <= shape.tokens { + let served = shape.batch.min(n); + consider_decode(ns, served); + for &(slot, _) in &eligible_lanes[..n] { + update_slot(&mut best, slot, ns, served); + } + } else { + let lengths = &mut sorted_lengths[..n]; + lengths.sort_unstable(); + let (mut max_served, mut used) = (0usize, 0usize); + for &length in lengths.iter() { + if max_served < shape.batch && used + length <= shape.tokens { + used += length; + max_served += 1; + } else { + break; + } + } + consider_decode(ns, max_served); + for &(slot, lane_len) in &eligible_lanes[..n] { + let (mut served, mut used, mut skipped_self) = + (1usize, lane_len, false); + for &length in lengths.iter() { + if !skipped_self && length == lane_len { + skipped_self = true; + continue; + } + if served < shape.batch && used + length <= shape.tokens { + used += length; + served += 1; + } else { + break; + } + } + update_slot(&mut best, slot, ns, served); } } - if let Some(ns) = nanos { - consider(ns, batch, eligible); + } + } else { + for &(batch, ref widths) in &self.speculative_catalog { + for &width in widths { + if let Some(ns) = self.costs.packed_round_duration(batch, width) { + consider(&mut best, ns, batch, mask); + consider_decode(ns, batch.min(streams)); + } } } } } else { for &batch in self.costs.batches(kind) { if let Some(ns) = self.costs.duration(kind, batch, 1) { - consider(ns, batch, mask); + consider(&mut best, ns, batch, mask); + consider_decode(ns, batch.min(streams)); } } } @@ -143,7 +235,7 @@ impl RequestScheduler { .shape_duration(GraphKind::Mixed, batch, width, prefill) .filter(|ns| *ns > 0) { - consider(ns, batch, mask); + consider(&mut best, ns, batch, mask); } } } @@ -157,7 +249,12 @@ impl RequestScheduler { } } } - references + let incumbent_decode_batch_ms = if best_decode.0.is_finite() { + best_decode.1 * (best_decode.2 as f64 / 1e6) + } else { + 0.0 + }; + (references, incumbent_decode_batch_ms) } /// Individually feasible service rates, in tokens and deliveries per millisecond. diff --git a/helios/src/scheduler/utility.rs b/helios/src/scheduler/utility.rs index 30f80c96b..a37590ffe 100644 --- a/helios/src/scheduler/utility.rs +++ b/helios/src/scheduler/utility.rs @@ -85,11 +85,24 @@ pub(super) struct LaneValue { pub age_price: f64, pub age_ms: f64, pub reference_delivery_ms: f64, + /// Scaled first-output waiting credit for a prompt competing against active decoders: + /// `unit * decode_age_price * (b_served * T_dec) * age_ms`. + pub first_output_value: f64, } impl LaneValue { - pub fn prefill(&self, consumed: usize, first_output: bool) -> f64 { - self.prefill_token * consumed as f64 + self.output_token * f64::from(first_output) + pub fn prefill_within(&self, consumed: usize, initial_prefill: usize, first_output: bool) -> f64 { + let mut value = + self.prefill_token * consumed as f64 + self.output_token * f64::from(first_output); + if self.first_output_value > 0.0 && (consumed > 0 || first_output) { + let fraction = if first_output { + 1.0 + } else { + consumed as f64 / initial_prefill.max(consumed).max(1) as f64 + }; + value += self.first_output_value * fraction; + } + value } pub fn decode(&self, expected_output: f64, duration_ms: f64) -> f64 { @@ -389,9 +402,9 @@ mod tests { output_token: 64.0, ..Default::default() }; - assert_eq!(value.prefill(64, true), 128.0); - let small = ValueRate::new(3_000_000, value.prefill(64, true), 0.0); - let padded = ValueRate::new(66_000_000, value.prefill(64, true), 0.0); + assert_eq!(value.prefill_within(64, 64, true), 128.0); + let small = ValueRate::new(3_000_000, value.prefill_within(64, 64, true), 0.0); + let padded = ValueRate::new(66_000_000, value.prefill_within(64, 64, true), 0.0); assert!(small.compare(padded).is_gt()); } diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 538145f10..2f9b6bfd6 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -424,6 +424,9 @@ struct Carried { generated_tokens: u32, /// The request's own sampling seed, from which each continuation's seed derives. seed: Option, + /// Most recent output publication time carried across preemption/readmission so + /// readmitted streams do not inherit stale pre-generation arrival age. + last_output_ns: Option, } /// The sampling seed of a preempted request's continuation after `generated` tokens. @@ -1568,7 +1571,11 @@ impl<'a> Worker<'a> { } }; incoming.blocked = None; - self.scheduler.set_arrival(handle, incoming.arrival_ns)?; + self.scheduler.set_arrival( + handle, + incoming.arrival_ns, + parked.as_ref().and_then(|parked| parked.carried.last_output_ns), + )?; let slot = handle.slot as usize; if let Err(error) = self .scheduler @@ -2243,6 +2250,7 @@ impl<'a> Worker<'a> { ); let forced = request.reasoning.take().unwrap().reasoning_open() && close_allowed; + let publications_before = request.incoming.publications.get(); let mut injected = Vec::new(); let mut abandon = false; if forced { @@ -2265,6 +2273,16 @@ impl<'a> Worker<'a> { } } if forced && !abandon { + if request.incoming.publications.get() != publications_before { + let published_ns = super::observation::monotonic_ns(); + self.scheduler.advance_to(published_ns)?; + request.carried.last_output_ns = Some( + request + .carried + .last_output_ns + .map_or(published_ns, |prev| prev.max(published_ns)), + ); + } self.metrics .reasoning_budget_cuts .fetch_add(1, Ordering::Relaxed); @@ -2447,12 +2465,17 @@ impl<'a> Worker<'a> { let live = self.scheduler.request(handle)?; let (prompt_tokens, reused) = (live.prompt_tokens, live.reused_prompt_tokens()); let checkpoint_accounting = live.checkpoint_accounting(); + let live_last_output_ns = live.accounting().last_output_ns; if publish_terminal { self.scheduler.finish(handle)?; } else { self.scheduler.cancel(handle)?; } let mut active = self.clear_active_slot(slot).unwrap(); + let last_output_ns = live_last_output_ns + .into_iter() + .chain(active.carried.last_output_ns) + .max(); if drop_reasoning { active.reasoning = None; } @@ -2486,6 +2509,7 @@ impl<'a> Worker<'a> { reused_prompt_tokens: Some(active.carried.reused_prompt_tokens.unwrap_or(reused)), generated_tokens, seed: Some(seed), + last_output_ns, }, }; self.parked.push_back((incoming, parked)); diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 74ed5d9e7..28e8e8dba 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -5818,6 +5818,7 @@ fn failed_host_restore_replans_all_images_from_the_shallower_prefix() { reused_prompt_tokens: Some(56), generated_tokens: 7, seed: Some(99), + last_output_ns: None, }; worker.active[0].as_mut().unwrap().last_token = Some(2); let (_, ticket) = fake_store(&mut worker).fetched.pop().unwrap(); @@ -8317,3 +8318,97 @@ fn prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_env assert!(!incoming.speculative_grammar_reasoning()); assert!(incoming.spec().grammar_constrained); } + +#[test] +fn forced_reasoning_close_readmission_anchors_first_output_wait_with_and_without_prior_publication() { + // Case 1: With a prior graph publication, host-published close tokens advance + // `first_output_wait_ns` on readmission to at least the later host publication time. + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, _generation) = fixture.incoming(vec![0], 2); + incoming.prompt.reasoning_cut = Some(budget_cut(4, 3)); + sender.send(vec![incoming]).unwrap(); + let mut worker = fixture.worker(receiver); + let _ = worker.admit().unwrap(); + let handle = worker.active[0].as_ref().unwrap().request; + let arrival_ns = worker.scheduler.request(handle).unwrap().accounting().arrival_ns; + let mut seq = 1; + advance(&mut worker, GraphKind::Init, seq, None); + seq += 1; + advance(&mut worker, GraphKind::Prefill, seq, Some(1)); + seq += 1; + if worker.scheduler.request(handle).unwrap().phase == RequestPhase::Snapshot { + advance(&mut worker, GraphKind::Snapshot, seq, None); + seq += 1; + } + let prior_graph_pub = worker + .scheduler + .request(handle) + .unwrap() + .accounting() + .last_output_ns + .expect("prefill should record a prior graph publication"); + advance(&mut worker, GraphKind::Decode, seq, Some(1)); + seq += 1; + if worker.scheduler.request(handle).unwrap().phase == RequestPhase::Snapshot { + advance(&mut worker, GraphKind::Snapshot, seq, None); + } + std::thread::sleep(std::time::Duration::from_millis(2)); + let before_host_close = crate::server::observation::monotonic_ns(); + assert!(worker.publish().unwrap()); + let (_, parked) = worker.parked.front().unwrap(); + let carried_last_output = parked + .carried + .last_output_ns + .expect("forced reasoning close must carry host publication timestamp"); + assert!( + carried_last_output >= before_host_close && carried_last_output > prior_graph_pub, + "expected carried last_output_ns ({carried_last_output}) >= before_host_close ({before_host_close}) > prior_graph_pub ({prior_graph_pub})" + ); + let _ = worker.admit().unwrap(); + let readmitted = worker.active[0].as_ref().unwrap().request; + let readmitted_acc = worker.scheduler.request(readmitted).unwrap().accounting(); + assert_eq!(readmitted_acc.arrival_ns, arrival_ns); + assert_eq!(readmitted_acc.first_output_wait_ns, carried_last_output); + + // Case 2: Without any prior graph publication (token held in stop buffer until + // forced close flushes/emits on host), readmission still anchors to host publication + // rather than stale original arrival time. + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let (mut incoming, _generation) = fixture.incoming(vec![0], 1); + incoming.prompt.stop_sequences = vec![vec![1, 9]]; + incoming.prompt.reasoning_cut = Some(budget_cut(4, 3)); + sender.send(vec![incoming]).unwrap(); + let mut worker = fixture.worker(receiver); + let _ = worker.admit().unwrap(); + let handle = worker.active[0].as_ref().unwrap().request; + let arrival_ns = worker.scheduler.request(handle).unwrap().accounting().arrival_ns; + advance(&mut worker, GraphKind::Init, 1, None); + advance(&mut worker, GraphKind::Prefill, 2, Some(1)); + if worker.scheduler.request(handle).unwrap().phase == RequestPhase::Snapshot { + advance(&mut worker, GraphKind::Snapshot, 3, None); + } + assert_eq!( + worker.scheduler.request(handle).unwrap().accounting().last_output_ns, + None, + "held stop-prefix token must not have recorded a prior graph publication" + ); + std::thread::sleep(std::time::Duration::from_millis(2)); + let before_host_close = crate::server::observation::monotonic_ns(); + assert!(worker.publish().unwrap()); + let (_, parked) = worker.parked.front().unwrap(); + let carried_last_output = parked + .carried + .last_output_ns + .expect("host-published close token must populate carried last_output_ns"); + assert!( + carried_last_output >= before_host_close && carried_last_output > arrival_ns, + "expected carried last_output_ns ({carried_last_output}) >= before_host_close ({before_host_close}) > arrival_ns ({arrival_ns})" + ); + let _ = worker.admit().unwrap(); + let readmitted = worker.active[0].as_ref().unwrap().request; + let readmitted_acc = worker.scheduler.request(readmitted).unwrap().accounting(); + assert_eq!(readmitted_acc.arrival_ns, arrival_ns); + assert_eq!(readmitted_acc.first_output_wait_ns, carried_last_output); +} diff --git a/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index a276ed64b..ccc9fcc08 100644 --- a/scripts/scheduling_sim/utility.py +++ b/scripts/scheduling_sim/utility.py @@ -127,6 +127,7 @@ def __init__(self, value: Value, config: UtilityConfig): self._token_normalizers: set[str] = set() self._delivery_normalizers: set[str] = set() self._coalesce_token: dict[str, float] = {} + self._first_output_value: dict[str, float] = {} self._initial_prefill: dict[str, int] = {} self._mask_unknown_prices = False @@ -140,6 +141,7 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = self._token_normalizers.clear() self._delivery_normalizers.clear() self._coalesce_token.clear() + self._first_output_value.clear() self._initial_prefill = {name: total for name, total in self._initial_prefill.items() if name in names} for view in views: if view.remaining_prefill > 0 and view.name not in self._initial_prefill: @@ -153,6 +155,18 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = for graph in measured if decoding and graph.decode_capacity), default=None, ) + pure_decode_ref = min( + ((graph.duration_ms / min(graph.decode_capacity, decoding), + -min(graph.decode_capacity, decoding), + graph.duration_ms) + for graph in measured + if decoding and graph.decode_capacity and not graph.prefill_capacity), + default=None, + ) + incumbent_decode_batch_ms = 0.0 + if pure_decode_ref is not None: + _, neg_served, duration_ms = pure_decode_ref + incumbent_decode_batch_ms = (-neg_served) * duration_ms for view in views: actions = candidates([view], catalog, self.value) if not actions: @@ -238,15 +252,29 @@ def best_decode_rate(n_streams: int) -> float: *(price.log_price - log(price.maximum_rate) for row in self.prices.values() for price in (row.tokens, row.deliveries) if price is not None)]) + unit = exp(-self.log_scale) if raw_coalesce: - unit = exp(-self.log_scale) self._coalesce_token = {name: unit * value for name, value in raw_coalesce.items()} + if self.config.age_price > 0 and incumbent_decode_batch_ms > 0: + for view in views: + if view.remaining_prefill > 0 and view.output_budget > 0: + age_ms = now_ms - view.last_service_ms + if age_ms > 0: + self._first_output_value[view.name] = ( + unit * self.config.age_price * view.weight + * incumbent_decode_batch_ms * age_ms + ) def lane_value(self, lane: Lane) -> float: prices = self.prices[lane.name] work = exp(-self.log_scale) * lane.useful_work(self.value) if lane.prefill and lane.name in self._coalesce_token: work += self._coalesce_token[lane.name] * lane.prefill + if lane.prefill and lane.name in self._first_output_value: + frac = 1.0 if lane.expected_output > 0 else min( + 1.0, lane.prefill / max(self._initial_prefill[lane.name], lane.prefill) + ) + work += self._first_output_value[lane.name] * frac if prices.tokens is not None and (not self._mask_unknown_prices or lane.name in self._token_normalizers): work += prices.tokens.value(lane.prefill + lane.expected_output, self.log_scale) return work diff --git a/tests/test_scheduling_utility.py b/tests/test_scheduling_utility.py index 1a634f1e5..d041f2a2d 100644 --- a/tests/test_scheduling_utility.py +++ b/tests/test_scheduling_utility.py @@ -3,7 +3,7 @@ from dataclasses import replace from itertools import combinations -from math import exp, log +from math import exp, isfinite, log from random import Random import pytest @@ -361,30 +361,146 @@ def test_invalid_preferences_are_rejected(config): def test_simultaneous_burst_coalesces_prefills_into_full_decode_batches(): - # Simultaneous B=8 burst on the synthetic catalog must coalesce prefills into - # higher-utilization decode batches and reduce max TTFT and sub-batch rounds. - base_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)) + # Under throughput policy (age_price=0.0, first-output waiting age inactive), + # coalescing independently eliminates sub-batch decode rounds and cuts max TTFT. + tp_base = run( + workloads()["burst_eight"], + catalog(), + Value(64), + scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.0, "service", 0.0)), + horizon_ms=15000, + ) + tp_coal = run( + workloads()["burst_eight"], + catalog(), + Value(64), + scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.0, "service")), + horizon_ms=15000, + ) + assert tp_coal.summary["unfinished"] == 0 + assert max(r["ttft_ms"] for r in tp_coal.requests) < max(r["ttft_ms"] for r in tp_base.requests) + assert tp_coal.trace[-1]["end_ms"] < tp_base.trace[-1]["end_ms"] + tp_base_sub = sum(len(e["lanes"]) < 8 for e in tp_base.trace if e["decode_capacity"]) + tp_coal_sub = sum(len(e["lanes"]) < 8 for e in tp_coal.trace if e["decode_capacity"]) + assert tp_base_sub > 0 and tp_coal_sub == 0, f"tp_coal_sub={tp_coal_sub}, tp_base_sub={tp_base_sub}" + + # Under balanced policy (age_price=0.1), coalescing does not regress max TTFT, + # makespan, or sub-batch fragmentation relative to coalescing-off. + bal_base = run( + workloads()["burst_eight"], + catalog(), + Value(64), + scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)), + horizon_ms=15000, + ) coal_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) - base = run(workloads()["burst_eight"], catalog(), Value(64), scheduler=base_policy, horizon_ms=15000) coal = run(workloads()["burst_eight"], catalog(), Value(64), scheduler=coal_policy, horizon_ms=15000) assert coal.summary["unfinished"] == 0 - base_ttft = max(row["ttft_ms"] for row in base.requests) + bal_base_ttft = max(row["ttft_ms"] for row in bal_base.requests) coal_ttft = max(row["ttft_ms"] for row in coal.requests) - assert coal_ttft < base_ttft * 0.85, f"expected >=15% max TTFT reduction: {coal_ttft} vs {base_ttft}" - assert coal.trace[-1]["end_ms"] < base.trace[-1]["end_ms"] * 0.95 - base_sub = sum(len(event["lanes"]) < 8 for event in base.trace if event["decode_capacity"]) + bal_base_sub = sum(len(event["lanes"]) < 8 for event in bal_base.trace if event["decode_capacity"]) coal_sub = sum(len(event["lanes"]) < 8 for event in coal.trace if event["decode_capacity"]) - assert coal_sub <= base_sub // 2, f"coal_sub={coal_sub}, base_sub={base_sub}" - # Under low speculative acceptance, coalescing also reduces max TTFT and sub-batch rounds. - low_base_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)) + assert coal_ttft <= bal_base_ttft and coal_ttft <= 600.0 + assert coal.trace[-1]["end_ms"] <= bal_base.trace[-1]["end_ms"] + assert coal_sub <= bal_base_sub and coal_sub <= 2 + + low_base = run( + workloads()["burst_eight_low"], + catalog(), + Value(64), + scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)), + horizon_ms=15000, + ) low_coal_policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) - low_base = run(workloads()["burst_eight_low"], catalog(), Value(64), scheduler=low_base_policy, horizon_ms=15000) low_coal = run(workloads()["burst_eight_low"], catalog(), Value(64), scheduler=low_coal_policy, horizon_ms=15000) assert low_coal.summary["unfinished"] == 0 - assert max(row["ttft_ms"] for row in low_coal.requests) < max(row["ttft_ms"] for row in low_base.requests) low_base_sub = sum(len(event["lanes"]) < 8 for event in low_base.trace if event["decode_capacity"]) low_coal_sub = sum(len(event["lanes"]) < 8 for event in low_coal.trace if event["decode_capacity"]) - assert low_coal_sub < low_base_sub, f"low_coal_sub={low_coal_sub}, low_base_sub={low_base_sub}" + assert low_coal_sub <= low_base_sub and low_coal_sub == 0 + + +def test_first_output_waiting_age_reduces_returning_prompt_stall_without_throughput_drift(): + graphs = ( + Graph("p256", 10.0, prefill_capacity=256), + Graph("d8", 24.0, decode_capacity=8), + ) + requests = [ + *(Request(f"d{i}", prompt_tokens=0, output_tokens=80, arrival_ms=0.0) for i in range(8)), + Request("ret", prompt_tokens=204, output_tokens=8, arrival_ms=200.0), + ] + bal = run(requests, graphs, Value(64), scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")), horizon_ms=5000) + ret_row = next(r for r in bal.requests if r["name"] == "ret") + assert ret_row["ttft_ms"] < 400.0, f"expected returning prompt TTFT < 400ms, got {ret_row['ttft_ms']}" + + # Under age_price=0.0, first-output waiting age is inactive. + tp_sched = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.0, "service")) + views = [ + *(View(f"d{i}", 0, 64, (1.0,), last_service_ms=0.0) for i in range(8)), + View("ret", 204, 64, (1.0,), last_service_ms=0.0), + ] + tp_sched.prepare(views, graphs, now_ms=500.0) + assert tp_sched._first_output_value == {} + + +def test_first_output_waiting_age_scaling_linearity_exclusions_and_burst_bounds(): + # Exact b_served * T_dec scaling (excluding mixed graphs), work / initial_prefill linearity, + # and zero-age inertness. + graphs = ( + Graph("p128", 5.0, prefill_capacity=128), + Graph("p512", 18.0, prefill_capacity=512), + Graph("d2", 12.0, decode_capacity=2), + Graph("d4", 40.0, decode_capacity=4), + Graph("mixed4", 4.0, prefill_capacity=256, decode_capacity=4), + ) + sched = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service", 0.0)) + views = [ + *(View(f"d{i}", 0, 64, (1.0,), last_service_ms=0.0) for i in range(4)), + View("p", 512, 64, (1.0,), last_service_ms=0.0), + View("fresh", 128, 64, (1.0,), last_service_ms=200.0), + ] + sched.prepare(views, graphs, now_ms=200.0) + # Pure decode winner is d2 (6 ms/del) -> b_served * T_dec = 2 * 12 = 24.0 (mixed4 excluded). + # Unscaled first_output_value = 0.1 * 24.0 * 200.0 = 480.0. + unscaled = sched._first_output_value["p"] * exp(sched.log_scale) + assert unscaled == pytest.approx(480.0) + assert "fresh" not in sched._first_output_value + + # Partial chunk (128/512 = 0.25) vs finishing step (1.0) linearity. + partial_lane = Lane("p", prefill=128, width=0, expected_output=0.0, weight=1.0) + finish_lane = Lane("p", prefill=512, width=0, expected_output=1.0, weight=1.0) + v_partial = sched.lane_value(partial_lane) + v_finish = sched.lane_value(finish_lane) + sched_zero = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.0, "service", 0.0)) + sched_zero.prepare(views, graphs, now_ms=200.0) + assert v_partial - sched_zero.lane_value(partial_lane) == pytest.approx( + 0.25 * sched._first_output_value["p"] + ) + assert v_finish - sched_zero.lane_value(finish_lane) == pytest.approx( + sched._first_output_value["p"] + ) + + # Adversarial oversubscribed (K_dec=32, B=4, 16 waiting prompts) and small-batch + # (K_dec=4, B=1, 24 waiting prompts) bursts remain bounded without starving decoders. + for k_dec, batch_cap, n_waiters in [(32, 4, 16), (4, 1, 24)]: + stress_graphs = ( + Graph("p256", 12.0, prefill_capacity=256), + Graph(f"d{batch_cap}", 10.0 + 2.0 * batch_cap, decode_capacity=batch_cap), + ) + reqs = [ + *(Request(f"d{i}", prompt_tokens=0, output_tokens=32, arrival_ms=0.0) for i in range(k_dec)), + *(Request(f"w{i}", prompt_tokens=204, output_tokens=8, arrival_ms=200.0) for i in range(n_waiters)), + ] + result = run( + reqs, + stress_graphs, + Value(64), + scheduler=UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")), + horizon_ms=60000, + ) + assert result.summary["unfinished"] == 0 + assert all(isfinite(row["ttft_ms"]) for row in result.requests) + waiter_ttfts = [row["ttft_ms"] for row in result.requests if row["name"].startswith("w")] + assert max(waiter_ttfts) < 15000.0, f"{k_dec}/{batch_cap}/{n_waiters}: max_ttft={max(waiter_ttfts)}" def test_coalescing_surplus_vanishes_at_saturated_batch_and_single_token_budget():