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
63 changes: 48 additions & 15 deletions docs/scheduling-runtime-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,20 @@ output token: beta + f/x
output delivery: g/z
```

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),
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
`output_token_value`, avoiding amplification of low-rate fairness prices, and
vanishes when active decode capacity is already saturated or when a queued
prefiller cannot enter decode (`max_new_tokens == 1`).

Only decoding requests have a delivery coordinate or output-age cost. Normalized
service prices follow the entropy-dual update in `scheduling-utility.md`. When a
prefilling request's maximum feasible token rate changes between chunks (for
Expand Down Expand Up @@ -403,16 +417,32 @@ Every selected complete speculative program enters the cost catalog with its
actual B/D/W/P. A smaller captured producer is a distinct physical program;
metadata must not relabel it as a deeper producer.

The first positive device observation sets the estimate. Further valid samples
while fresh use the median of the last nine replay observations, averaging the
middle pair when fewer than nine samples give an even count. An entry becomes stale after 30 seconds
The first positive device observation sets the estimate. For non-prefill
graphs, further valid samples while fresh use the median of the last nine
replay observations, averaging the middle pair when fewer than nine samples give
an even count. For pure prefill graphs (`PREFILL`, `TERMINAL_PREFILL`, and
`SCORED_PREFILL`), samples are stratified across six fill-ratio and KV-context
depth buckets (`u <= 0.5` vs `u > 0.5` crossed with `< 4096`, `4096..32768`,
and `>= 32768` starting tokens), each retaining a nine-sample rolling median.
Predictions fit a three-parameter nonnegative linear model
`theta_0 + theta_1 * u + theta_2 * u * (start_position / 4096)` by exact
relative-error-weighted nonnegative least squares over populated stratum
medians; when only a narrow fill regime (spread `< 0.15`) has been observed,
queries above `u_max` apply a bounded constant-throughput upward floor
`t_at_umax * min(u / u_max, 4)` to the base term (before adding `theta_2 * h`)
so partial fills cannot discount full-chunk cost estimates or lock out a large
capacity after TTL reset. When a smaller prefill capacity has no deep-context observations
(`start_position >= 4096`), it borrows the per-token KV-context slope
`theta_2 / peer_capacity` from the largest fresh strictly larger peer of the
same graph kind so deep prompts do not drift down onto stale shallow smaller
capacities. An entry becomes stale after 30 seconds
without a valid observation. Its measured cost remains available for selection
and service-rate normalization. The first valid observation of a stale entry
replaces its estimate directly; elapsed time alone never makes a measured graph
unknown. When multiple packed speculative shapes cover a `(batch, width)` lookup
for service-rate normalization or continuation pricing, Helios takes the minimum
positive measured duration across matching shapes and returns zero only when
every matching shape is unmeasured.
replaces its estimate directly (clearing all prefill strata); elapsed time alone
never makes a measured graph unknown. When multiple packed speculative shapes
cover a `(batch, width)` lookup for service-rate normalization or continuation
pricing, Helios takes the minimum positive measured duration across matching
shapes and returns zero only when every matching shape is unmeasured.

The raw device observation is the maximum positive rank-local CUDA replay interval.
When the prepared graphs expose frame-owned readiness timestamps, the cost sample
Expand Down Expand Up @@ -559,13 +589,15 @@ resource availability, and feedback dependencies without rerunning selection.
Cancellation stops further selection immediately; pages and state slots remain
owned through their last submitted fence.

The transport has two frame slots. Only ordinary decode and complete speculative
generation may occupy both. Prefill, scored prefill, mixed execution, resume,
vision, and state operations drain the window. Unknown or stale costs, grammar,
copy-only proposals, host-fed pending tokens or committed cursors, history
inputs, and phase transitions also require completion feedback. Dependency
checks apply to the actual selected program. A finishing prefill exposes its
decoder and checkpoint operation only after completion.
The transport has two frame slots. Ordinary decode, complete speculative
generation, and consecutive nonterminal `PREFILL` chunks may occupy both when
they neither reach prompt completion or a conditioned-window limit nor arm or
land on a checkpoint cut. Terminal prefill (`TERMINAL_PREFILL`), scored prefill,
mixed execution, resume, vision, and state operations drain the window. Unknown
or stale costs, grammar, copy-only proposals, host-fed pending tokens or
committed cursors, history inputs, and phase transitions also require completion
feedback. Dependency checks apply to the actual selected program. A finishing
prefill exposes its decoder and checkpoint operation only after completion.

Checkpoint retention uses the exact token endpoints supplied by the native
frontend. Zero snapshot capacity disables all checkpoint cuts. Otherwise, the last
Expand Down Expand Up @@ -649,6 +681,7 @@ Defaults specify these preferences:
| `adaptation_ms` | 100 | Service-price adaptation time |
| `estimate_ttl_ns` | 30,000,000,000 | Timing freshness interval |
| `adaptive_verification_alpha` | 1 | Exponent on prefix-survival estimates in speculative selection scores |
| `coalescing_horizon_tokens` | 64 | Output-token horizon for decode-batch coalescing bonus on queued prefills |

These weights express a throughput/cadence tradeoff. They are not graph timing
measurements or latency guarantees. Setting fairness or age coefficients to zero
Expand Down
5 changes: 3 additions & 2 deletions helios/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,8 +478,9 @@ delivery price initializes from its reference delivery interval. See
`PolicyConfig` holds value coefficients, not time limits. Its defaults are an
output-token value of 64 prompt-token units, token fairness 16, delivery
fairness 4, decode-age price 0.1, terminal value 256, terminal-age price 1, a
100 ms service-price adaptation time, a 30-second timing freshness interval, and
adaptive-verification exponent 1. No millisecond cap applies to a frame or to
100 ms service-price adaptation time, a 30-second timing freshness interval,
adaptive-verification exponent 1, and a 64-token decode-batch coalescing
horizon. No millisecond cap applies to a frame or to
the queued frames together. When the oldest queued graph runs past its expected
finish, further queueing stops until its completion arrives. The coefficients
are preferences, not latency bounds. Mixed prefill/generation graphs are
Expand Down
4 changes: 4 additions & 0 deletions helios/src/execution/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ impl GraphKind {
matches!(self, Self::Prefill | Self::TerminalPrefill | Self::ScoredPrefill)
}

pub fn pipelines(self) -> bool {
matches!(self, Self::Decode | Self::Speculative | Self::Prefill)
}

pub fn samples(self) -> bool {
matches!(
self,
Expand Down
9 changes: 7 additions & 2 deletions helios/src/execution/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,13 @@ impl TensorParallelExecutor {
if self.shutdown.is_some() {
return Err(invalid("tensor-parallel executor is closed"));
}
let barrier = grammar || !matches!(self.local.manifest().graphs.get(graph).map(|g| g.kind),
Some(super::GraphKind::Decode | super::GraphKind::Speculative));
let barrier = grammar
|| !self
.local
.manifest()
.graphs
.get(graph)
.is_some_and(|g| g.kind.pipelines());
if !self.can_submit(barrier) { return Ok(None); }
let Some(fence) = self.local.validate_submission(graph, uploads, grammar)? else {
return Ok(None);
Expand Down
10 changes: 6 additions & 4 deletions helios/src/execution/threaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -870,10 +870,12 @@ impl ThreadedExecutor {
return Err(error);
}
let barrier = grammar
|| !matches!(
self.local.manifest().graphs.get(graph).map(|g| g.kind),
Some(super::GraphKind::Decode | super::GraphKind::Speculative)
);
|| !self
.local
.manifest()
.graphs
.get(graph)
.is_some_and(|g| g.kind.pipelines());
if !self.can_submit(barrier) {
return Ok(None);
}
Expand Down
7 changes: 1 addition & 6 deletions helios/src/execution/threaded/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use std::{fmt::Write as _, time::Duration};

use super::{ExecutionManifest, Fence, FrameCompletion, Result, VecDeque, invalid};
use crate::execution::GraphKind;

pub(crate) trait PendingFrame {
fn fence(&self) -> Fence;
Expand All @@ -29,11 +28,7 @@ pub(crate) fn can_submit_pending<P: PendingFrame>(
&& pending.back().is_none_or(|frame| frame.committed())
&& (!barrier || pending.is_empty())
&& !pending.iter().any(|frame| {
frame.grammar()
|| !matches!(
manifest.graphs[frame.graph()].kind,
GraphKind::Decode | GraphKind::Speculative
)
frame.grammar() || !manifest.graphs[frame.graph()].kind.pipelines()
})
}

Expand Down
5 changes: 5 additions & 0 deletions helios/src/execution/threaded/protocol_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,11 @@ fn rank_coordinator_matches_model_pending_window() {
assert!(can_submit_pending(&pending, false, &manifest));
assert!(!can_submit_pending(&pending, true, &manifest));
manifest.graphs[0].kind = GraphKind::Prefill;
assert!(can_submit_pending(&pending, false, &manifest));
pending[0].grammar = true;
assert!(!can_submit_pending(&pending, false, &manifest));
pending[0].grammar = false;
manifest.graphs[0].kind = GraphKind::TerminalPrefill;
assert!(!can_submit_pending(&pending, false, &manifest));
manifest.graphs[0].kind = GraphKind::Speculative;
assert!(can_submit_pending(&pending, false, &manifest));
Expand Down
6 changes: 2 additions & 4 deletions helios/src/execution/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -964,8 +964,7 @@ impl GraphExecutor {
) -> Result<Option<Fence>> {
let fence = self.next_fence()?;
validate_uploads(&self.manifest, graph, uploads, &mut self.resolved_uploads)?;
if !self.can_submit(grammar || !matches!(self.manifest.graphs[graph].kind,
GraphKind::Decode | GraphKind::Speculative)) {
if !self.can_submit(grammar || !self.manifest.graphs[graph].kind.pipelines()) {
return Ok(None);
}
if crate::engram::consumes(self.manifest.graphs[graph].kind) {
Expand Down Expand Up @@ -1017,8 +1016,7 @@ impl GraphExecutor {
self.manifest.graphs.get(graph_index).ok_or_else(|| {
Error::execution(ExecutionError::State, "graph index out of range")
})?;
let grammar_constrained = grammar_constrained
|| !matches!(graph.kind, GraphKind::Decode | GraphKind::Speculative);
let grammar_constrained = grammar_constrained || !graph.kind.pipelines();
let mut resolved = validate_uploads(
&self.manifest,
graph_index,
Expand Down
2 changes: 1 addition & 1 deletion helios/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ pub fn scheduler_capabilities_with_manifest(
let semantics = config.contract.graph(&graph.name)?;
let inputs: Vec<_> = semantics.inputs.iter().filter(|binding|
matches!(binding.source, ValueSource::PendingToken | ValueSource::PromptAndPendingToken)
|| matches!(graph.kind, GraphKind::Decode | GraphKind::Speculative | GraphKind::Mixed)
|| matches!(graph.kind, GraphKind::Prefill | GraphKind::Decode | GraphKind::Speculative | GraphKind::Mixed)
&& matches!(binding.source, ValueSource::ConsumedTokens | ValueSource::SnapshotConsumedTokens))
.map(|binding| binding.buffer.clone()).collect();
if !inputs.is_empty() {
Expand Down
59 changes: 54 additions & 5 deletions helios/src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,12 +851,27 @@ impl RequestScheduler {
.unwrap_or(0)
}

pub(super) fn prefill_cursor(request: &LiveRequest) -> usize {
request.scheduled_consumed.max(request.consumed_tokens) as usize
}

pub(super) fn resolve_prefill_kind(
&self,
request: &LiveRequest,
capacity: usize,
work: usize,
cut: Option<usize>,
) -> GraphKind {
self.resolve_prefill_kind_from(request, Self::prefill_cursor(request), capacity, work, cut)
}

pub(super) fn resolve_prefill_kind_from(
&self,
request: &LiveRequest,
start: usize,
capacity: usize,
work: usize,
cut: Option<usize>,
) -> GraphKind {
if request.prompt_logprobs {
return GraphKind::ScoredPrefill;
Expand All @@ -865,7 +880,7 @@ impl RequestScheduler {
.unwrap_or(request.prompt_tokens)
.min(request.prefill_limit())
.min(request.prompt_tokens);
let end = (request.consumed_tokens as usize).saturating_add(work);
let end = start.saturating_add(work);
let window = self.terminal_prefill_window();
let needs_terminal =
end >= next_stop || (window > 0 && next_stop.saturating_sub(end) <= window);
Expand All @@ -887,6 +902,15 @@ impl RequestScheduler {
&self,
request: &LiveRequest,
cut: Option<usize>,
) -> bool {
self.prefill_requires_terminal_completion_from(request, Self::prefill_cursor(request), cut)
}

pub(super) fn prefill_requires_terminal_completion_from(
&self,
request: &LiveRequest,
start: usize,
cut: Option<usize>,
) -> bool {
if request.prompt_logprobs || self.terminal_prefill_catalog.is_empty() {
return false;
Expand All @@ -895,20 +919,20 @@ impl RequestScheduler {
.unwrap_or(request.prompt_tokens)
.min(request.prefill_limit())
.min(request.prompt_tokens);
let remaining = next_stop.saturating_sub(request.consumed_tokens as usize);
let remaining = next_stop.saturating_sub(start);
if remaining == 0 {
return false;
}
if request.deferred_prefill {
let Some(&max_terminal) = self.terminal_prefill_catalog.last() else {
return false;
};
return self.prefill_work_through(request, max_terminal, cut) >= remaining;
return self.prefill_work_from(request, start, max_terminal, cut) >= remaining;
}
let Some(&max_capacity) = self.prefill_catalog.last() else {
return false;
};
if self.prefill_work_through(request, max_capacity, cut) < remaining {
if self.prefill_work_from(request, start, max_capacity, cut) < remaining {
return false;
}
let Some(&smallest_fit) = self.prefill_catalog.iter().find(|&&cap| cap >= remaining) else {
Expand Down Expand Up @@ -1082,10 +1106,35 @@ impl RequestScheduler {
Ok(())
}

fn prefill_step_requires_feedback(&self, plan: &ScheduledPlan) -> bool {
if plan
.checkpoint_plans
.iter()
.any(checkpoints::CapturePlan::requires_feedback)
{
return true;
}
plan.lanes.iter().any(|lane| {
let Ok(request) = self.request(lane.request) else {
return true;
};
let end = lane.start_position.saturating_add(lane.tokens as u64);
request.prompt_logprobs
|| request.checkpoint_capture.is_some()
|| end >= request.prompt_tokens as u64
|| end >= request.prefill_limit() as u64
})
}

pub fn plan_requires_feedback(&self, plan: &ScheduledPlan) -> bool {
let geometry = (plan.kind, plan.batch_capacity, plan.draft_tokens, plan.token_capacity,
plan.packed_token_capacity, plan.prefill_capacity());
plan.requires_feedback || !matches!(plan.kind, GraphKind::Decode | GraphKind::Speculative)
let kind_requires_feedback = match plan.kind {
GraphKind::Prefill => self.prefill_step_requires_feedback(plan),
kind => !kind.pipelines(),
};
plan.requires_feedback
|| kind_requires_feedback
|| self.capabilities.completion_inputs.iter().any(|(key, inputs)| *key == geometry && !inputs.is_empty())
|| plan.lanes.iter().any(|lane| self.request(lane.request).is_ok_and(|request|
request.grammar_constrained))
Expand Down
Loading
Loading