Repository navigation
Allow speculative reasoning for grammar-constrained requests - #626
Merged
Merged
Conversation
Run grammar-constrained requests without device grammar masks while generation is inside an open reasoning region declared by the output envelope, keeping multi-token speculation and two-frame executor pipelining active and deferring full-vocabulary mask computation during reasoning. On completion, validate each emitted token on the host via RequestGrammar::try_advance_unmasked before observing or emitting it. When reasoning closes or a token is rejected by the grammar (for example premature EOS or a merged boundary token), suppress trailing burst overshoot, sync the exact boundary vocabulary mask, cancel the live slot so any queued second frame drains without leaking output or publishing a terminal snapshot, and readmit the truncated prefix with device grammar enforcement enabled (reusing cached prompt checkpoints via Restore and rebuilding KV/recurrent state through Prefill). Recipient and content-header envelopes (Atem and TmlJson) also transition into speculative reasoning on a rising edge from a constrained header into an open reasoning frame and return to device-constrained decoding on close. Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=2e5b Signed-off-by: Luke Alonso <lalonso@gmail.com>
Collaborator
|
A case file has been opened for 626. Future reviews will auto-run 90 minutes after code updates are pushed.
|
Collaborator
Autobot ReviewFull Review · Value Proposition · Case File Recommendation: Changes RequestedCore mechanism is well-architected and cleanly placed in Helios, but head
Walkthrough
Merge Risk: Medium · up to
|
This was referenced Nov 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
Grammar-constrained requests (JSON schemas, Lark grammars, and active strict function tools) previously ran with device grammar enforcement (
grammar_constrained = true,GrammarEnabled = 1) for their entire generation. Because device-generated speculative draft positions cannot share a single grammar mask, this forced every grammar-constrained request to decode at speculative width 1, imposed a step-level feedback barrier across the entire decode batch (preventing two-frame executor pipelining for concurrent unconstrained requests sharing the batch), and computed and uploaded a full-vocabulary bitmask on every generated token.For thinking models, most of the output is an open reasoning trace where the composed envelope grammar permits ordinary text and only constrains reasoning closure and post-reasoning structure. Running the reasoning phase without device grammar masks unlocks full speculative widths and two-frame pipelining without requiring per-model rollback kernels or core re-export, because Helios can validate reasoning tokens on the host and transition at the exact reasoning boundary through its existing slot-cancellation, checkpoint-restore, and chunked-prefill path (which reconstructs KV and non-invertible recurrent state across every supported cache scheme).
What Changed
helios/src/grammar.rs):RequestGrammar::try_advance_unmasked(token)to validate and consume one token viallguidance::Matcher::try_consume_tokenswithout runningcompute_mask_or_eos(). Forbidden tokens (such as premature EOS, padded out-of-vocabulary model IDs, or invalid merged boundary tokens) returnOk(false)without mutating or poisoning parser state.RequestGrammar::sync_mask()to recompute the vocabulary bitmask only when transitioning into device-constrained decoding or checking a forcedthinking_token_budgetclose token.helios/src/server/request.rs,helios/src/model/admission.rs):Prompt::grammar_reasoning, populated inprepare_inferencewhen a request has a grammar and either starts inside an open reasoning region (OutputStart::Reasoning) or uses a recipient/content-header envelope (AtemorTmlJsonatRecipientHeaderorRecipientFrame). Requests starting inOutputStart::Content,OutputStart::ToolBody, or raw Completions remain device-constrained from token 0.Admission::from_promptwith an explicitgrammar_constrainedflag so requests in speculative reasoning uploadGrammarEnabled = 0(grammar_mask: None), reusing the cached unconstrained mask row and avoiding per-step mask uploads.helios/src/server/runtime.rs):Incoming::spec()always setgrammar_constrained = prompt.grammar.is_some(), andWorker::complete()rangrammar.advance()and updatedAdmission::grammar_maskon every token.Incoming::speculative_grammar_reasoning()is active,Incoming::spec()setsgrammar_constrained = falseso the scheduler selects full speculative widths and pipelines up to two frames concurrently.Worker::complete()validates each accepted burst token in order withtry_advance_unmaskedbefore observing or emitting it. When reasoning closes (!reasoning.reasoning_open()) or a token is rejected by the grammar, the worker suppresses trailing overshoot tokens in that burst (omitting them from emitted events,ObservedToken, logprobs, andgenerated_tokens), syncs the exact boundary grammar mask, cancels the live slot viaRequestScheduler::cancel(draining any queued second frame without emitting output or publishing a terminal snapshot), and parks the truncated prefix viapark_grammar_transitionwith device grammar enforcement enabled (grammar_reasoning_mode = Some(false)). On readmission, Helios restores the longest cached prefix checkpoint (GraphKind::Restore) and runsGraphKind::Prefillover the remaining reasoning suffix to rebuild exact KV and recurrent state before width-1 device-masked decoding begins.AtemandTmlJsonenvelopes starting in a constrained header, a rising edge intoreasoning_open()transitions into speculative reasoning (when more than one token remains in output and context budgets) and transitions back to device-constrained decoding when reasoning closes.thinking_token_budget(mergingcut.afterintoremainingon natural early close, syncing the deferred mask before forced close injection, and transitioning to device-constrained mode on the continuation pass) and preemption (preserving the active reasoning mode across preemption readmission).docs/mtp-design.md,docs/core-design.md,docs/api.md):No GPU graphs, kernel ABI bindings, or Protobuf schemas changed; existing exported model cores work without re-export.
Claimed Benefit
cancel+Restorefrom the pinned prompt/prefix checkpoint + chunkedPrefillover the reasoning tokens since that checkpoint), plus at most one speculative burst and one queued frame of discarded overshoot. For empty or very short reasoning blocks (a few tokens), or if the prompt checkpoint was not cached on a very long prompt with minimal reasoning, transition overhead can match or exceed the speculative decode savings.Evidence
helios/src/grammar.rs,helios/src/server/runtime/phase_tests.rs):unmasked_advancement_matches_masked_decisions_and_defers_mask_sync: verifiestry_advance_unmasked+sync_maskmatches step-by-stepadvanceacross valid reasoning bytes, premature EOS, padded out-of-vocab IDs, reasoning close, exact post-close bitmask equality, and constrained JSON continuation.speculative_grammar_reasoning_runs_pipelined_and_transitions_on_close_with_overshoot: verifiesgrammar_constrained == falseandgrammar_mask == Noneduring reasoning, concurrent two-frame width-8 pipelining (!requires_feedback), mid-burst</think>close discarding invalid trailing overshoot tokens from emitted tokens/observations/generated_tokens, clean drain of the queued second frame without leaking output, prompt-checkpointRestorereuse on readmission, and width-1requires_feedbackconstrained continuation to EOS.speculative_grammar_reasoning_rolls_back_forbidden_token_including_premature_eos: verifies non-destructive rollback on premature EOS both mid-burst and on token 0 (emitted == 0), parking before the forbidden token and completing legally in device-constrained mode.speculative_grammar_reasoning_integrates_with_thinking_budget_and_logprobs: verifies both natural early close before budget (mergingcut.afterand suppressing overshoot logprobs) and budget-exhaustion forced close (syncing deferred mask, injecting</think>, and transitioning to constrained mode).speculative_grammar_reasoning_preserves_mode_on_preemption_and_stays_constrained_without_reasoning: verifiesOutputStart::Contentstays constrained from token 0 and preemption mid-reasoning preserves speculative mode.content_header_envelope_enters_speculative_reasoning_after_header_and_returns_to_constrained: verifiesTmlJsonstarts constrained atRecipientHeader, transitions to width-8 speculative reasoning on<|content_thinking|>, and rolls back overshoot on<|end_message|>into constrained decoding.prepare_inference_enables_speculative_grammar_reasoning_only_for_eligible_envelopesand updatedreasoning_budget_does_not_inject_a_close_inside_a_tool_call: verifyprepare_inferenceeligibility andtool_ends_reasoningtransition at<tool_call>.FLARE_TEST_TEMPLATE_DIR=/tmp/flare-test-templates-pr619 cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server --target-dir flare-cli/target: 1,806 passed, 0 failed, 83 ignored (checkpoint/GPU-gated tests).cargo test --locked --release --manifest-path flare/Cargo.toml --target-dir flare-cli/target -- --test-threads=1(plus isolated re-run ofhub::tests::legacy_unbound_source_ref_fails_offline_and_refreshes_online_without_dependencies, which hit a transient loopback connection reset on the full run): 237 passed, 0 failed, 4 ignored.cargo test --locked --release --manifest-path flare-cli/Cargo.toml: 211 passed, 0 failed.cargo test --locked --release --manifest-path heliopause/Cargo.toml --target-dir flare-cli/target: 216 passed, 0 failed, 6 ignored.python3 verification/helios-lifecycle/check.py --tlc-jar /home/luke/.cache/flare-formal/tla2tools-1.7.4.jar --target-dir flare-cli/target: all 8 TLA+ models (Lifecycle,RankProtocol,DispatchRing,OffloadTransfer,CacheOwnership,Speculation,ResponseLifecycle,CheckpointReservation) and their observed-edge Rust conformance suites passed.cargo-kanisequential validator proofs (cargo-kaninot installed on this host).helios).Discord: lukealonso