diff --git a/helios/src/scheduler/learning.rs b/helios/src/scheduler/learning.rs index 5ebfffb11..24b5a6555 100644 --- a/helios/src/scheduler/learning.rs +++ b/helios/src/scheduler/learning.rs @@ -5,18 +5,20 @@ //! Cost-bounded acquisition of request-local speculative yield observations. -use super::{policy::{Candidate, bits}, utility::LaneValue, *}; +use super::{policy::{Candidate, CurveCache, bits}, utility::LaneValue, *}; impl RequestScheduler { + #[cfg(test)] pub(super) fn optimistic_tokens(&self, request: &LiveRequest, width: usize) -> f64 { - super::rounds::forecast_tokens(&self.powered_curve(request, true), width) + self.proposal_forecast_tokens(request, width, true) } pub(super) fn acceptance_probe(&self, ordinary: Candidate, values: &[LaneValue; REQUEST_LANES], age_price: f64) -> Option { let mut candidates = Vec::new(); - self.packed_round_candidates(&mut candidates, values, age_price, true); - self.mixed_candidates(&mut candidates, values, age_price, true); + let mut curves = CurveCache::new(true); + self.packed_round_candidates_with_curves(&mut candidates, values, age_price, true, &mut curves); + self.mixed_candidates_with_curves(&mut candidates, values, age_price, true, &mut curves); let count = self.prune_padding(&mut candidates); // Round lengths depend only on the candidate, so each is estimated once. let widths = |candidate: Candidate, optimistic: bool| -> [usize; REQUEST_LANES] { diff --git a/helios/src/scheduler/policy.rs b/helios/src/scheduler/policy.rs index 21d0b8fcd..d976a8734 100644 --- a/helios/src/scheduler/policy.rs +++ b/helios/src/scheduler/policy.rs @@ -95,6 +95,40 @@ struct PrefillSlotPlan { nat_fit: Option, } +/// Per-slot memoization of powered speculative survival curves within one pricing pass. +/// Each cache instance is bound to one `optimistic` mode so optimistic and ordinary curves never mix. +pub(super) struct CurveCache { + optimistic: bool, + entries: [Option>; REQUEST_LANES], +} + +impl CurveCache { + pub(super) fn new(optimistic: bool) -> Self { + Self { + optimistic, + entries: std::array::from_fn(|_| None), + } + } + + pub(super) fn get_or_insert_with( + &mut self, + slot: usize, + optimistic: bool, + build: impl FnOnce() -> Vec, + ) -> &[f64] { + debug_assert_eq!( + self.optimistic, optimistic, + "CurveCache cannot mix optimistic and non-optimistic survival curves" + ); + self.entries[slot].get_or_insert_with(build) + } + + #[cfg(test)] + pub(super) fn is_cached(&self, slot: usize) -> bool { + self.entries[slot].is_some() + } +} + #[derive(Clone, Copy)] pub(super) struct Candidate { pub draft_tokens: usize, @@ -859,7 +893,12 @@ impl RequestScheduler { (values, age_price, scale) } - fn next_progress(&self, r: &LiveRequest, value: LaneValue) -> Option<(u64, f64)> { + fn next_progress( + &self, + r: &LiveRequest, + value: LaneValue, + curves: &mut CurveCache, + ) -> Option<(u64, f64)> { let mut best: Option<(ValueRate, f64)> = None; let mut consider = |ns, work| { let rate = ValueRate::new(ns, work, 0.0); @@ -905,7 +944,6 @@ impl RequestScheduler { } } } else { - let mut curve = None; if r.generated_tokens == 0 || self.speculative_widths.is_empty() { let kind = if r.generated_tokens == 0 { GraphKind::Resume @@ -921,15 +959,18 @@ impl RequestScheduler { for &(batch, ref widths) in &self.speculative_catalog { for &width in widths { if let Some(ns) = self.speculative_duration(r, batch, width) { - let curve = curve.get_or_insert_with(|| self.powered_curve(r, false)); - let expected = super::rounds::forecast_tokens(curve, self.speculative_tokens(r, width)); + let expected = self.cached_expected_tokens( + r, + self.speculative_tokens(r, width), + false, + curves, + ); consider(ns, value.decode(expected, ns as f64 / 1e6)); } } } } } - let mut mixed_curve = None; for &(batch, width, prefill) in &self.mixed_catalog { let Some(ns) = self .costs @@ -957,12 +998,15 @@ impl RequestScheduler { ); } } else if r.consumed_tokens >= r.prompt_tokens as u64 && r.generated_tokens > 0 { - let tokens = self.speculative_tokens(r, width); let expected = if self.speculative_widths.is_empty() { 1.0 } else { - let curve = mixed_curve.get_or_insert_with(|| self.powered_curve(r, false)); - super::rounds::forecast_tokens(curve, tokens) + self.cached_expected_tokens( + r, + self.speculative_tokens(r, width), + false, + curves, + ) }; consider(ns, value.decode(expected, ns as f64 / 1e6)); } @@ -976,12 +1020,13 @@ impl RequestScheduler { kind: GraphKind, duration_ns: u64, value: LaneValue, + curves: &mut CurveCache, ) -> f64 { if terminal_cleanup(r) { let ms = duration_ns as f64 / 1e6; return value.finish(ms, ms); } - let Some((mut following, work)) = self.next_progress(r, value) else { + let Some((mut following, work)) = self.next_progress(r, value, curves) else { return 0.0; }; if duration_ns == 0 || following == 0 { @@ -1046,6 +1091,7 @@ impl RequestScheduler { } } + #[allow(clippy::too_many_arguments)] fn continuation_candidate( &self, kind: GraphKind, @@ -1054,6 +1100,7 @@ impl RequestScheduler { first_offers: &[(usize, f64)], values: &[LaneValue; REQUEST_LANES], age_price: f64, + curves: &mut CurveCache, ) -> Option<(u64, ValueRate)> { if !matches!( kind, @@ -1124,7 +1171,7 @@ impl RequestScheduler { }; let total_ms = horizon as f64 / 1e6; let mut value = - self.lane_value_for_tokens(request, following, work, horizon, values[slot]); + self.prefill_lane_value(request, following, work, values[slot]); let mut selected = 1u64 << slot; if capacity > 1 { let mut finishing = [(0usize, 0.0); REQUEST_LANES]; @@ -1227,7 +1274,15 @@ impl RequestScheduler { let preceding = if horizon == 0 { 0 } else { duration_ns }; let offer = ( slot, - self.lane_value_within(request, role, extent, preceding, horizon, values[slot]), + self.cached_lane_value_within( + request, + role, + extent, + preceding, + horizon, + values[slot], + curves, + ), ); if mixed && role == GraphKind::Prefill { let best = &mut prompts[usize::from(promoted)]; @@ -1332,18 +1387,67 @@ impl RequestScheduler { } } - fn lane_value( + fn cached_expected_tokens( + &self, + r: &LiveRequest, + tokens: usize, + optimistic: bool, + curves: &mut CurveCache, + ) -> f64 { + if tokens <= 1 { + return f64::from(tokens != 0); + } + let curve = curves.get_or_insert_with( + r.handle.slot as usize, + optimistic, + || self.powered_curve(r, optimistic), + ); + super::rounds::forecast_tokens(curve, tokens) + } + + fn prefill_lane_value( + &self, + r: &LiveRequest, + kind: GraphKind, + tokens: usize, + value: LaneValue, + ) -> f64 { + let end = r.scheduled_consumed as usize + tokens; + let first_output = end == r.prompt_tokens; + let initial = r.initial_prefill_tokens(); + let mut val = value.prefill_within(tokens, initial, first_output); + if !first_output + && kind == GraphKind::TerminalPrefill + && r.deferred_prefill + && value.first_output_value > 0.0 + && tokens > 0 + && self.estimated_checkpoint_cut(r) == Some(end) + && self.fits_single_prefill_from(r, r.admission_reused_tokens as usize) + { + let reconciled = end.saturating_sub(r.prefix_tokens as usize); + if reconciled > tokens { + let old_frac = tokens as f64 / initial.max(tokens).max(1) as f64; + let new_frac = reconciled as f64 / initial.max(reconciled).max(1) as f64; + val += value.first_output_value * (new_frac - old_frac).max(0.0); + } + } + val + } + + pub(super) fn cached_lane_value( &self, r: &LiveRequest, kind: GraphKind, capacity: usize, duration_ns: u64, value: LaneValue, + curves: &mut CurveCache, ) -> f64 { - self.lane_value_within(r, kind, capacity, 0, duration_ns, value) + self.cached_lane_value_within(r, kind, capacity, 0, duration_ns, value, curves) } - fn lane_value_within( + #[allow(clippy::too_many_arguments)] + fn cached_lane_value_within( &self, r: &LiveRequest, kind: GraphKind, @@ -1351,29 +1455,43 @@ impl RequestScheduler { preceding_ns: u64, horizon_ns: u64, value: LaneValue, + curves: &mut CurveCache, ) -> f64 { - self.lane_value_for_tokens_within( + self.cached_lane_value_for_tokens_within( r, kind, self.lane_tokens(r, kind, capacity), preceding_ns, horizon_ns, value, + curves, ) } - fn lane_value_for_tokens( + #[cfg(test)] + pub(super) fn lane_value_for_tokens_within( &self, r: &LiveRequest, kind: GraphKind, tokens: usize, - duration_ns: u64, + preceding_ns: u64, + horizon_ns: u64, value: LaneValue, ) -> f64 { - self.lane_value_for_tokens_within(r, kind, tokens, 0, duration_ns, value) + let mut curves = CurveCache::new(false); + self.cached_lane_value_for_tokens_within( + r, + kind, + tokens, + preceding_ns, + horizon_ns, + value, + &mut curves, + ) } - pub(super) fn lane_value_for_tokens_within( + #[allow(clippy::too_many_arguments)] + fn cached_lane_value_for_tokens_within( &self, r: &LiveRequest, kind: GraphKind, @@ -1381,39 +1499,21 @@ impl RequestScheduler { preceding_ns: u64, horizon_ns: u64, value: LaneValue, + curves: &mut CurveCache, ) -> f64 { match kind { GraphKind::Prefill | GraphKind::TerminalPrefill | GraphKind::ScoredPrefill => { - let end = r.scheduled_consumed as usize + tokens; - let first_output = end == r.prompt_tokens; - let initial = r.initial_prefill_tokens(); - let mut val = value.prefill_within(tokens, initial, first_output); - if !first_output - && kind == GraphKind::TerminalPrefill - && r.deferred_prefill - && value.first_output_value > 0.0 - && tokens > 0 - && self.estimated_checkpoint_cut(r) == Some(end) - && self.fits_single_prefill_from(r, r.admission_reused_tokens as usize) - { - let reconciled = end.saturating_sub(r.prefix_tokens as usize); - if reconciled > tokens { - let old_frac = tokens as f64 / initial.max(tokens).max(1) as f64; - let new_frac = reconciled as f64 / initial.max(reconciled).max(1) as f64; - val += value.first_output_value * (new_frac - old_frac).max(0.0); - } - } - val + self.prefill_lane_value(r, kind, tokens, value) } GraphKind::Decode | GraphKind::Speculative => value.decode_within( - self.expected_speculative_tokens(r, tokens), + self.cached_expected_tokens(r, tokens, false, curves), preceding_ns as f64 / 1e6, horizon_ns as f64 / 1e6, ), GraphKind::Resume => { value.decode_within(1.0, preceding_ns as f64 / 1e6, horizon_ns as f64 / 1e6) } - _ => self.prerequisite_value(r, kind, horizon_ns, value), + _ => self.prerequisite_value(r, kind, horizon_ns, value, curves), } } @@ -1436,7 +1536,7 @@ impl RequestScheduler { ) else { continue; }; - let rate = ValueRate::new(slot_ns, self.lane_value_for_tokens(r, kind, work, slot_ns, values[slot]), age_price); + let rate = ValueRate::new(slot_ns, self.prefill_lane_value(r, kind, work, values[slot]), age_price); if winner.is_none_or(|(best_slot, _, _, best_rate)| match rate.compare(best_rate) { std::cmp::Ordering::Greater => true, std::cmp::Ordering::Equal => slot < best_slot, @@ -1455,6 +1555,7 @@ impl RequestScheduler { }); } + #[allow(clippy::too_many_arguments)] fn add_candidate( &self, output: &mut Vec, @@ -1464,6 +1565,7 @@ impl RequestScheduler { mask: u64, values: &[LaneValue; REQUEST_LANES], age_price: f64, + curves: &mut CurveCache, ) { let Some(duration_ns) = self.costs.duration(kind, batch, capacity) else { return; @@ -1477,7 +1579,7 @@ impl RequestScheduler { } offers[count] = ( slot, - self.lane_value(r, kind, capacity, duration_ns, values[slot]), + self.cached_lane_value(r, kind, capacity, duration_ns, values[slot], curves), ); count += 1; } @@ -1507,6 +1609,7 @@ impl RequestScheduler { &offers[..count], values, age_price, + curves, ) .unwrap_or_else(|| (selected, ValueRate::new(duration_ns, expected, age_price))); output.push(Candidate { host_lengths: None, draft_tokens: drafts, packed_token_capacity: packed, @@ -1530,8 +1633,10 @@ impl RequestScheduler { age_price: f64, ) { output.clear(); - self.mixed_candidates(output, values, age_price, false); - self.packed_round_candidates(output, values, age_price, false); + // Request and forecast state stay fixed within a candidate pass; evaluate each lane curve at most once. + let mut curves = CurveCache::new(false); + self.mixed_candidates_with_curves(output, values, age_price, false, &mut curves); + self.packed_round_candidates_with_curves(output, values, age_price, false, &mut curves); let mut prefill_plans = [PrefillSlotPlan::default(); REQUEST_LANES]; for kind in [ GraphKind::Prefill, @@ -1572,28 +1677,47 @@ impl RequestScheduler { } } else if kind == GraphKind::Vision { for &capacity in &self.capabilities.vision.patch_capacities { - self.add_candidate(output, kind, 1, capacity, mask, values, age_price); + self.add_candidate( + output, kind, 1, capacity, mask, values, age_price, &mut curves, + ); } } else if kind == GraphKind::Speculative { for &(batch, ref widths) in &self.speculative_catalog { for &capacity in widths { - self.add_candidate(output, kind, batch, capacity, mask, values, age_price); + self.add_candidate( + output, kind, batch, capacity, mask, values, age_price, &mut curves, + ); } } } else { for &batch in self.costs.batches(kind) { - self.add_candidate(output, kind, batch, 1, mask, values, age_price); + self.add_candidate( + output, kind, batch, 1, mask, values, age_price, &mut curves, + ); } } } } + #[cfg(test)] pub(super) fn mixed_candidates( &self, output: &mut Vec, values: &[LaneValue; REQUEST_LANES], age_price: f64, optimistic: bool, + ) { + let mut curves = CurveCache::new(optimistic); + self.mixed_candidates_with_curves(output, values, age_price, optimistic, &mut curves); + } + + pub(super) fn mixed_candidates_with_curves( + &self, + output: &mut Vec, + values: &[LaneValue; REQUEST_LANES], + age_price: f64, + optimistic: bool, + curves: &mut CurveCache, ) { let decode = if self.speculative_widths.is_empty() { GraphKind::Decode @@ -1625,11 +1749,10 @@ impl RequestScheduler { }) { continue; } - let value = self.lane_value( + let value = self.prefill_lane_value( r, GraphKind::Prefill, - prefill, - duration_ns, + self.prefill_work(r, prefill), values[slot], ); if prompt.is_none_or(|(_, best)| value > best) { @@ -1639,8 +1762,22 @@ impl RequestScheduler { Some(kind) if kind == decode => { decoders[count] = ( slot, - if optimistic { values[slot].decode(self.optimistic_tokens(r, self.speculative_tokens(r, width)), duration_ns as f64 / 1e6) } - else { self.lane_value(r, decode, width, duration_ns, values[slot]) }, + if optimistic { + let tokens = self.speculative_tokens(r, width); + values[slot].decode( + self.cached_expected_tokens(r, tokens, true, curves), + duration_ns as f64 / 1e6, + ) + } else { + self.cached_lane_value( + r, + decode, + width, + duration_ns, + values[slot], + curves, + ) + }, ); count += 1; } @@ -1862,12 +1999,16 @@ impl RequestScheduler { candidate.feedback = !kind.pipelines(); let slot = request.handle.slot as usize; let kind = if mixed { GraphKind::Prefill } else { candidate.kind }; - let mut expected = self.lane_value_for_tokens(request, kind, work, duration_ns, values[slot]); + let mut expected = self.prefill_lane_value(request, kind, work, values[slot]); if mixed { let decode = if self.speculative_widths.is_empty() { GraphKind::Decode } else { GraphKind::Speculative }; expected += bits(candidate.mask & !(1 << slot)).map(|slot| { - self.lane_value(self.slots[slot].request.as_ref().unwrap(), decode, - candidate.capacity, duration_ns, values[slot]) + let r = self.slots[slot].request.as_ref().unwrap(); + let tokens = self.lane_tokens(r, decode, candidate.capacity); + values[slot].decode( + self.expected_speculative_tokens(r, tokens), + duration_ns as f64 / 1e6, + ) }).sum::(); } candidate.rate = ValueRate::new( @@ -1987,8 +2128,11 @@ impl RequestScheduler { ); } } else { + let mut curves = CurveCache::new(false); for &batch in self.costs.batches(kind) { - self.add_candidate(&mut candidates, kind, batch, 1, mask, &values, age_price); + self.add_candidate( + &mut candidates, kind, batch, 1, mask, &values, age_price, &mut curves, + ); } } let candidate = *candidates diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 19944eae7..660859d49 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -9506,3 +9506,347 @@ fn deferred_terminal_prefill_at_checkpoint_cut_credits_reconciled_segment_wait() ); } } + +#[test] +fn waiting_init_prices_each_decoding_lane_curve_once_per_candidate_pass() { + let shapes = [ + (2, 3, 128, 2 * MS), + (4, 3, 256, 3 * MS), + (8, 8, 512, 4 * MS), + ]; + let mut s = mixed_engine(8, true, &shapes); + let decoders: Vec<_> = (0..4).map(|id| add(&mut s, id, 64, 128)).collect(); + ready(&mut s, &decoders); + let _waiting_init = add(&mut s, 99, 128, 128); + + let (values, age, _) = s.lane_values(0); + let mut candidates = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.candidates(&mut candidates, &values, age); + let evaluations = super::rounds::CURVE_EVALUATIONS.get(); + + assert!(candidates.iter().any(|c| c.kind == GraphKind::Init)); + assert!(candidates.iter().any(|c| c.kind == GraphKind::Speculative)); + assert!(candidates.iter().any(|c| c.kind == GraphKind::Mixed)); + assert_eq!( + evaluations, + decoders.len(), + "each decoding lane's powered curve must be evaluated once per candidate pass" + ); +} + +#[test] +fn mixed_candidates_price_each_decoding_lane_curve_once_per_call() { + let shapes = [ + (2, 1, 64, MS), + (2, 3, 128, 2 * MS), + (4, 3, 256, 3 * MS), + (8, 8, 512, 4 * MS), + ]; + let mut s = mixed_engine(8, true, &shapes); + let decoders: Vec<_> = (0..4).map(|id| add(&mut s, id, 64, 128)).collect(); + ready(&mut s, &decoders); + let prefill = add(&mut s, 99, 256, 128); + initialize(&mut s, prefill); + + let (values, age, _) = s.lane_values(0); + for optimistic in [false, true] { + let mut candidates = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.mixed_candidates(&mut candidates, &values, age, optimistic); + let evaluations = super::rounds::CURVE_EVALUATIONS.get(); + + assert!(candidates.len() >= shapes.len()); + assert_eq!( + evaluations, + decoders.len(), + "mixed_candidates(optimistic={optimistic}) must evaluate each decoding lane's powered curve once per call" + ); + } +} + +#[test] +fn decode_only_candidate_pass_builds_no_forecast_curve() { + let shapes = [(2, 1, 128, 2 * MS), (4, 1, 256, 3 * MS)]; + let mut s = mixed_engine(8, false, &shapes); + let decoders: Vec<_> = (0..4).map(|id| add(&mut s, id, 64, 128)).collect(); + ready(&mut s, &decoders); + let _waiting_init = add(&mut s, 99, 128, 128); + + let (values, age, _) = s.lane_values(0); + let mut candidates = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.candidates(&mut candidates, &values, age); + + assert!(candidates.iter().any(|c| c.kind == GraphKind::Decode)); + assert!(candidates.iter().any(|c| c.kind == GraphKind::Init)); + assert_eq!( + super::rounds::CURVE_EVALUATIONS.get(), + 0, + "decode-only candidate pricing must not build speculative forecast curves" + ); +} + +#[test] +fn cached_lane_pricing_matches_uncached_for_unit_and_fractional_alpha() { + let shapes = [ + (2, 1, 64, MS), + (2, 3, 128, 2 * MS), + (3, 3, 192, 2_500_000), + (4, 3, 256, 3 * MS), + (8, 8, 512, 4 * MS), + ]; + let candidate_key = |c: &Candidate| { + ( + c.kind, + c.mask, + c.batch, + c.capacity, + c.packed_token_capacity, + c.prefill_capacity, + c.prefill_slot, + c.duration_ns, + c.rate.duration_ns, + c.rate.score.to_bits(), + ) + }; + for alpha in [1.0, 0.6] { + let mut s = mixed_engine(8, true, &shapes); + s.configure_policy(PolicyConfig { + adaptive_verification_alpha: alpha, + ..s.policy + }) + .unwrap(); + // Two decoding lanes with distinct observations and two identical lanes to exercise ties. + let wide_decoders: Vec<_> = (0..4).map(|id| add(&mut s, id, 64, 128)).collect(); + // A decoding lane with one output token remaining has speculative width 1. + let last_token_decoder = add(&mut s, 10, 64, 2); + let mut all_decoders = wide_decoders.clone(); + all_decoders.push(last_token_decoder); + ready(&mut s, &all_decoders); + for (idx, &handle) in wide_decoders.iter().enumerate() { + let accepted = match idx { + 0 => 5, + 1 => 1, + _ => 3, // Slots 2 and 3 share identical observations and values. + }; + let req = s.request_mut(handle).unwrap(); + req.acceptance + .observe(req.generated_tokens, 7, accepted, true, None); + } + let prefill = add(&mut s, 20, 256, 128); + initialize(&mut s, prefill); + let _waiting_init = add(&mut s, 30, 128, 128); + + let (values, age, _) = s.lane_values(0); + let mut curves = super::policy::CurveCache::new(false); + for &handle in &all_decoders { + let slot = handle.slot as usize; + let r = s.request(handle).unwrap(); + let mut ordinary_reference_curve = Vec::new(); + for optimistic in [false, true] { + let reference_curve: Vec = s + .speculative_curve(r, optimistic) + .into_iter() + .map(|p| p.powf(alpha)) + .collect(); + assert_eq!(s.powered_curve(r, optimistic), reference_curve); + for width in [0usize, 1, 2, 4, 8] { + let expected = super::rounds::forecast_tokens(&reference_curve, width); + let actual = if optimistic { + s.optimistic_tokens(r, width) + } else { + s.expected_speculative_tokens(r, width) + }; + assert_eq!(actual.to_bits(), expected.to_bits()); + } + if !optimistic { + ordinary_reference_curve = reference_curve; + } + } + for (kind, capacity) in [ + (GraphKind::Decode, 1), + (GraphKind::Speculative, 1), + (GraphKind::Speculative, 3), + (GraphKind::Speculative, 8), + ] { + let tokens = if kind == GraphKind::Decode { + 1 + } else { + s.speculative_tokens(r, capacity) + }; + let cached = + s.cached_lane_value(r, kind, capacity, 3 * MS, values[slot], &mut curves); + let fresh_cache = + s.lane_value_for_tokens_within(r, kind, tokens, 0, 3 * MS, values[slot]); + let reference = values[slot].decode( + super::rounds::forecast_tokens(&ordinary_reference_curve, tokens), + 3.0, + ); + assert_eq!(cached.to_bits(), fresh_cache.to_bits()); + assert_eq!(cached.to_bits(), reference.to_bits()); + } + } + assert!( + !curves.is_cached(last_token_decoder.slot as usize), + "a lane with one remaining output token must not populate the curve cache" + ); + + let mut candidates = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.candidates(&mut candidates, &values, age); + assert_eq!( + super::rounds::CURVE_EVALUATIONS.get(), + wide_decoders.len(), + "only lanes with speculative width > 1 should evaluate a curve (alpha={alpha})" + ); + // Repeated passes produce the exact same ordered candidate vector and selected winner. + let mut repeat = Vec::new(); + s.candidates(&mut repeat, &values, age); + let keys: Vec<_> = candidates.iter().map(candidate_key).collect(); + let repeat_keys: Vec<_> = repeat.iter().map(candidate_key).collect(); + assert_eq!(keys, repeat_keys); + + // Packed speculative candidates from the shared pass match standalone packed_round_candidates. + let mut standalone_packed = Vec::new(); + s.packed_round_candidates(&mut standalone_packed, &values, age, false); + let shared_packed: Vec<_> = candidates + .iter() + .filter(|c| c.kind == GraphKind::Speculative) + .map(candidate_key) + .collect(); + let standalone_packed_keys: Vec<_> = + standalone_packed.iter().map(candidate_key).collect(); + assert_eq!(shared_packed, standalone_packed_keys); + + // Verify every Mixed candidate (both ordinary and optimistic) reuses its curve cache + // and matches uncached pricing bit-for-bit. + for optimistic in [false, true] { + let mut mixed = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.mixed_candidates(&mut mixed, &values, age, optimistic); + assert_eq!( + super::rounds::CURVE_EVALUATIONS.get(), + wide_decoders.len(), + "mixed_candidates(optimistic={optimistic}, alpha={alpha}) must evaluate only wide decoders once" + ); + if !optimistic { + let shared_mixed: Vec<_> = candidates + .iter() + .filter(|c| c.kind == GraphKind::Mixed) + .map(candidate_key) + .collect(); + let direct_mixed: Vec<_> = mixed.iter().map(candidate_key).collect(); + assert_eq!(shared_mixed, direct_mixed); + } + for c in &mixed { + let mut expected = 0.0; + for slot in super::policy::bits(c.mask) { + let r = s.slots[slot].request.as_ref().unwrap(); + if c.prefill_slot == Some(slot) { + expected += s.lane_value_for_tokens_within( + r, + GraphKind::Prefill, + s.prefill_work(r, c.prefill_capacity), + 0, + c.duration_ns, + values[slot], + ); + } else { + let tokens = s.speculative_tokens(r, c.capacity); + let ref_curve: Vec = s + .speculative_curve(r, optimistic) + .into_iter() + .map(|p| p.powf(alpha)) + .collect(); + let expected_tokens = super::rounds::forecast_tokens(&ref_curve, tokens); + if optimistic { + assert_eq!( + s.optimistic_tokens(r, tokens).to_bits(), + expected_tokens.to_bits() + ); + } + expected += + values[slot].decode(expected_tokens, c.duration_ns as f64 / 1e6); + } + } + let reference_rate = ValueRate::new(c.duration_ns, expected, age); + assert_eq!(c.rate.score.to_bits(), reference_rate.score.to_bits()); + } + } + + // Verify waiting Init continuation candidates and selected plan winner stay deterministic + // and break ties between identical decoding lanes consistently toward the lower slot. + let init_candidates: Vec<_> = candidates + .iter() + .filter(|c| c.kind == GraphKind::Init) + .collect(); + assert!(!init_candidates.is_empty()); + let init_plan = s.phase_plan(GraphKind::Init, None); + assert_eq!(init_plan.kind, GraphKind::Init); + let best_init = init_candidates + .iter() + .max_by(|a, b| a.rate.compare(b.rate)) + .unwrap(); + assert_eq!( + init_plan.selection_value_rate.to_bits(), + best_init.rate.score.to_bits() + ); + // Batch-3 Mixed with a prompt leaves two decoder slots: slot 0 wins first, and + // the tie between identical slots 2 and 3 breaks toward lower slot 2. + let tied_mixed = candidates + .iter() + .find(|c| { + c.kind == GraphKind::Mixed + && c.batch == 3 + && c.capacity == 3 + && c.prefill_slot == Some(prefill.slot as usize) + }) + .unwrap(); + let slot0 = wide_decoders[0].slot as usize; + let slot2 = wide_decoders[2].slot as usize; + let slot3 = wide_decoders[3].slot as usize; + assert_ne!(tied_mixed.mask & (1 << slot0), 0); + assert_ne!(tied_mixed.mask & (1 << slot2), 0); + assert_eq!(tied_mixed.mask & (1 << slot3), 0); + + // Optimistic packed candidates and acceptance_probe share one optimistic curve cache + // across packed and mixed pricing without mixing curve modes. + let mut opt_packed = Vec::new(); + super::rounds::CURVE_EVALUATIONS.set(0); + s.packed_round_candidates(&mut opt_packed, &values, age, true); + assert!(!opt_packed.is_empty()); + assert_eq!( + super::rounds::CURVE_EVALUATIONS.get(), + wide_decoders.len(), + "optimistic packed_round_candidates must evaluate only wide decoders once (alpha={alpha})" + ); + let ordinary_winner = *candidates + .iter() + .max_by(|a, b| a.rate.compare(b.rate)) + .unwrap(); + super::rounds::CURVE_EVALUATIONS.set(0); + let _probe = s.acceptance_probe(ordinary_winner, &values, age); + assert_eq!( + super::rounds::CURVE_EVALUATIONS.get(), + wide_decoders.len(), + "acceptance_probe must share one optimistic curve cache across packed and mixed pricing (alpha={alpha})" + ); + let winner = s.plan().unwrap(); + let winner_repeat = s.plan().unwrap(); + assert_eq!( + ( + winner.kind, + winner.batch_capacity, + winner.token_capacity, + winner.selection_value_rate.to_bits(), + ), + ( + winner_repeat.kind, + winner_repeat.batch_capacity, + winner_repeat.token_capacity, + winner_repeat.selection_value_rate.to_bits(), + ) + ); + } +} diff --git a/helios/src/scheduler/rounds.rs b/helios/src/scheduler/rounds.rs index cf5aeaceb..c515c279d 100644 --- a/helios/src/scheduler/rounds.rs +++ b/helios/src/scheduler/rounds.rs @@ -5,7 +5,13 @@ //! Completed speculative forecasts and unified captured generation rounds. -use super::{policy::{Candidate, bits}, utility::{LaneValue, ValueRate, best_cohort}, *}; +use super::{policy::{Candidate, CurveCache, bits}, utility::{LaneValue, ValueRate, best_cohort}, *}; + +#[cfg(test)] +thread_local! { + /// Powered speculative curve evaluations on this thread, for tests that bound planning work. + pub(super) static CURVE_EVALUATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} const POPULATION_PRIOR_WEIGHT: f32 = 4.0; const POPULATION_MAX_WEIGHT: f32 = 64.0; @@ -561,8 +567,14 @@ impl RequestScheduler { if mask & (1 << slot) == 0 { return Vec::new(); } let request = self.slots[slot].request.as_ref().unwrap(); if gpu { self.speculative_curve(request, optimistic) } - else { request.acceptance.curve(request.generated_tokens, optimistic) - .into_iter().map(|probability| probability.powf(self.policy.adaptive_verification_alpha) * values[slot].output_token).collect() } + else { + let alpha = self.policy.adaptive_verification_alpha; + request.acceptance.curve(request.generated_tokens, optimistic) + .into_iter().map(|probability| { + let powered = if alpha == 1.0 { probability } else { probability.powf(alpha) }; + powered * values[slot].output_token + }).collect() + } }); let mut positions = Vec::new(); for slot in bits(mask) { @@ -584,8 +596,13 @@ impl RequestScheduler { for &slot in available { let request = self.slots[slot].request.as_ref().unwrap(); let limit = self.speculative_tokens(request, width.min(drafts + 1)); - probabilities[slot] = request.acceptance.curve(request.generated_tokens, optimistic) - .into_iter().map(|probability| probability.powf(self.policy.adaptive_verification_alpha)).collect(); + let alpha = self.policy.adaptive_verification_alpha; + let curve = request.acceptance.curve(request.generated_tokens, optimistic); + probabilities[slot] = if alpha == 1.0 { + curve + } else { + curve.into_iter().map(|probability| probability.powf(alpha)).collect() + }; for position in 0..limit.saturating_sub(1) { scores.push((probabilities[slot][position] * values[slot].output_token, position, slot)); } @@ -617,13 +634,25 @@ impl RequestScheduler { self.proposal_forecast_tokens(request, width, false) } - fn proposal_forecast_tokens(&self, request: &LiveRequest, width: usize, optimistic: bool) -> f64 { + pub(super) fn proposal_forecast_tokens(&self, request: &LiveRequest, width: usize, optimistic: bool) -> f64 { + if width <= 1 { + return f64::from(width != 0); + } forecast_tokens(&self.powered_curve(request, optimistic), width) } /// Prefix survival raised to the adaptive verification exponent. pub(super) fn powered_curve(&self, request: &LiveRequest, optimistic: bool) -> Vec { - self.speculative_curve(request, optimistic).into_iter().map(|p| p.powf(self.policy.adaptive_verification_alpha)).collect() + #[cfg(test)] + CURVE_EVALUATIONS.set(CURVE_EVALUATIONS.get() + 1); + let curve = self.speculative_curve(request, optimistic); + if self.policy.adaptive_verification_alpha == 1.0 { + return curve; + } + curve + .into_iter() + .map(|p| p.powf(self.policy.adaptive_verification_alpha)) + .collect() } pub(super) fn speculative_duration(&self, request: &LiveRequest, batch: usize, width: usize) -> Option { @@ -821,8 +850,16 @@ impl RequestScheduler { rate: ValueRate::new(shape.nanos, value, age), feedback: false }) } + #[cfg(test)] pub(super) fn packed_round_candidates(&self, output: &mut Vec, values: &[LaneValue; REQUEST_LANES], age: f64, optimistic: bool) { + let mut curves = CurveCache::new(optimistic); + self.packed_round_candidates_with_curves(output, values, age, optimistic, &mut curves); + } + + /// Price packed speculative rounds while reusing per-lane powered curves for the same `optimistic` mode. + pub(super) fn packed_round_candidates_with_curves(&self, output: &mut Vec, + values: &[LaneValue; REQUEST_LANES], age: f64, optimistic: bool, curves: &mut CurveCache) { let available: Vec<_> = self.slots.iter().enumerate().filter_map(|(slot, entry)| { let request = entry.request.as_ref()?; (request.phase == RequestPhase::Decode && self.eligible(request)).then_some(slot) @@ -830,8 +867,6 @@ impl RequestScheduler { let mut forecasts = HashMap::new(); let mut fixed_prefixes = HashMap::new(); let mut host_rankings = HashMap::new(); - // Lane forecasts stay fixed while shapes compete; evaluate each at most once. - let mut curves: [Option>; REQUEST_LANES] = std::array::from_fn(|_| None); let mut order = Vec::with_capacity(available.len()); let mut frontier = std::collections::BinaryHeap::new(); for shape in self.costs.packed_round_shapes() { @@ -866,7 +901,10 @@ impl RequestScheduler { for &slot in &available { let request = self.slots[slot].request.as_ref().unwrap(); let limit = self.speculative_tokens(request, (shape.drafts + 1).min(shape.width)); - let curve = curves[slot].get_or_insert_with(|| self.powered_curve(request, optimistic)); + if limit <= 1 { + continue; + } + let curve = curves.get_or_insert_with(slot, optimistic, || self.powered_curve(request, optimistic)); let mut before = 1.0; for position in 0..limit.saturating_sub(1) { let total = forecast_tokens(curve, position + 2);