Skip to content

Feed the sampled token before its fast-forward tokens - #731

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
quartzjer:guided-feed-sampled-token
Oct 30, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
quartzjer:guided-feed-sampled-token

Conversation

@quartzjer

@quartzjer quartzjer commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

When a sampled token is followed by fast-forward tokens, GuidedGenerationLoop.run feeds only the fast-forward tokens to the model. The sampled token is emitted and committed to the grammar, but never goes through a forward pass, so later logits condition on a sequence missing a token the output contains. The output stays grammatical, so nothing fails visibly.

This happens whenever fastForward: true and the grammar forces tokens right after a sampled one. JSON schemas do that at most structural boundaries. Both guided call sites in MLXFoundationModels pass fastForward: true, and so does the MLXGuidedGeneration README example. The loop came in with #334.

This PR feeds the sampled token before its fast-forward tokens, still one token per forward pass. The path with no fast-forward tokens and the early-stop paths are unchanged.

Tests

GuidedForwardStateTests.modelSeesEveryEmittedToken runs the loop on the CPU with a byte-level tokenizer, a small grammar and a stub model that records every token it is fed. On normal completion it checks that the fed sequence is the prompt followed by the output, with fast-forward on and off. With fast-forward on, it fails on main. The output is {"key":"A"}, but after the prompt the model is fed only "key":" and "}. It never sees the sampled { or A.

I also ran the guided-generation and tool-calling integration suites (107 tests) on macOS 27, on main and with this PR, #733 and #732 applied together. Every failure with the PRs also occurs on main except one: allowedCanChooseARealTool failed in 2 of 5 runs with the PRs. It is in the .allowed tool-calling path, which doesn't use the guided loop, and it fails the same way as the .allowed tests that fail intermittently on both: the model writes {{ in its tool call. requiredCannotAnswerWithoutCallingARealTool and the gemma-3-270m case of intRoundTrip fail on both.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes.
  • AI usage disclosure: I used Claude (Anthropic) to draft the code, tests and description, and Claude and ChatGPT (OpenAI) to review them. I have read every line, can explain it, and ran the tests.

When xgrammar returned fast-forward tokens after a sampled token, the
guided loop fed only the fast-forward tokens to the model, so later
logits conditioned on a sequence missing the sampled token. Feed the
sampled token first, still one token per forward pass.
@ctymoszek

Copy link
Copy Markdown
Collaborator

This looks good, thanks!

One small request: GuidedForwardStateTests.swift imports MLXNN (for Module), but the MLXGuidedGenerationTests target doesn't declare it in Package.swift. It builds today because MLXNN comes in transitively through MLXLMCommon, but it would be better to make it explicit.

Could you add .product(name: "MLXNN", package: "mlx-swift") to the target's dependencies?

@quartzjer

Copy link
Copy Markdown
Contributor Author

thanks! added MLXNN to the MLXGuidedGenerationTests dependencies.

@ctymoszek ctymoszek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thank you!

@davidkoski
davidkoski merged commit 411d8e7 into ml-explore:main Oct 30, 2026
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 5, 2026
Apply the upstream commits efcedcd..c8dabc6 (the 25 after 991266a) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- efcedcd Gemma 4 VLM: expose hidden states for a prepared input (ml-explore#730)
- 3d066d3 mlx-swift 0.33.0 (ml-explore#720)
- 39b92df Read Gemma 3 RoPE scaling from rope_parameters (ml-explore#723)
- c358cea Throw when Bert id2label keys share an integer id (ml-explore#736)
- c3d3afe FastVLM: Keep image sentinels out of the repetition-penalty history (ml-explore#735)
- 72a4673 Fix attention masks sized from the absolute cache offset (ml-explore#728)
- cf9b7e9 Prefill over a quantized KV cache through the fused SDPA kernel (ml-explore#703)
- ef36109 Add reasoning streaming events and support Gemma 4 channels (ml-explore#563)
- 691a19a Support Nemotron 3.5 (Lightning, Bolt, Super) text models (ml-explore#712)
- f5b0677 Expose Qwen 3.5 text geometry read-only (ml-explore#737)
- c2f1073 Add GrammarConstraint.freshMatcher() (ml-explore#732)
- 411d8e7 Feed the sampled token before its fast-forward tokens (ml-explore#731)
- 71cc028 MLXFoundationModels: let MLXLanguageModel set the prefill step size (ml-explore#745)
- 52e6001 Report model tensor buffer memory (ml-explore#746)
- 128f49f Use the MLXFast gated delta kernel where mlx core supports it (ml-explore#740)
- 35bd2c9 Add MiniCPM5 Tool Call Parser (ml-explore#637)
- c611a3f integration tests to run using xcode 27 (now that it is released) (ml-explore#743)
- bb36fc3 EmbeddingGemma 2: soft tokens for every row of a batch (ml-explore#729)
- b8d4935 Show the response schema to the model during guided generation (ml-explore#715)
- 2775ddd RotatingKVCache: keep the pinned prefix visible in multi-token masks (ml-explore#747)
- eccf774 Fix EmbeddingGemma 2 image orientation and batch text embeddings (ml-explore#692)
- ffe7647 Add resumable Qwen MTP speculative decoding to ChatSession (ml-explore#581)
- 327d92d Put images before text in GLM-OCR prompts (ml-explore#765)
- 2fdad9e Keep Nemotron-H Mamba activations in the input dtype (ml-explore#754)
- c8dabc6 Fix the x86_64 build of the EmbeddingGemma 2 image processor (ml-explore#763)

mlx-swift 0.33.0 (MLX core 0.32.4 line):
- MultiRowQuantizedMatvec: widen each input before the 4-bit pack sum, as
  qmv_fast now does, so verify rows keep the bits of a decode step.
- GatedDeltaDecodeKernel and the DeepSeek-V4 Sinkhorn kernel: the sigmoid
  reads metal::precise::exp, as MLX Sigmoid now does (mlx#4461).

Conflicts and choices:
- ml-explore#563: Generation.reasoning carries thinking apart from .chunk on every
  path (textToolHandler takes reasoningPrimedInside, read before the
  prefill). ChatSession records the content with the finished reasoning
  beside it, and prefilledReasoningStartDelimiter, as upstream does;
  ReasoningHistory keeps one fork rule: a protocol that replays reasoning
  also replays a turn cut off inside it, so the next render extends the
  cache. Upstream's Qwen3VL generator replaces separatingImportedReasoning;
  the fork's whole-text helpers (separating, staysInsidePrimedReasoning,
  the duplicate prompt probe) are gone. FM ports the thinking gate fix,
  routed reasoning on allowed-tool turns, and ReasoningTokenCollector.
  Benchmark transcripts count .reasoning.
- ml-explore#581: the fork already holds the port of the PR and the MTP work on it.
  The later transcript rebuild after a target-only turn is not taken: the
  fork cold-starts the drafter at the cached position and keeps the target
  cache. Recorded as an empty pick.
- ml-explore#740: MLXFast gated delta for prefill and fallbacks; decode and MTP
  verify keep the fork kernels.
- ml-explore#745: same public API; the executor reads the step size from a
  task-local, as drainCoordinator, and makeParameters defaults to it.
- ml-explore#715: the schema prompt is built after the fork's history replay. A
  session that changes schema between turns changes its system prompt.
- ml-explore#703: quantizedCacheAttention carries the fork's attention sinks.
- ml-explore#728, ml-explore#747, ml-explore#731, ml-explore#735: applied to the split files; ml-explore#747 and ml-explore#731 were
  already fixed in the fork.
- ml-explore#732: the fork's xgrammar v0.1.34 keeps Fork(); the clone tests stay on.

Tests: MLXLMTests 964 XCTest and 2278 Swift Testing tests pass.
MLXGuidedGenerationTests 76, MLXFoundationModelsTests 493, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 7 pass. HybridRecurrentCacheOffsetTests pass;
nemotron_h_puzzle reuses NemotronHModel. Release, M5 Ultra:
Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests,
PromptCacheSpoolCostAssessmentTests, qwen38FourBitMTPGeneration and
qwen38FourBitMTPSystemPromptCache pass (each run alone). Default MTP
math/code ~94-100 / 85 tok/s against plain ~57; edit turn reuses 2169 and
prefills 123.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants