Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docs/scheduling-runtime-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 16 additions & 18 deletions helios/src/scheduler/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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 {
Expand All @@ -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);
Expand Down Expand Up @@ -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::<f64>() / rems.len() as f64
}
let best_decode_rate = |n_streams: usize| -> f64 {
let mut best = 0.0f64;
if self.speculative_widths.is_empty() {
Expand Down Expand Up @@ -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);
}
Expand All @@ -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);
}
Expand Down Expand Up @@ -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
Expand Down
217 changes: 217 additions & 0 deletions helios/src/scheduler/policy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&registered).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);
Expand Down
8 changes: 2 additions & 6 deletions scripts/scheduling_sim/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading