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
19 changes: 11 additions & 8 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -803,14 +803,17 @@ An output limit or user stop omits a strict call that began but did not finish;
EOS inside such a call produces an error. A required or named tool choice
still fails if no qualifying call completed.
An active strict function tool attaches a request grammar for the entire
generation, including reasoning, prose, and tool calls. While generation is inside
an open reasoning region declared by the output envelope, tokens are validated on
the host without device masks so speculative widths and two-frame pipelining stay
active; once reasoning closes (or if a token violates the grammar), the runtime
transitions to device-masked decoding at MTP width one with one step in flight
for any decode batch containing it. Outside open reasoning—including prose when
`tool_choice: "auto"` produces only prose—device grammar enforcement applies
from the start. See the [native replay loop](core-design.md#native-replay-loop).
generation, including reasoning, prose, and tool calls. While generation is inside an open reasoning region declared by the output
envelope, tokens are validated on the host without per-step vocabulary mask
recomputation: non-speculative models keep one step in flight with an all-ones
mask and toggle the synced mask in place when reasoning closes, while
speculative models keep full speculative widths and two-frame pipelining active
and transition via in-place toggle or terminal-checkpoint restore (falling back
to rollback on burst overshoot or grammar rejection). Outside open
reasoning—including prose when `tool_choice: "auto"` produces only prose—device
grammar enforcement applies at MTP width one with one step in flight for any
decode batch containing it. See the
[native replay loop](core-design.md#native-replay-loop).
Active strict tools on unsupported parsers, `strict: true` on custom or
Messages tools, and invalid strict schemas return HTTP 400. Custom Lark
answer grammars cannot be combined with active strict tools on DSML, Qwen
Expand Down
24 changes: 16 additions & 8 deletions docs/core-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -1726,14 +1726,22 @@ ordinary function arguments. An active strict function tool constrains its call
using the declared schema and the core's tool syntax. The output encoder holds
the call until it has validated the complete arguments; a truncated strict call
does not publish partial arguments. The composed request grammar validates the entire generation: reasoning, prose,
and tool calls. While generation is inside an open reasoning region declared by
the output envelope, the runtime validates emitted tokens on the host without
device grammar masks, allowing multi-token speculation and two-frame executor
pipelining; when reasoning closes or a token is rejected by the grammar, the
runtime truncates any burst overshoot, drains any queued frame, syncs the
grammar mask, and readmits the continuation with device grammar enforcement.
While device grammar masking is active (outside open reasoning, including prose
and tool calls), the request uses MTP width one and the
and tool calls. While generation is inside an open reasoning region declared by the output
envelope, the runtime validates emitted tokens on the host without recomputing
vocabulary masks. Non-speculative models keep one step in flight with device
`GrammarEnabled` active and a cached all-ones mask during open reasoning, then
toggle the synced vocabulary mask in place on the live slot when reasoning
closes or re-opens without thinking-budget expansion (or publish and restore a
terminal checkpoint when thinking-budget expansion applies). Speculative models run unmasked reasoning with multi-token
speculation and two-frame executor pipelining; when reasoning closes with no
overshoot and no pending frame or budget expansion, cores whose sampling graphs
bind `ValueSource::GrammarEnabled` toggle in place, while cores without
per-step `GrammarEnabled` bindings (or with one draining frame that does not
consume past the boundary) preserve KV and recurrent state by publishing a
terminal checkpoint and restoring it. Speculative burst overshoot or grammar
rejection falls back to cancelling the live slot and readmitting the truncated
prefix. While device grammar masking is active (outside open reasoning,
including prose and tool calls), the request uses MTP width one and the
[native replay loop](#native-replay-loop) keeps one step in flight for any
decode batch containing it.
`tool_choice=required` requires a completed call to a declared tool;
Expand Down
40 changes: 31 additions & 9 deletions docs/mtp-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,15 +420,37 @@ are ready.

While a grammar-constrained request is inside an open reasoning region declared
by its output envelope (including reasoning opened after a constrained recipient
or content-header frame), the runtime runs without device grammar masks so the
request uses full speculative widths and two-frame executor pipelining without a
feedback barrier. On completion, the runtime validates each emitted token
against the request grammar on the host without recomputing the full vocabulary
mask. When a token closes reasoning or is rejected by the grammar, the runtime
suppresses any trailing overshoot tokens in that burst, cancels the live slot so
any queued second frame drains without emitting output or publishing a terminal
snapshot, syncs the vocabulary mask at the exact boundary prefix, and readmits
the continuation with device grammar masking enabled.
or content-header frame), the runtime validates each emitted token against the
request grammar on the host without recomputing the full vocabulary mask. On
non-speculative models, the request keeps a step-level feedback barrier with
device `GrammarEnabled` active and a cached all-ones mask during open
reasoning, and toggles the synced vocabulary mask in place on the live slot
when reasoning closes or re-opens without thinking-budget expansion (or
publishes and restores a terminal checkpoint when thinking-budget expansion
applies). On speculative models, open reasoning runs
without device grammar masks so the request uses full speculative widths and
two-frame executor pipelining without a feedback barrier:

- When a token closes reasoning (or re-opens reasoning) with no burst
overshoot, no queued second frame, and no thinking-budget expansion, cores
whose sampling graphs bind `ValueSource::GrammarEnabled` toggle the
scheduler's grammar constraint, device `GrammarEnabled`, and vocabulary mask
in place on the live slot.
- When reasoning closes or re-opens with no burst overshoot on a speculative
core whose sampling graphs do not bind `ValueSource::GrammarEnabled` (or when
a thinking-budget expansion applies or a single second frame is already in
flight), the runtime pauses further scheduling for that slot while any
in-flight frame drains. If the drained frame stays at or below the exact
boundary length (`consumed_tokens <= exact_len`), Helios publishes an
immutable terminal checkpoint (`Snapshot` -> `finish`) and readmits the
continuation via `Restore` (`Prefill(1)` or `Resume`) with the updated
grammar mode, preserving live KV and recurrent state.
- When a burst overshoots the boundary, a draining second frame consumes past
the boundary, or the host grammar rejects a token, the runtime suppresses any
trailing overshoot tokens, cancels the live slot so queued work drains
without publishing a terminal snapshot, syncs the vocabulary mask at the
exact boundary prefix, and readmits the continuation with device grammar
masking enabled.

Host-evaluated custom stops (stop strings and stop token sequences) participate
in multi-token speculative rounds and two-frame executor pipelining without a
Expand Down
19 changes: 13 additions & 6 deletions docs/prefix-cache-offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,19 @@ handshake rejects mismatched rank modes at startup, and multi-host `--rank` +
`selene-manager` negotiates raw-only and excludes packed records for
multi-process sessions):

- In `gpu` mode, new captures encode on GPU as `GKV1`, matrix-predictor and
large-page (>= 256 KiB) `GKV1` restores decode on GPU (falling back to the
bounded CPU pool if a background capture holds the GPU codec), and smaller
non-matrix `GKV1` and `ZKV1` restores decode on the bounded CPU worker pool
over async HtoD DMA so critical-path restores do not stall behind foreground
GPU saturation. All active offload tiers (`memory`, `disk`, `pool`) share one
- In `gpu` mode, new captures encode on GPU as `GKV1`, acquiring
`CopyEngineGate::enter_offload_batch` before locking the per-rank GPU codec
mutex so background captures blocked on active peer-copy graphs do not hold
the codec mutex. Matrix-predictor and large-page (>= 256 KiB) `GKV1` restores
partition windows into maximal GPU-batched, CPU-batched, and singleton runs
so leading or interleaved `Literal` and CPU-routed pages do not disable GPU
batching for subsequent `GKV1` pages. Foreground GPU restores non-blockingly
acquire the codec mutex and `CopyEngineGate::try_enter_offload_batch`,
falling back immediately to the bounded CPU pool without blocking or
consuming a gate wave token when a background capture holds the GPU codec or
a peer-copy graph blocks the gate. Smaller non-matrix `GKV1` and `ZKV1`
restores decode on the bounded CPU worker pool over async HtoD DMA so
critical-path restores do not stall behind foreground GPU saturation. All active offload tiers (`memory`, `disk`, `pool`) share one
3-buffer aliased per-rank `GpuRankCodec` workspace (~130 MiB per GPU on
GLM-5.3-Flash TP4, ~32 MiB per GPU on DeepSeek-V4.1-Flash TP4, ~440 MiB on
Qwen3.8-Flash-Next TP1) with no secondary CUDA primary context. Because `gpu`
Expand Down
49 changes: 31 additions & 18 deletions docs/scheduling-runtime-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,29 +463,42 @@ 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. 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.
The first positive device observation sets the estimate. For graphs without
variable prefill work, 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`) and mixed graphs (`MIXED`), samples
are stratified across six positive-fill and KV-context depth buckets
(`u <= 0.5` vs `u > 0.5` crossed with `< 4096`, `4096..32768`, and `>= 32768`
starting tokens), plus a zero-fill bucket for decode-only `MIXED` executions
(`work == 0`), 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
medians; when only a narrow positive-fill regime (`pos_u_max > 0`,
`pos_u_max - pos_u_min < 0.15` across positive-fill strata) has been observed,
queries above `pos_u_max` apply a bounded constant-throughput upward floor
`pos_t_at_umax * min(u / pos_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, even after zero-fill `MIXED` samples
have been recorded. Decode-only `MIXED` queries (`work == 0`) use `theta_0`
only when a `zero_fill` sample anchors it and `theta_0 > 0`, falling back to
the lowest-fill observed median (`t_at_umin`) otherwise so positive-fill-only
fits never extrapolate decode-only latency toward zero. When a `MIXED` entry
has recorded only `zero_fill` samples (`pos_u_max == 0`), decode-only queries
use that observed median while positive-fill queries (`work > 0`) remain
unmeasured (`0`) until a positive-fill step executes, preventing decode-only
samples from under-pricing full-chunk prefills or inflating prefill service
rates. 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 (clearing all prefill strata); elapsed time alone
never makes a measured graph unknown. When multiple packed speculative shapes
same graph kind (and same `(batch, width)` for `MIXED`) 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 (clearing all fill and context 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.
Expand Down
2 changes: 1 addition & 1 deletion helios/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
execution::{CompletionRecord, ExecutionManifest, GraphKind},
scheduler::{SchedulerCapabilities, SchedulerLimits},
};
pub use admission::Admission;
pub use admission::{Admission, AdmissionGrammar};
pub use contract::PreparedContract;
pub use inputs::{InputStep, pack_inputs};
pub use packing::Inputs;
Expand Down
62 changes: 53 additions & 9 deletions helios/src/model/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,47 @@ impl PromptMetadataMut<'_> {
}
}

/// Device-side grammar masking state for an admitted request.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum AdmissionGrammar {
/// Device grammar masking is disabled (`GrammarEnabled = 0`, all-ones mask).
#[default]
Disabled,
/// Device grammar masking is enabled (`GrammarEnabled = 1`) with an all-ones mask
/// so non-speculative requests can toggle masks in place without `Restore`.
UnmaskedEnabled,
/// Device grammar masking is enabled (`GrammarEnabled = 1`) with an explicit mask.
Masked(Vec<i32>),
}

impl AdmissionGrammar {
pub fn is_enabled(&self) -> bool {
!matches!(self, Self::Disabled)
}

pub fn mask(&self) -> Option<&[i32]> {
match self {
Self::Masked(mask) => Some(mask.as_slice()),
Self::Disabled | Self::UnmaskedEnabled => None,
}
}

pub fn mask_mut(&mut self) -> Option<&mut Vec<i32>> {
match self {
Self::Masked(mask) => Some(mask),
Self::Disabled | Self::UnmaskedEnabled => None,
}
}
}

pub struct Admission {
pub handle: RequestHandle,
pub sampling: SamplingParameters,
pub core_parameters: crate::model::CoreParameters,
pub max_new_tokens: u32,
pub prompt: Vec<u32>,
pub data: crate::model::PromptData,
pub grammar_mask: Option<Vec<i32>>,
pub grammar: AdmissionGrammar,
pub ignore_eos: bool,
pub prompt_logprobs: bool,
}
Expand Down Expand Up @@ -94,8 +127,8 @@ impl Admission {
.iter()
.any(|token| *token as usize >= config.contract.input_vocabulary)
|| self
.grammar_mask
.as_ref()
.grammar
.mask()
.is_some_and(|mask| mask.len() != config.contract.vocabulary.div_ceil(32))
{
return Err(
Expand All @@ -112,12 +145,17 @@ impl Admission {

#[cfg(feature = "server")]
pub(crate) fn grammar_updated(&mut self, mask: &[i32]) {
self.grammar_mask
.as_mut()
self.grammar
.mask_mut()
.expect("grammar admission has a mask")
.copy_from_slice(mask);
}

#[cfg(feature = "server")]
pub(crate) fn set_grammar(&mut self, grammar: AdmissionGrammar) {
self.grammar = grammar;
}

#[cfg(feature = "server")]
pub fn from_prompt(
config: &ModelConfig,
Expand All @@ -133,28 +171,34 @@ impl Admission {
prompt.tokens.len(),
ignore_eos,
grammar_constrained,
grammar_constrained,
)
}

#[cfg(feature = "server")]
#[allow(clippy::too_many_arguments)]
pub fn from_continuation(
config: &ModelConfig,
handle: RequestHandle,
prompt: &crate::server::Prompt,
initial_prompt_tokens: usize,
ignore_eos: bool,
grammar_constrained: bool,
grammar_mask_active: bool,
grammar_enabled: bool,
) -> Result<Self> {
let grammar = match prompt.grammar.as_ref() {
Some(grammar) if grammar_mask_active => AdmissionGrammar::Masked(grammar.mask().to_vec()),
Some(_) if grammar_enabled => AdmissionGrammar::UnmaskedEnabled,
_ => AdmissionGrammar::Disabled,
};
let admission = Self {
handle,
sampling: prompt.sampling.clone(),
core_parameters: prompt.core_parameters.clone(),
max_new_tokens: prompt.max_new_tokens,
prompt: prompt.tokens.clone(),
data: prompt.data.clone(),
grammar_mask: grammar_constrained
.then(|| prompt.grammar.as_ref().map(|grammar| grammar.mask().to_vec()))
.flatten(),
grammar,
ignore_eos,
prompt_logprobs: prompt.prompt_logprobs,
};
Expand Down
2 changes: 1 addition & 1 deletion helios/src/model/packed_round_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ fn packed_combined_packing_preserves_sparse_slot_keys_and_ceiling_padding() {
admissions[h.slot as usize] = Some(Admission { prompt_logprobs: false, handle: h,
sampling: SamplingParameters::default(), core_parameters: Default::default(),
max_new_tokens: 64, prompt, data: PromptData { positions: (0..64).map(|i| [i; 3]).collect(),
vision_token_indices: vec![-1; 64], ..Default::default() }, grammar_mask: None, ignore_eos: true });
vision_token_indices: vec![-1; 64], ..Default::default() }, grammar: AdmissionGrammar::Disabled, ignore_eos: true });
handles.push(h);
}
scheduler.cancel(handles[1]).unwrap();admissions[handles[1].slot as usize] = None;
Expand Down
Loading
Loading