Skip to content

Allow speculative reasoning for grammar-constrained requests - #626

Merged
lukealonso merged 1 commit into
mainfrom
speculative-grammar-reasoning
Nov 30, 2026
Merged

lukealonso merged 1 commit into
mainfrom
speculative-grammar-reasoning

Conversation

@lukealonso

Copy link
Copy Markdown
Collaborator

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

  • Unmasked host token validation and deferred mask computation (helios/src/grammar.rs):
    • Added RequestGrammar::try_advance_unmasked(token) to validate and consume one token via llguidance::Matcher::try_consume_tokens without running compute_mask_or_eos(). Forbidden tokens (such as premature EOS, padded out-of-vocabulary model IDs, or invalid merged boundary tokens) return Ok(false) without mutating or poisoning parser state.
    • Added RequestGrammar::sync_mask() to recompute the vocabulary bitmask only when transitioning into device-constrained decoding or checking a forced thinking_token_budget close token.
  • Reasoning-envelope eligibility and device admission (helios/src/server/request.rs, helios/src/model/admission.rs):
    • Added Prompt::grammar_reasoning, populated in prepare_inference when a request has a grammar and either starts inside an open reasoning region (OutputStart::Reasoning) or uses a recipient/content-header envelope (Atem or TmlJson at RecipientHeader or RecipientFrame). Requests starting in OutputStart::Content, OutputStart::ToolBody, or raw Completions remain device-constrained from token 0.
    • Replaced unconditional mask upload in Admission::from_prompt with an explicit grammar_constrained flag so requests in speculative reasoning upload GrammarEnabled = 0 (grammar_mask: None), reusing the cached unconstrained mask row and avoiding per-step mask uploads.
  • Worker speculative-reasoning execution and boundary rollback (helios/src/server/runtime.rs):
    • Before this change, Incoming::spec() always set grammar_constrained = prompt.grammar.is_some(), and Worker::complete() ran grammar.advance() and updated Admission::grammar_mask on every token.
    • Now, while Incoming::speculative_grammar_reasoning() is active, Incoming::spec() sets grammar_constrained = false so the scheduler selects full speculative widths and pipelines up to two frames concurrently.
    • On completion, Worker::complete() validates each accepted burst token in order with try_advance_unmasked before 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, and generated_tokens), syncs the exact boundary grammar mask, cancels the live slot via RequestScheduler::cancel (draining any queued second frame without emitting output or publishing a terminal snapshot), and parks the truncated prefix via park_grammar_transition with device grammar enforcement enabled (grammar_reasoning_mode = Some(false)). On readmission, Helios restores the longest cached prefix checkpoint (GraphKind::Restore) and runs GraphKind::Prefill over the remaining reasoning suffix to rebuild exact KV and recurrent state before width-1 device-masked decoding begins.
    • For Atem and TmlJson envelopes starting in a constrained header, a rising edge into reasoning_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.
    • Integrated with thinking_token_budget (merging cut.after into remaining on 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).
  • Documentation (docs/mtp-design.md, docs/core-design.md, docs/api.md):
    • Updated the grammar-constrained decoding and speculative-execution sections to document host-validated speculative reasoning and boundary transition behavior.

No GPU graphs, kernel ABI bindings, or Protobuf schemas changed; existing exported model cores work without re-export.

Claimed Benefit

  • Expected performance improvement (not yet measured on a live GPU): Grammar-constrained requests with open reasoning are expected to decode their reasoning phase at full speculative widths and two-frame executor pipelining without per-step CPU mask generation or H2D mask uploads, and without forcing concurrent unconstrained requests in the same batch down to one step in flight.
  • Transition cost and limitations: Leaving speculative reasoning incurs one slot transition (cancel + Restore from the pinned prompt/prefix checkpoint + chunked Prefill over 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

  • Unit and runtime phase tests (helios/src/grammar.rs, helios/src/server/runtime/phase_tests.rs):
    • unmasked_advancement_matches_masked_decisions_and_defers_mask_sync: verifies try_advance_unmasked + sync_mask matches step-by-step advance across 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: verifies grammar_constrained == false and grammar_mask == None during 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-checkpoint Restore reuse on readmission, and width-1 requires_feedback constrained 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 (merging cut.after and 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: verifies OutputStart::Content stays constrained from token 0 and preemption mid-reasoning preserves speculative mode.
    • content_header_envelope_enters_speculative_reasoning_after_header_and_returns_to_constrained: verifies TmlJson starts constrained at RecipientHeader, 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_envelopes and updated reasoning_budget_does_not_inject_a_close_inside_a_tool_call: verify prepare_inference eligibility and tool_ends_reasoning transition at <tool_call>.
  • Full Rust test suites (Linux release builds):
    • 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 of hub::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.
  • Formal lifecycle verification:
    • 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.
  • Unrun checks:
    • Live CUDA serving and throughput benchmarks on exported model cores (not run in this environment; performance claims above are expectations, not measured GPU numbers).
    • cargo-kani sequential validator proofs (cargo-kani not installed on this host).
    • Checkpoint-dependent tokenizer integration tests (83 ignored in helios).

Discord: lukealonso

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>
@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 626.
Case File Intake Report

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@flare-autobot flare-autobot added area:scheduling Request scheduling, fairness, batching, and speculative-width selection. enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 30, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

Core mechanism is well-architected and cleanly placed in Helios, but head f7907a2 has an unexplained CI failure and no live served-workload GPU benchmark evidence to verify that speculative reasoning gains outweigh the O(R) boundary re-prefill and window-drain cost.

  • Blockers: 1 · Should fix: 3 · Subtract/Simplify: 4 · Nits: 1
Walkthrough
  • helios/src/grammar.rs (+156/−0): Adds mask_dirty, RequestGrammar::try_advance_unmasked(token) (host-side validation via llguidance::Matcher::try_consume_tokens without calling compute_mask_or_eos()) and RequestGrammar::sync_mask() to recompute the bitmask lazily at transition/budget boundaries, plus unmasked_advancement_matches_masked_decisions_and_defers_mask_sync.
  • helios/src/server/request.rs (+20/−0) & helios/src/model/admission.rs (+4/−4): Populates Prompt::grammar_reasoning in prepare_inference for eligible OutputStart::Reasoning and recipient-envelope (RecipientHeader/RecipientFrame) grammar requests, and gates Admission::grammar_mask on an explicit grammar_constrained: bool so speculative-reasoning admissions emit GrammarEnabled = 0.
  • helios/src/server/runtime.rs (+327/−19): Sets RequestSpec::grammar_constrained = false while Incoming::speculative_grammar_reasoning() is active, builds Active.reasoning for eligible grammar requests, validates burst tokens in order in Worker::complete(), suppresses trailing overshoot on reasoning close or forbidden token, syncs the deferred mask, and cancels/parks the truncated prefix via park_grammar_transition / park_with_tokens. Adds Atem/TmlJson re-entry (allow_reasoning_reentry), thinking_token_budget integration (let_publish_cut, cut.after merge, pre-check sync_mask()), and preemption mode preservation.
  • helios/src/server/runtime/phase_tests.rs (+863/−4) & prompt_tests.rs (+1/−1): Adds 6 isolated worker-phase unit tests covering pipelined reasoning + overshoot truncation, premature-EOS rollback (mid-burst and token 0), thinking-budget + logprobs, preemption & OutputStart::Content, TmlJson header re-entry, and prepare_inference eligibility; updates reasoning_budget_does_not_inject_a_close_inside_a_tool_call for tool_ends_reasoning.
  • docs/api.md, docs/core-design.md, docs/mtp-design.md: Updates grammar-constrained decoding and speculative-execution sections for host-validated speculative reasoning and boundary transition behavior.
Merge Risk: Medium · up to f7907a2
  • Hot-path request lifecycle change: Every grammar-constrained request starting in open reasoning (OutputStart::Reasoning) or recipient/content headers (Atem, TmlJson) now automatically executes speculative decode with two frames in flight and transitions via cancel + Restore + Prefill at the reasoning boundary (helios/src/server/runtime.rs:253-286, 1898-2165). There is no opt-out flag if a workload regresses.
  • Unmeasured transition & bystander cost: Every boundary transition re-prefills R reasoning tokens since the prompt-end checkpoint (runtime.rs:2407-2449), and GraphKind::Prefill drains the two-frame executor window (helios/src/scheduler.rs:1085-1094), momentarily revoking pipelining for co-batched unconstrained requests. Multi-block reasoning in Atem/TmlJson pays this transition on each block.
  • Unverified GPU / cache-scheme coverage: All new tests exercise CPU fixture graphs in --release; 83 checkpoint/GPU-gated tests and live serving on real recurrent/hybrid/KV cache schemes have not been run yet.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:scheduling Request scheduling, fairness, batching, and speculative-width selection. enhancement New feature or request performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants