From 975f82578a7b2a59c28fc34647769cd9ce22ab0c Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:44:42 -0600 Subject: [PATCH] helios/scheduler: use active cohort mean in coalescing horizon Why In Helios's prepared-graph scheduler (`helios/src/scheduler/policy.rs`), the per-prefill-token decode-batch coalescing bonus (`coalescing_prefill_log_bonus`) prices the steady-state throughput gain unlocked when queued prefills join an under-batched active decode cohort over a bounded cohort-mean output horizon (`coalescing_horizon_tokens`, default 64.0). Previously, `coalescing_prefill_log_bonus` reduced all active decoders' remaining output budgets to a single scalar minimum (`peer_budget = peer_budget.min(rem)`), and the Python reference scheduler (`scripts/scheduling_sim/utility.py`) used the same scalar minimum for the coalescing horizon (while already averaging per-decoder expected output `mean_out` across active decoders in `best_decode_rate`). Under heterogeneous mixed serving, any single active decoder within one token of its output limit (`rem = 1`) collapsed both Rust's speculative per-round expected output (`mean_out`) and both implementations' coalescing `horizon` to 1 token for the entire cohort, eliminating over 98% of the coalescing incentive even when all other active decoders had large remaining budgets. Averaging per-decoder clamped budgets across the active cohort repairs the Rust-to-simulator `mean_out` parity gap and extends cohort averaging to the coalescing `horizon`, preserving continuation value when individual requests approach completion while still shrinking smoothly as the cohort approaches its output limit. What - In `helios/src/scheduler/policy.rs::coalescing_prefill_log_bonus` (+16/-18 lines, -2 net Rust production LOC; visibility unchanged): - Replace the scalar minimum `peer_budget` with a bounded per-decoder remaining-budget array (`decoder_rems`), where each `rem` is an active decoder's remaining output tokens clamped by KV sequence headroom (`max_sequence_tokens - scheduled_consumed`). - Extract local helper `mean_capped(rems: &[usize], cap: f64) -> f64`, hoist `expected_at(eff_width)` and `expected_at(width as f64)` out of the per-decoder loop, and delete provably dead `.max(1.0)` clamps and the unreachable `if horizon > 0.0` branch while keeping the `per_token.is_finite() && per_token > 0.0` guard. - Compute speculative per-round expected output (`mean_out`, parity with `utility.py`) and each prefiller's coalescing `horizon` (clamped to `min(coalescing_horizon_tokens, post_prefill)`, where `post_prefill` is the prefiller's remaining output budget after its first generated token) via `mean_capped`. - In `scripts/scheduling_sim/utility.py` (+2/-6, -4 net Python production LOC): replace `peer_budget = min(v.output_budget for v in decoders)` in the coalescing horizon calculation with the cohort mean across active decoders, matching Helios and `best_decode_rate`'s existing cohort-mean `mean_out`. - In `docs/scheduling-runtime-design.md`: update the coalescing horizon specification to describe the bounded cohort-mean decode horizon and per-decoder clamped cohort averaging. - In `helios/src/scheduler/policy_tests.rs` and `tests/test_scheduling_utility.py`: add unit tests covering `[1, 100]` and `n=3` `[1, 20, 100]` heterogeneous cohorts, Rust-specific KV-headroom clamping, packed and unpacked speculative cohorts (reusing `super::rounds::forecast_tokens`), single-decoder equivalence, zero-bonus invariants, and an end-to-end `scripts/scheduling_sim` heterogeneous-budget test (`max_new_tokens < 64`) under `balanced` (`age_price = 0.1`). Result - Single-decoder and homogeneous-budget cohorts produce identical values to the prior minimum formula; a `[1, 100]` cohort retains a 32.5-token horizon instead of collapsing to 1 token. - End-to-end `scripts/scheduling_sim` (`catalog()`, `balanced`, `age_price = 0.1`, cohort-mean vs prior `min(rem, ph)` horizon): - Non-speculative (`short0` `max_new_tokens=8` + 3 long decoders + 4 queued 4K prefills): makespan 7,779.0 -> 7,734.0 ms (-45.0 ms), mean prefill TTFT 266.8 -> 201.0 ms (-24.6%), max prefill TTFT 373.0 -> 327.0 ms (-12.3%), max output gap 226.0 -> 182.0 ms (-19.5%). - Speculative (`short0` `max_new_tokens=32` + 3 long decoders + 5 queued 4K prefills): makespan 1,912.0 -> 1,878.0 ms (-34.0 ms), mean prefill TTFT 293.6 -> 266.4 ms (-9.3%), max prefill TTFT 468.0 -> 432.0 ms (-7.7%), max output gap 278.0 -> 212.0 ms (-23.7%). - Measured on `DeepSeek-V4.1-Flash` (`FujitsuPolycom/tokbench`, seed 42, temp 0, base `1fbcc3c990b5`) on 4x RTX PRO 6000 Blackwell (SM120, TP4) and 4x DGX Spark GB10 (SM121, TP4, `gb10-tp4-202612010547`): - Solo on `1fbcc3c9`: `long-context-mixed` (1-rep) +1.8% output (655.4 -> 667.3 tok/s), stalls 28.1% -> 26.3%, SLO 89.8% -> 92.6%; `mixed-c32` (2-rep) output 1,281.7 -> 1,276.8 tok/s, TTFT p50 1,425 -> 1,390 ms, stalls 11.29% -> 11.49%, SLO 93.0% -> 91.1%; `cold-heavy-mix` (1-rep) regresses output 541.8 -> 521.8 tok/s (-3.7%) and SLO 88.1% -> 79.1% (-9.0 pp, `agentic_multiturn` TTFT p99 3,323 -> 5,144 ms) because keeping coalescing active near EOS pulls 150K-250K cold prefills ahead of decoders without `#661` chunk shrinking. - Atop `#661` (`3d868f84`, primary stall reduction from `#661`): `mixed-c32` (2-rep med) output 1,254 -> 1,261 tok/s, stalls 6.65% -> 5.95%, TTFT p50 1,479 -> 1,439 ms, SLO 89.4% -> 90.5%; `long-context-mixed` (1-rep) stalls 16.4% -> 9.8% while SLO dropped 89.3% -> 82.1% (-7.2 pp); `cold-heavy-mix` (1-rep) output 545.6 -> 547.8 tok/s, stalls 56.3% -> 55.7%, SLO 81.6% -> 79.8%. - Composed 4-PR stack (`#660 + #661 + #665`, where prefix-cache hit-rate gains come from `#665` and primary stall cuts from `#661`): SM120 `mixed-c32` (2-rep) output 1,374.6 -> 1,394.2 tok/s (+1.4%), stalls 4.82% -> 4.34%, TTFT p50 1,001 -> 922 ms (-7.9%), SLO 96.5% -> 97.1%; GB10 `mixed-c8` (2-rep) stalls 41.8% -> 38.0%, TTFT p50 1,181 -> 1,118 ms, SLO 79.0% -> 81.7%; GB10 `agentic-coding` C=8 (1-rep) stalls 45.4% -> 34.5%, TTFT p50 1,024 -> 877 ms, SLO 81.8% -> 85.7%. Evidence Verified on clean `git archive` of tree `fe2b8739991e`: - Rust (`RUSTFLAGS="-D warnings"`): `cargo check --locked --release` across `eos`, `selene`, `selene-manager`, `helios` (`runtime-core,server --tests`), `flare`, `flare-cli` -> 0 warnings. - `cargo test --locked --release`: `eos` (12 passed), `selene --features test-support` (553 passed), `selene-manager --features test-support` (426 passed, 1 ignored), `helios --features server --lib` (1,283 passed, 15 ignored), `helios --features runtime-core,server --lib` (1,795 passed, 47 ignored), `flare --lib` (246 passed, 4 ignored), `flare-cli` (245 passed, 3 ignored). - Python: `ruff==0.12.8` passed on modified Python files; `pytest` passed (854 passed across `tests/preparation/test_core_boundary.py`, `tests/test_scheduling*.py`, and `tests/test_design_review_hook.py`, including `test_coalescing_heterogeneous_budget_end_to_end_balanced`). - Fault mutation checks (scratch copies): reverting `scripts/scheduling_sim/ utility.py` `horizon` to `min(ph, min(output_budget))` failed both `test_coalescing_heterogeneous_budget_end_to_end_balanced` and `test_coalescing_horizon_averages_active_decoder_budgets`; reverting `helios/src/scheduler/policy.rs::mean_capped` to `.min()` failed both Rust coalescing unit tests (`2/2` killed). - `git merge-tree --write-tree`: clean (`rc=0`) against `main` (`4cc6f2fd`), `2acc3f3a`, `#660` (`9709d496`), `#661` (`3d868f84`), and `#665` (`c5b39236`). - Hardware binaries were built from earlier equivalent trees `df9a8ebd` (solo), `38130855` (on `#661`), and `dbbf65df` (stack) before the semantics-preserving `mean_capped` / hoist refactor; final rebase onto `main` after `#661` lands and CI/A/B confirmation on the rebased head remain pending. Standalone GB10, other GPUs, and other recipes were not benchmarked. Discord: Dooner Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> --- docs/scheduling-runtime-design.md | 9 +- helios/src/scheduler/policy.rs | 34 ++--- helios/src/scheduler/policy_tests.rs | 217 +++++++++++++++++++++++++++ scripts/scheduling_sim/utility.py | 8 +- tests/test_scheduling_utility.py | 90 +++++++++++ 5 files changed, 331 insertions(+), 27 deletions(-) diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 1adb19266..714785604 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -221,9 +221,12 @@ When active decoders are under-batched relative to the measured decode or speculative catalog and queued prefills can enter decode (`max_new_tokens > 1`, not `prompt_logprobs`), each queued prefiller's per-token prefill price receives an additional coalescing continuation term pricing the multi-step `K -> K + m` -decode-batch throughput surplus over a bounded per-stream decode horizon -(`coalescing_horizon_tokens`, default `64.0`, clamped to each prefiller's -post-prefill output budget and the active decoders' minimum remaining budget), +decode-batch throughput surplus over a bounded cohort-mean decode horizon +(`coalescing_horizon_tokens`, default `64.0`, averaged across active decoders +after clamping each decoder's remaining output budget to the prefiller's +post-prefill output budget and the configured horizon, with speculative +per-round expected output similarly clamped per decoder and averaged across the +cohort), amortized uniformly across the prefiller's uncached prompt tokens so total credit sums to 1× regardless of chunking and chunk sizing stays smooth under active decoder waiting age. The surplus is valued at intrinsic diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index 8295ffb71..cec12b660 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -528,8 +528,8 @@ impl RequestScheduler { return bonus_log; } let mut decoder_slots = [0usize; REQUEST_LANES]; + let mut decoder_rems = [0usize; REQUEST_LANES]; let mut decoder_count = 0usize; - let mut peer_budget = usize::MAX; let mut prefillers = [(0usize, 0usize, 0usize); REQUEST_LANES]; let mut prefiller_count = 0usize; for (slot, entry) in self.slots.iter().enumerate() { @@ -549,8 +549,8 @@ impl RequestScheduler { .min(self.limits.max_sequence_tokens.saturating_sub(r.scheduled_consumed as usize)); if rem > 0 { decoder_slots[decoder_count] = slot; + decoder_rems[decoder_count] = rem; decoder_count += 1; - peer_budget = peer_budget.min(rem); } } } else if !r.prompt_logprobs && r.scheduled_consumed < r.prompt_tokens as u64 { @@ -564,7 +564,7 @@ impl RequestScheduler { } } } - if decoder_count == 0 || prefiller_count == 0 || peer_budget == usize::MAX { + if decoder_count == 0 || prefiller_count == 0 { return bonus_log; } let max_drafts = self.capabilities.completion_token_capacity.saturating_sub(1); @@ -596,6 +596,9 @@ impl RequestScheduler { } sum }; + fn mean_capped(rems: &[usize], cap: f64) -> f64 { + rems.iter().map(|&rem| (rem as f64).min(cap)).sum::() / rems.len() as f64 + } let best_decode_rate = |n_streams: usize| -> f64 { let mut best = 0.0f64; if self.speculative_widths.is_empty() { @@ -624,7 +627,7 @@ impl RequestScheduler { max_per_lane }; let eff_width = max_per_lane.min(packed_per_lane).max(1.0); - let mean_out = expected_at(eff_width).min(peer_budget as f64).max(1.0); + let mean_out = mean_capped(&decoder_rems[..decoder_count], expected_at(eff_width)); let ms = shape.nanos as f64 / 1e6; best = best.max(served as f64 * mean_out / ms); } @@ -633,7 +636,7 @@ impl RequestScheduler { for &width in widths { if let Some(ns) = self.costs.duration(GraphKind::Speculative, batch, width).filter(|&n| n > 0) { let served = n_streams.min(batch); - let mean_out = expected_at(width as f64).min(peer_budget as f64).max(1.0); + let mean_out = mean_capped(&decoder_rems[..decoder_count], expected_at(width as f64)); let ms = ns as f64 / 1e6; best = best.max(served as f64 * mean_out / ms); } @@ -664,19 +667,14 @@ impl RequestScheduler { return bonus_log; } for &(slot, initial_prefill, post_prefill) in &prefillers[..prefiller_count] { - let horizon = self - .policy - .coalescing_horizon_tokens - .min(post_prefill as f64) - .min(peer_budget as f64); - if horizon > 0.0 { - // Amortize the unlocked coalescing surplus uniformly across the prefiller's - // uncached prompt tokens so total credit sums to 1x regardless of chunking - // and chunk sizing stays smooth under active decode waiting age. - let per_token = (best_surplus_per_horizon * horizon) / initial_prefill as f64; - if per_token.is_finite() && per_token > 0.0 { - bonus_log[slot] = per_token.ln(); - } + let ph = self.policy.coalescing_horizon_tokens.min(post_prefill as f64); + let horizon = mean_capped(&decoder_rems[..decoder_count], ph); + // Amortize the unlocked coalescing surplus uniformly across the prefiller's + // uncached prompt tokens so total credit sums to 1x regardless of chunking + // and chunk sizing stays smooth under active decode waiting age. + let per_token = (best_surplus_per_horizon * horizon) / initial_prefill as f64; + if per_token.is_finite() && per_token > 0.0 { + bonus_log[slot] = per_token.ln(); } } bonus_log diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 99d58599f..d73bfcd76 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -6863,6 +6863,223 @@ fn simultaneous_burst_coalesces_prefills_into_full_decode_batches() { assert!(sim_coal_full >= 120, "expected full B=4 decode rounds, got {sim_coal_full}"); } +fn coalescing_bonus(s: &mut RequestScheduler, slot: usize) -> f64 { + let saved = s.policy; + let (with_vals, _, with_scale) = s.lane_values(0); + let with_unscaled = with_vals[slot].prefill_token * with_scale.exp(); + s.policy.coalescing_horizon_tokens = 0.0; + let (without_vals, _, without_scale) = s.lane_values(0); + let without_unscaled = without_vals[slot].prefill_token * without_scale.exp(); + s.policy = saved; + (with_unscaled - without_unscaled).max(0.0) +} + +fn add_active_decoder(s: &mut RequestScheduler, id: u32, prompt: usize, rem: u32) -> RequestHandle { + let handle = add(s, id, prompt, rem + 1); + let req = s.request_mut(handle).unwrap(); + req.phase = RequestPhase::Decode; + req.consumed_tokens = prompt as u64; + req.scheduled_consumed = prompt as u64; + req.generated_tokens = 1; + handle +} + +#[test] +fn coalescing_horizon_averages_active_decoder_budgets_across_cohort() { + let setup = |decoder_rems: &[u32], prefill_max_new: u32| -> (RequestScheduler, usize) { + let mut s = interactive_engine(8, false); + set_cost(&mut s, GraphKind::Prefill, 1, 512, 100 * MS); + set_cost(&mut s, GraphKind::Decode, 1, 1, 15 * MS); + set_cost(&mut s, GraphKind::Decode, 2, 1, 20 * MS); + set_cost(&mut s, GraphKind::Decode, 4, 1, 24 * MS); + for (idx, &rem) in decoder_rems.iter().enumerate() { + add_active_decoder(&mut s, (idx + 1) as u32, 64, rem); + } + let prefill = add(&mut s, 99, 512, prefill_max_new); + (s, prefill.slot as usize) + }; + + // Mixed cohort: one near-EOS decoder (rem = 1) and one long decoder (rem = 100). + // Cohort-mean horizon is (min(1, 64) + min(100, 64)) / 2 = 32.5. + let (mut mixed, p_slot) = setup(&[1, 100], 128); + let mixed_bonus = coalescing_bonus(&mut mixed, p_slot); + let base_rate = 2.0 / 20.0; + let next_rate = 3.0 / 24.0; + let surplus = PolicyConfig::default().output_token_value * 3.0 * (1.0 - base_rate / next_rate); + let expected_mixed = (surplus * 32.5) / 512.0; + assert!( + (mixed_bonus - expected_mixed).abs() < 1e-9, + "mixed cohort coalescing bonus {mixed_bonus} should equal cohort-mean {expected_mixed}" + ); + + // Heterogeneous n=3 cohort: rem = [1, 20, 100] with ph = 64 gives + // cohort-mean horizon (1 + 20 + 64) / 3 = 85 / 3. + let (mut three, p_three) = setup(&[1, 20, 100], 128); + let three_bonus = coalescing_bonus(&mut three, p_three); + let three_base = 3.0 / 24.0; + let three_next = 4.0 / 24.0; + let three_surplus = + PolicyConfig::default().output_token_value * 4.0 * (1.0 - three_base / three_next); + let expected_three = (three_surplus * ((1.0 + 20.0 + 64.0) / 3.0)) / 512.0; + assert!( + (three_bonus - expected_three).abs() < 1e-9, + "n=3 cohort coalescing bonus {three_bonus} should equal cohort-mean {expected_three}" + ); + + // KV-headroom-clamped decoder (max_sequence_tokens - scheduled_consumed = 2 < max_new - generated = 100) + // alongside two long decoders (rem = 100) gives cohort-mean horizon (2 + 64 + 64) / 3. + // Note: KV-headroom clamping is Rust-specific (`scripts/scheduling_sim/simulator.py` tracks + // `max_new_tokens - generated` only). + let (mut kv_clamped, p_kv) = setup(&[100, 100, 100], 128); + let kv_limit = kv_clamped.limits.max_sequence_tokens as u64; + let d0_req = kv_clamped.slots[0].request.as_mut().unwrap(); + d0_req.consumed_tokens = kv_limit - 2; + d0_req.scheduled_consumed = kv_limit - 2; + let kv_bonus = coalescing_bonus(&mut kv_clamped, p_kv); + let expected_kv = (three_surplus * ((2.0 + 64.0 + 64.0) / 3.0)) / 512.0; + assert!( + (kv_bonus - expected_kv).abs() < 1e-9, + "KV-headroom-clamped cohort bonus {kv_bonus} should equal cohort-mean {expected_kv}" + ); + + // Single-decoder cohort matches exact min(horizon, post_prefill, rem). + let (mut single, p_single) = setup(&[10], 128); + let single_bonus = coalescing_bonus(&mut single, p_single); + let single_base = 1.0 / 15.0; + let single_next = 2.0 / 20.0; + let single_surplus = + PolicyConfig::default().output_token_value * 2.0 * (1.0 - single_base / single_next); + let expected_single = (single_surplus * 10.0) / 512.0; + assert!( + (single_bonus - expected_single).abs() < 1e-9, + "single-decoder coalescing bonus {single_bonus} should equal {expected_single}" + ); + + // Zero active decoders and single-token prefillers produce zero coalescing bonus. + let (mut no_decoders, p_no_dec) = setup(&[], 128); + assert_eq!(coalescing_bonus(&mut no_decoders, p_no_dec), 0.0); + let (mut one_tok_prefill, p_one_tok) = setup(&[1, 100], 1); + assert_eq!(coalescing_bonus(&mut one_tok_prefill, p_one_tok), 0.0); +} + +#[test] +fn coalescing_speculative_mean_output_averages_per_decoder_budgets() { + let make_spec_scheduler = |b4_w1_ms: u64, packed_b4: Option<(usize, u64)>| -> (RequestScheduler, RequestHandle, usize) { + let mut s = engine(4, true); + let mut graphs = super::tests::duration_graphs(4); + graphs.retain(|g| g.kind != GraphKind::Speculative); + graphs.push(crate::execution::GraphDescriptor { + tuned_bindings: vec![], + name: "speculative-b2-d7-w8-p16".to_string(), + kind: GraphKind::Speculative, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 7, + handle: 1, + batch_capacity: 2, + token_capacity: 8, + packed_token_capacity: 16, + prefill_capacity: 0, + estimated_duration_ns: 20 * MS, + input_bindings: vec![], + }); + graphs.push(crate::execution::GraphDescriptor { + tuned_bindings: vec![], + name: "speculative-b4-d0-w1-p4".to_string(), + kind: GraphKind::Speculative, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 0, + handle: 2, + batch_capacity: 4, + token_capacity: 1, + packed_token_capacity: 4, + prefill_capacity: 0, + estimated_duration_ns: b4_w1_ms * MS, + input_bindings: vec![], + }); + let mut registered = vec![(2, 8), (4, 1)]; + if let Some((packed_tokens, nanos_ms)) = packed_b4 { + graphs.push(crate::execution::GraphDescriptor { + tuned_bindings: vec![], + name: format!("speculative-b4-d7-w8-p{packed_tokens}"), + kind: GraphKind::Speculative, + sampling_mode: SamplingMode::General, + confidence_width: 0, + draft_tokens: 7, + handle: 3, + batch_capacity: 4, + token_capacity: 8, + packed_token_capacity: packed_tokens, + prefill_capacity: 0, + estimated_duration_ns: nanos_ms * MS, + input_bindings: vec![], + }); + registered.push((4, 8)); + } + s.measured_graph_durations(&graphs).unwrap(); + s.speculative_graphs(®istered).unwrap(); + let d0 = add_active_decoder(&mut s, 1, 64, 1); + let _d1 = add_active_decoder(&mut s, 2, 64, 100); + let p0 = add(&mut s, 3, 512, 128); + (s, d0, p0.slot as usize) + }; + + // Inspect the deterministic population acceptance curve on this engine so expected output + // is exact and independent of prior tuning constants. + let (probe, d0, _) = make_spec_scheduler(10, None); + let curve = probe.powered_curve(probe.request(d0).unwrap(), false); + let exp8 = super::rounds::forecast_tokens(&curve, 8); + assert!(exp8 > 1.5, "speculative prior must predict >1.5 tokens at width 8, got {exp8}"); + let cohort_mean_8 = (exp8.min(1.0) + exp8.min(100.0)) / 2.0; + + // 1. Wide B=2 speculative graph beats B=4 width-1 at K=2, while B=4 width-1 beats it at K=3. + let b4_ms = (25.0 / cohort_mean_8).round().max(1.0) as u64; + let (mut s, _, p_slot) = make_spec_scheduler(b4_ms, None); + let rate_a = 2.0 * cohort_mean_8 / 20.0; + let rate_b_2 = 2.0 / b4_ms as f64; + let rate_b_3 = 3.0 / b4_ms as f64; + assert!(rate_a > rate_b_2 && rate_b_3 > rate_a); + let expected_bonus = PolicyConfig::default().output_token_value + * 3.0 + * (1.0 - rate_a / rate_b_3) + * 32.5 + / 512.0; + let actual_bonus = coalescing_bonus(&mut s, p_slot); + assert!( + (actual_bonus - expected_bonus).abs() < 1e-9, + "speculative coalescing bonus {actual_bonus} should equal cohort-mean {expected_bonus}" + ); + + // 2. When B=4 width-1 is slower than cohort-mean B=2 width-8 even at K=3, surplus vanishes; + // clamping mean_out to min_i(rem_i) = 1 would erroneously report a positive bonus. + let slow_b4_ms = (35.0 / cohort_mean_8).ceil() as u64; + assert!(3.0 / (slow_b4_ms as f64) < rate_a); + let (mut s_sat, _, p_sat) = make_spec_scheduler(slow_b4_ms, None); + assert_eq!(coalescing_bonus(&mut s_sat, p_sat), 0.0); + + // 3. Packed host-allocation round (batch=4, packed=12) reduces eff_width from 6 at K=2 to + // 4 at K=3; cohort-mean reflects the per-decoder expected output at each packed eff_width. + let (mut s_packed, _, p_packed) = make_spec_scheduler(100, Some((12, 18))); + let exp6 = super::rounds::forecast_tokens(&curve, 6); + let exp4 = super::rounds::forecast_tokens(&curve, 4); + let mean_6 = (exp6.min(1.0) + exp6.min(100.0)) / 2.0; + let mean_4 = (exp4.min(1.0) + exp4.min(100.0)) / 2.0; + let base_packed = (2.0 * cohort_mean_8 / 20.0).max(2.0 * mean_6 / 18.0); + let next_packed = (2.0 * cohort_mean_8 / 20.0).max(3.0 * mean_4 / 18.0); + assert!(next_packed > base_packed); + let expected_packed = PolicyConfig::default().output_token_value + * 3.0 + * (1.0 - base_packed / next_packed) + * 32.5 + / 512.0; + let actual_packed = coalescing_bonus(&mut s_packed, p_packed); + assert!( + (actual_packed - expected_packed).abs() < 1e-9, + "packed speculative coalescing bonus {actual_packed} should equal {expected_packed}" + ); +} + #[test] fn short_prefill_tails_do_not_poison_full_chunk_graph_selection() { let mut s = interactive_engine(2, false); diff --git a/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index ccc9fcc08..006954276 100644 --- a/scripts/scheduling_sim/utility.py +++ b/scripts/scheduling_sim/utility.py @@ -230,13 +230,9 @@ def best_decode_rate(n_streams: int) -> float: best_surplus_per_horizon, self.value.decode_value * multiplier ) if best_surplus_per_horizon > 0: - peer_budget = min(v.output_budget for v in decoders) for view in prefillers: - horizon = min( - self.config.coalescing_horizon_tokens, - float(view.output_budget - 1), - float(peer_budget), - ) + ph = min(self.config.coalescing_horizon_tokens, float(view.output_budget - 1)) + horizon = sum(min(float(v.output_budget), ph) for v in decoders) / k if horizon > 0: initial_prefill = max( self._initial_prefill.get(view.name, view.remaining_prefill), diff --git a/tests/test_scheduling_utility.py b/tests/test_scheduling_utility.py index d041f2a2d..7adf6840a 100644 --- a/tests/test_scheduling_utility.py +++ b/tests/test_scheduling_utility.py @@ -503,6 +503,96 @@ def test_first_output_waiting_age_scaling_linearity_exclusions_and_burst_bounds( assert max(waiter_ttfts) < 15000.0, f"{k_dec}/{batch_cap}/{n_waiters}: max_ttft={max(waiter_ttfts)}" +def test_coalescing_horizon_averages_active_decoder_budgets(): + graphs = ( + Graph("prefill-512", 10.0, prefill_capacity=512), + Graph("decode-b1", 15.0, decode_capacity=1), + Graph("decode-b2", 20.0, decode_capacity=2), + Graph("decode-b4", 24.0, decode_capacity=4), + ) + policy = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + # Mixed cohort: one near-EOS decoder (budget=1) and one long decoder (budget=100). + # Cohort-mean horizon is (min(1, 64) + min(100, 64)) / 2 = 32.5. + policy.prepare([View("d0", 0, 1, ()), View("d1", 0, 100, ()), View("p0", 512, 128, ())], graphs) + actual_mixed = policy._coalesce_token["p0"] * exp(policy.log_scale) + expected_mixed = 64.0 * 3.0 * (1.0 - (2.0 / 20.0) / (3.0 / 24.0)) * 32.5 / 512.0 + assert abs(actual_mixed - expected_mixed) < 1e-9 + + # Single-decoder cohort matches exact min(horizon, post_prefill, budget). + policy_single = UtilityScheduler(Value(64), UtilityConfig(16, 4, 100, 0.1, "service")) + policy_single.prepare([View("d0", 0, 10, ()), View("p0", 512, 128, ())], graphs) + actual_single = policy_single._coalesce_token["p0"] * exp(policy_single.log_scale) + expected_single = 64.0 * 2.0 * (1.0 - (1.0 / 15.0) / (2.0 / 20.0)) * 10.0 / 512.0 + assert abs(actual_single - expected_single) < 1e-9 + + +def test_coalescing_heterogeneous_budget_end_to_end_balanced(): + graphs = catalog() + value = Value(64) + + # Non-speculative cohort: one near-EOS decoder (max_new_tokens=8 < 64) alongside three + # long decoders and four queued 4K prefills under balanced policy (age_price=0.1). + dec_reqs = [ + Request("short0", 0, 8, arrival_ms=0.0, acceptance=(0.0,) * 7, max_new_tokens=8), + *(Request(f"long{i}", 0, 256, arrival_ms=0.0, acceptance=(0.0,) * 7, max_new_tokens=256) for i in range(3)), + *(Request(f"p{i}", 4096, 256, arrival_ms=50.0, acceptance=(0.0,) * 7, max_new_tokens=256) for i in range(4)), + ] + dec_off = run( + dec_reqs, + graphs, + value, + scheduler=UtilityScheduler(value, UtilityConfig(16, 4, 100, 0.1, "service", 0.0)), + horizon_ms=30_000, + ) + dec_coal = run( + dec_reqs, + graphs, + value, + scheduler=UtilityScheduler(value, UtilityConfig(16, 4, 100, 0.1, "service")), + horizon_ms=30_000, + ) + assert dec_coal.summary["unfinished"] == 0 + dec_off_ttfts = [row["ttft_ms"] for row in dec_off.requests if row["name"].startswith("p")] + dec_coal_ttfts = [row["ttft_ms"] for row in dec_coal.requests if row["name"].startswith("p")] + assert dec_coal.summary["elapsed_ms"] < dec_off.summary["elapsed_ms"] + assert dec_coal.summary["elapsed_ms"] <= 7740.0 + assert sum(dec_coal_ttfts) / len(dec_coal_ttfts) < sum(dec_off_ttfts) / len(dec_off_ttfts) + assert max(dec_coal_ttfts) < max(dec_off_ttfts) and max(dec_coal_ttfts) <= 330.0 + assert dec_coal.summary["max_output_gap_ms"] < dec_off.summary["max_output_gap_ms"] + assert dec_coal.summary["max_output_gap_ms"] <= 190.0 + + # Speculative cohort: one short decoder (max_new_tokens=32 < 64) alongside three long + # decoders and five queued 4K prefills under balanced policy (age_price=0.1). + spec_reqs = [ + Request("short0", 0, 32, arrival_ms=0.0, acceptance=(1.0,) * 7, max_new_tokens=32), + *(Request(f"long{i}", 0, 256, arrival_ms=0.0, acceptance=(1.0,) * 7, max_new_tokens=256) for i in range(3)), + *(Request(f"p{i}", 4096, 256, arrival_ms=50.0, acceptance=(1.0,) * 7, max_new_tokens=256) for i in range(5)), + ] + spec_off = run( + spec_reqs, + graphs, + value, + scheduler=UtilityScheduler(value, UtilityConfig(16, 4, 100, 0.1, "service", 0.0)), + horizon_ms=30_000, + ) + spec_coal = run( + spec_reqs, + graphs, + value, + scheduler=UtilityScheduler(value, UtilityConfig(16, 4, 100, 0.1, "service")), + horizon_ms=30_000, + ) + assert spec_coal.summary["unfinished"] == 0 + spec_off_ttfts = [row["ttft_ms"] for row in spec_off.requests if row["name"].startswith("p")] + spec_coal_ttfts = [row["ttft_ms"] for row in spec_coal.requests if row["name"].startswith("p")] + assert spec_coal.summary["elapsed_ms"] < spec_off.summary["elapsed_ms"] + assert spec_coal.summary["elapsed_ms"] <= 1885.0 + assert sum(spec_coal_ttfts) / len(spec_coal_ttfts) < sum(spec_off_ttfts) / len(spec_off_ttfts) + assert max(spec_coal_ttfts) < max(spec_off_ttfts) and max(spec_coal_ttfts) <= 440.0 + assert spec_coal.summary["max_output_gap_ms"] <= spec_off.summary["max_output_gap_ms"] + assert spec_coal.summary["max_output_gap_ms"] <= 220.0 + + def test_coalescing_surplus_vanishes_at_saturated_batch_and_single_token_budget(): graphs = ( Graph("prefill-512", 10.0, prefill_capacity=512),