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
12 changes: 8 additions & 4 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -645,10 +645,14 @@ 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. For as long as the
request decodes, its MTP width is one and any decode batch containing it keeps
one step in flight rather than two. This also applies when `tool_choice: "auto"`
produces only prose. 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 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).
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
16 changes: 11 additions & 5 deletions docs/core-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -1694,11 +1694,17 @@ reasoning and tool delimiters. An answer grammar constrains the answer, not
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 is active for
the entire generation: reasoning, prose, and tool calls. Until that request
finishes decoding, its MTP width is one and the [native replay loop](#native-replay-loop)
keeps one step in flight for any decode batch containing it. These constraints
do not begin or end at a tool delimiter.
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
[native replay loop](#native-replay-loop) keeps one step in flight for any
decode batch containing it.
`tool_choice=required` adds a prompt instruction and requires a completed call
to a declared tool. Without a grammar it uses ordinary sampling. Named tool
selection filters the definitions to that tool; it does not by itself enable a
Expand Down
17 changes: 15 additions & 2 deletions docs/mtp-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,13 +410,26 @@ frame index. A frame remains owned until its transfer and host consumption
finish. Ordinary decode uses the same two-frame completion contract.

MTP proposals are generated
on the device; grammar-constrained MTP requests use width one because the
on the device; grammar-constrained MTP requests use width one while device
grammar masks are active because the
runtime does not provide valid masks for those device-generated conditional
prefixes. One grammar mask reused across draft positions is invalid.
Grammar-constrained rounds require a step-level feedback barrier
Device-constrained rounds require a step-level feedback barrier
across the executor window until the native grammar state and uploaded masks
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.

Host-evaluated custom stops (stop strings and stop token sequences) participate
in multi-token speculative rounds and two-frame executor pipelining without a
feedback barrier. On completion, the runtime inspects each accepted burst in
Expand Down
156 changes: 156 additions & 0 deletions helios/src/grammar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ impl GrammarCompiler {
eos_ids: self.eos_ids.clone(),
accepting: false,
stopped: false,
mask_dirty: false,
error: None,
};
request.refresh_mask()?;
Expand Down Expand Up @@ -665,17 +666,27 @@ pub struct RequestGrammar {
eos_ids: Arc<[u32]>,
accepting: bool,
stopped: bool,
/// True after `try_advance_unmasked` consumed a token without recomputing `mask`.
mask_dirty: bool,
error: Option<Error>,
}

impl RequestGrammar {
/// Int32 words with token t stored in bit (t % 32) of word (t / 32).
/// Padded model IDs and the mask of a stopped or failed parser are zero.
pub fn mask(&self) -> &[i32] {
debug_assert!(
!self.mask_dirty,
"sync_mask must run before reading a deferred grammar mask"
);
&self.mask
}

pub fn allows(&self, token: u32) -> bool {
debug_assert!(
!self.mask_dirty,
"sync_mask must run before querying a deferred grammar mask"
);
(token as usize) < self.tokenizer_vocab
&& self.mask[token as usize / 32] as u32 & (1 << (token % 32)) != 0
}
Expand All @@ -689,6 +700,78 @@ impl RequestGrammar {
self.stopped
}

/// Recomputes the vocabulary mask when `try_advance_unmasked` deferred it.
pub fn sync_mask(&mut self) -> Result<()> {
if let Some(error) = &self.error {
return Err(error.clone());
}
if !self.mask_dirty || self.stopped {
return Ok(());
}
self.mask_dirty = false;
self.refresh_mask()
}

/// Validates and consumes a token generated without device mask enforcement.
/// Returns `Ok(false)` without modifying parser state when the token is
/// forbidden; defers full vocabulary mask computation until `sync_mask`.
pub fn try_advance_unmasked(&mut self, token: u32) -> Result<bool> {
if let Some(error) = &self.error {
return Err(error.clone());
}
if self.stopped || (token as usize) >= self.tokenizer_vocab {
return Ok(false);
}
if self.eos_ids.contains(&token) {
let accepting = match self.matcher.is_accepting() {
Ok(value) => value,
Err(error) => {
return self.fail(Error::Admission(AdmissionError::Grammar(Failure::boxed(
format!("grammar acceptance check failed: {error:#}"),
error.into_boxed_dyn_error(),
))));
}
};
if !accepting {
return Ok(false);
}
self.stopped = true;
self.accepting = true;
self.mask.fill(0);
self.mask_dirty = false;
return Ok(true);
}
let consumed = match self.matcher.try_consume_tokens(&[token]) {
Ok(consumed) => consumed,
Err(error) => {
return self.fail(Error::Admission(AdmissionError::Grammar(Failure::boxed(
format!("grammar advancement failed: {error:#}"),
error.into_boxed_dyn_error(),
))));
}
};
if consumed == 0 {
return Ok(false);
}
if !self.matcher.stop_reason().is_ok() {
return self.fail(Error::admission(
AdmissionError::Grammar,
format!("grammar stopped with {:?}", self.matcher.stop_reason()),
));
}
self.accepting = match self.matcher.is_accepting() {
Ok(value) => value,
Err(error) => {
return self.fail(Error::Admission(AdmissionError::Grammar(Failure::boxed(
format!("grammar acceptance check failed: {error:#}"),
error.into_boxed_dyn_error(),
))));
}
};
self.mask_dirty = true;
Ok(true)
}

pub fn advance(&mut self, token: u32) -> Result<()> {
if let Some(error) = &self.error {
return Err(error.clone());
Expand All @@ -699,6 +782,9 @@ impl RequestGrammar {
"grammar already consumed EOS",
));
}
if self.mask_dirty {
self.sync_mask()?;
}
if !self.allows(token) {
return self.fail(Error::admission(
AdmissionError::Grammar,
Expand All @@ -714,6 +800,7 @@ impl RequestGrammar {
}
self.stopped = true;
self.mask.fill(0);
self.mask_dirty = false;
return Ok(());
}
if let Err(error) = self.matcher.consume_token(token) {
Expand All @@ -737,6 +824,7 @@ impl RequestGrammar {

fn refresh_mask_available(&mut self) -> Result<bool> {
self.mask.fill(0);
self.mask_dirty = false;
if !self.matcher.stop_reason().is_ok() {
return self.fail(Error::admission(
AdmissionError::Grammar,
Expand Down Expand Up @@ -774,6 +862,7 @@ impl RequestGrammar {
fn fail<T>(&mut self, error: Error) -> Result<T> {
self.mask.fill(0);
self.accepting = false;
self.mask_dirty = false;
self.error = Some(error.clone());
Err(error)
}
Expand Down Expand Up @@ -1762,6 +1851,73 @@ pub(crate) mod tests {
}
}
}

#[test]
fn unmasked_advancement_matches_masked_decisions_and_defers_mask_sync() {
let mut tokenizer = byte_tokenizer();
tokenizer
.add_special_tokens([tokenizers::AddedToken::from("</think>", true)])
.unwrap();
let think_end = tokenizer.token_to_id("</think>").unwrap();
let tokenizer_vocab = tokenizer.get_vocab_size(true);
let model_vocab = tokenizer_vocab + 32;
let compiler =
GrammarCompiler::new(&tokenizer, model_vocab, &[256, 257], &[(think_end, "</think>".into())])
.unwrap();
let envelope = OutputEnvelope {
recipient: None,
reasoning_end: Some("</think>"),
tool: None,
function: None,
tool_ends_reasoning: false,
tool_body_start: false,
response: None,
message_close: None,
};
let schema = json!({"const": {"ok": true}});
let mut masked = compiler
.compile_json_schema_in(&schema, Some(&envelope))
.unwrap();
let mut unmasked = compiler
.compile_json_schema_in(&schema, Some(&envelope))
.unwrap();

// Reasoning tokens succeed without refreshing the mask.
for &byte in b"step 1" {
let token = u32::from(byte);
assert!(unmasked.try_advance_unmasked(token).unwrap());
masked.advance(token).unwrap();
assert_eq!(unmasked.is_accepting(), masked.is_accepting());
}
// Forbidden tokens (premature EOS and padded out-of-vocab ID) return Ok(false)
// without poisoning or mutating parser state.
assert!(!unmasked.try_advance_unmasked(256).unwrap());
assert!(!unmasked.try_advance_unmasked(257).unwrap());
assert!(!unmasked.try_advance_unmasked(tokenizer_vocab as u32).unwrap());
assert!(!unmasked.try_advance_unmasked((model_vocab - 1) as u32).unwrap());

// Closing reasoning stays valid; syncing the deferred mask reproduces the exact
// bitmask and accepting state of step-by-step masked advancement.
assert!(unmasked.try_advance_unmasked(think_end).unwrap());
masked.advance(think_end).unwrap();
unmasked.sync_mask().unwrap();
assert_eq!(unmasked.mask(), masked.mask());
assert_eq!(unmasked.is_accepting(), masked.is_accepting());

// Constrained continuation rejects invalid bytes and accepts the valid answer + EOS.
assert!(!unmasked.allows(u32::from(b'x')));
for &byte in br#"{"ok":true}"# {
let token = u32::from(byte);
unmasked.advance(token).unwrap();
masked.advance(token).unwrap();
assert_eq!(unmasked.mask(), masked.mask());
}
assert!(unmasked.is_accepting());
assert!(unmasked.try_advance_unmasked(256).unwrap());
masked.advance(256).unwrap();
assert!(unmasked.is_stopped());
assert!(!unmasked.try_advance_unmasked(u32::from(b'a')).unwrap());
}
}

#[cfg(all(test,feature="server"))]
Expand Down
8 changes: 4 additions & 4 deletions helios/src/model/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ impl Admission {
handle: RequestHandle,
prompt: &crate::server::Prompt,
ignore_eos: bool,
grammar_constrained: bool,
) -> Result<Self> {
let admission = Self {
handle,
Expand All @@ -119,10 +120,9 @@ impl Admission {
max_new_tokens: prompt.max_new_tokens,
prompt: prompt.tokens.clone(),
data: prompt.data.clone(),
grammar_mask: prompt
.grammar
.as_ref()
.map(|grammar| grammar.mask().to_vec()),
grammar_mask: grammar_constrained
.then(|| prompt.grammar.as_ref().map(|grammar| grammar.mask().to_vec()))
.flatten(),
ignore_eos,
prompt_logprobs: prompt.prompt_logprobs,
};
Expand Down
20 changes: 20 additions & 0 deletions helios/src/server/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,25 @@ pub(super) fn prepare_validated_inference(
if ignore_eos && grammar.is_some() {
return Err("structured output cannot ignore end-of-sequence tokens".into());
}
let grammar_reasoning = grammar
.is_some()
.then(|| {
output
.as_ref()
.filter(|out| {
out.content.start == crate::output::tagged::OutputStart::Reasoning
|| envelope.as_ref().is_some_and(|env| {
env.recipient.is_some()
&& matches!(
out.content.start,
crate::output::tagged::OutputStart::RecipientHeader
| crate::output::tagged::OutputStart::RecipientFrame
)
})
})
.cloned()
})
.flatten();
Ok(PreparedInference {
prompt: Prompt {
tokens,
Expand All @@ -419,6 +438,7 @@ pub(super) fn prepare_validated_inference(
stop_sequences,
stop_strings,
grammar,
grammar_reasoning,
ignore_eos,
logprobs: opts.logprobs.is_some(),
logprob_token_ids: opts
Expand Down
Loading
Loading