From 05d6b602e91c6fcbe762e9339260f176b10e9c33 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 reference wait while waiting prompts accumulate none. When a returning or newly arrived prompt competes against a large active decode cohort (for example, 8 to 31 concurrent decoders on models without mixed prefill-decode graphs), the prompt must wait for its token-service fairness price to ramp up over multiple seconds before winning a prefill slot. If 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, or `ServicePrice` exemptions: - `helios/src/scheduler/service.rs`: Extend delivery-reference selection with `delivery_references_and_decode_batch`, returning 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). Using `b_served = min(B, K_dec)` from incumbent decoders only keeps waiting prompts from amplifying each other under oversubscribed bursts (`K > B`) or small-batch catalogs. - `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`, where `frac = 1.0` when the step finishes the prompt and `frac = work / initial_prefill` on non-finishing chunks. The credit is carried through prerequisite and two-stage continuation scoring (`Init`, `Restore`, `Vision`, `Snapshot`) without adding waiting prompts to the common waiting-cost penalty sum. - `helios/src/scheduler.rs` and `helios/src/server/runtime.rs`: Track `RequestAccounting::first_output_wait_ns`. Preserve it across a prefill chunk stopped strictly by an armed `RetentionRole::Anchor` cut when the prompt otherwise fit in a single eligible prefill graph, while continuing to charge all measured token service truthfully in `observe_service`. Carry `last_output_ns` across preemption and forced-reasoning readmission so readmitted streams age from their most recent output rather than stale original arrival time. - `scripts/scheduling_sim/utility.py` and `helios/src/scheduler/policy_tests.rs`: Mirror the zero-knob formula in `UtilityScheduler` and add unit tests for policy/zero-decoder/score-only inertness, `b_served * T_dec` scaling, anchor-cut wait-clock preservation, and readmission wait clamping. Expected benefit: - Under `--scheduler-policy balanced`, reduce returning-prompt TTFT behind 8 to 31 active decoders from multi-second stalls to sub-second latency while keeping incumbent decode gap distributions bounded under oversubscribed and small-batch bursts. - Under `--scheduler-policy throughput` (`decode_age_price = 0.0`), zero-decoder workloads, and score-only `prompt_logprobs` (`max_new_tokens = 0`), remain completely inert. All previously exported model cores load and serve unchanged. Supporting evidence and limitations: - Prototype commit prepared for early design review prior to running the Linux Rust test suite, Python simulator regression suite, TLA+ conformance checks, and served GPU A/B benchmarks. All offline simulator projections and full verification runs remain to be executed and reported before marking ready for review. Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com> Design-Signed-Off-By: yatesdr; design-review=2e5b --- helios/src/scheduler.rs | 35 +++++- helios/src/scheduler/policy.rs | 100 +++++++++++++-- helios/src/scheduler/policy_tests.rs | 181 +++++++++++++++++++++++++++ helios/src/scheduler/service.rs | 24 +++- helios/src/scheduler/utility.rs | 19 ++- helios/src/server/runtime.rs | 8 ++ scripts/scheduling_sim/utility.py | 23 +++- 7 files changed, 374 insertions(+), 16 deletions(-) diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 9f4f20988..cf45a78be 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,6 +2674,32 @@ impl RequestScheduler { let mut window_snapshots = Vec::new(); for (row, lane) in step.lanes.iter().enumerate() { let kind = step.lane_kind(row); + // A prefill stopped strictly by an armed anchor cut on a prompt that + // otherwise fit in one eligible prefill graph keeps its first-output + // wait clock across the forced split so its short tail is not re-queued + // behind active decoders at zero waiting age. + let preserve_first_output_wait = kind.is_prefill() + && self.request(lane.request).is_ok_and(|request| { + 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 prefill = + (record.consumed_tokens as u64).saturating_sub(request.consumed_tokens); + let output = record.generated_tokens - request.generated_tokens as i64; + record.status != 3 + && !finished + && prefill > 0 + && output == 0 + && !request.deferred_prefill + && (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) + }); let Ok(request) = self.request_mut(lane.request) else { continue; }; @@ -2757,7 +2788,9 @@ impl RequestScheduler { }; 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..50c8aecfe 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; + } } } } @@ -254,6 +264,19 @@ impl RequestScheduler { 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 = arrival_ns; + Ok(()) + } + + pub fn set_first_output_wait(&mut self, handle: RequestHandle, wait_ns: u64) -> Result<()> { + let request = self.request(handle)?; + if wait_ns > self.now_ns || request.last_use != Fence(0) { + return Err( + "first-output wait must precede admission and be assigned before dispatch".into(), + ); + } + let request = self.slots[handle.slot as usize].request.as_mut().unwrap(); + request.accounting.first_output_wait_ns = wait_ns.max(request.accounting.arrival_ns); Ok(()) } @@ -284,6 +307,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 +437,32 @@ 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 = if request.prompt_logprobs { + &self.scored_prefill_catalog + } else if terminal_only { + &self.terminal_prefill_catalog + } else { + &self.prefill_catalog + }; + 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() + }) + } + pub fn submission_window_available(&self, duration_ns: u64) -> bool { self.submissions.len() < 2 && !self.submissions.values().any(|s| s.requires_feedback) @@ -473,10 +523,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 +671,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 +726,29 @@ 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 = + self.policy.decode_age_price * incumbent_decode_batch_ms * age_ms; } scale = scale .max(token_log[slot]) @@ -694,6 +765,7 @@ impl RequestScheduler { value.delivery = (delivery_log[slot] - scale).exp(); value.terminal *= unit; value.age_price *= unit; + value.first_output_value *= unit; age_price += value.age_price; } (values, age_price, scale) @@ -731,8 +803,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 +856,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 +1294,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..ece9e5c36 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -6930,3 +6930,184 @@ 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); + 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]).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::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 anchor boundary at 202. + let handle = s + .admit(RequestSpec { + prompt: vec![42; 204], + message_boundaries: vec![202, 204], + 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 (512 > 256) resets wait clock. + let long = s + .admit(RequestSpec { + prompt: vec![99; 512], + message_boundaries: vec![256, 512], + 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_eq!(chunk.lanes[0].tokens, 256); + 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(10 * 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).unwrap(); + s.set_first_output_wait(handle, 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); +} diff --git a/helios/src/scheduler/service.rs b/helios/src/scheduler/service.rs index c37121640..069c3c772 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); let family = |r: &LiveRequest| match r.phase { RequestPhase::Decode if self.speculative_widths.is_empty() => Some(GraphKind::Decode), RequestPhase::Decode => Some(GraphKind::Speculative), @@ -154,10 +165,21 @@ impl RequestScheduler { excluded_wait_ms: (count - served).max(0.0) * per_delivery_ms, served_share: (served / count).min(1.0), }); + if matches!(kind, GraphKind::Decode | GraphKind::Speculative) + && (per_delivery_ms < best_decode.0 + || (per_delivery_ms == best_decode.0 && served > best_decode.1)) + { + best_decode = (per_delivery_ms, served); + } } } } - references + let incumbent_decode_batch_ms = if best_decode.0.is_finite() { + best_decode.1 * best_decode.1 * best_decode.0 + } 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..9748de79a 100644 --- a/helios/src/scheduler/utility.rs +++ b/helios/src/scheduler/utility.rs @@ -85,11 +85,28 @@ 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) + self.prefill_within(consumed, consumed.max(1), 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).min(1.0) + }; + value += self.first_output_value * fraction; + } + value } pub fn decode(&self, expected_output: f64, duration_ms: f64) -> f64 { diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 538145f10..5a6dab691 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. @@ -1569,6 +1572,9 @@ impl<'a> Worker<'a> { }; incoming.blocked = None; self.scheduler.set_arrival(handle, incoming.arrival_ns)?; + if let Some(last_output_ns) = parked.as_ref().and_then(|parked| parked.carried.last_output_ns) { + self.scheduler.set_first_output_wait(handle, last_output_ns)?; + } let slot = handle.slot as usize; if let Err(error) = self .scheduler @@ -2447,6 +2453,7 @@ 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 last_output_ns = live.accounting().last_output_ns.or(active.carried.last_output_ns); if publish_terminal { self.scheduler.finish(handle)?; } else { @@ -2486,6 +2493,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/scripts/scheduling_sim/utility.py b/scripts/scheduling_sim/utility.py index a276ed64b..7b32b1500 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,11 @@ def prepare(self, views: list[View], catalog: tuple[Graph, ...], now_ms: float = for graph in measured if decoding and graph.decode_capacity), default=None, ) + incumbent_decode_batch_ms = 0.0 + if reference is not None: + per_delivery_ms, neg_served = reference + served = -neg_served + incumbent_decode_batch_ms = per_delivery_ms * served * served for view in views: actions = candidates([view], catalog, self.value) if not actions: @@ -238,15 +245,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