Skip to content

Report token log probabilities during speculative decoding - #774

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:speculative-log-probabilities
Nov 9, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:speculative-log-probabilities

Conversation

@aleroot

@aleroot aleroot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

ChatSession.observe (#714) reports token log probabilities, but it throws unsupportedSpeculativeDecoding when a drafter is active. An application that shows token probabilities, for example to inspect a reply, has to choose between that view and speculative decoding (#581). The choice isn't needed: the verify pass already scores every proposal with the main model, and each emitted token is sampled from its own row of those logits. The speculative iterators just discarded the rows.

Measurements

Apple M2, 16 GB. Qwen3.5-9B-4bit with Qwen3.5-9B-MTP-4bit (block size 3), greedy, 256 tokens, warm runs, top-5 values read on every token:

Log probabilities off Top-5 log probabilities
Plain decoding 18.67–19.26 tok/s 17.47–18.93 tok/s
MTP speculation (acceptance 0.854) 20.03–20.90 tok/s 20.33–20.67 tok/s

With a drafter, reporting no longer costs the speed-up. With reporting off, MTP measures the same as main (20.24–20.83 vs 20.45–21.01 tok/s).

The tokens are identical to plain decoding, and every token reports a value. Compared with one teacher-forced forward over the same sequence, the values differ by about as much as plain decoding's do:

|Δ chosen log probability| against teacher-forced mean p95 max
Plain decoding 0.0114 0.0565 0.1071
MTP speculation 0.0101 0.0528 0.1101

The remaining gap is 4-bit/bf16 kernel numerics between single-row and multi-row matmuls. In float32 the values match TokenIterator to 1e-4.

Checklist

Put an x in the boxes that apply.

  • 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:

Speculative iterators returned no log probabilities, so ChatSession threw
unsupportedSpeculativeDecoding when an observation requested them. The
verify pass already computes the main model's logits for every emitted
token; the iterators discarded them.

SpeculativeTokenIterator and MTPSpeculativeTokenIterator now record each
emitted token's values from the processed logits row it was sampled from,
the values TokenIterator reports. A round normalizes its emitted rows in
one batch after acceptance and evaluates the per-token views in the same
asyncEval, so reading them does not sync the GPU per token. Rejected
proposals report nothing, and nothing is computed when reporting is off.

The guard and ChatSession.ObservationError (added in ml-explore#714, unreleased)
are removed.
@aleroot

aleroot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski I had to adapt the log probabilities to the speculative decoding. It would be good to get this into the next release. ChatSession.ObservationError.unsupportedSpeculativeDecoding came in with #714. If the new release ships before this PR, the error type and the speculative-decoding throw become public API, and removing them later would be a breaking change. Merging this first means the release goes out with log probabilities working under speculative decoding and no error type that's already obsolete.

@aleroot aleroot mentioned this pull request Nov 7, 2026
27 tasks done

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Change looks good, thank you!

@davidkoski
davidkoski merged commit 6e3fe5d into ml-explore:main Nov 9, 2026
3 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 14, 2026
Apply the upstream commits 22bdf2c..6352907 (the 15 after c8dabc6) 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.

- 22bdf2c Decode surrogate pairs and the remaining Python escapes (ml-explore#769)
- 0877a36 Fix model weight loading progress (ml-explore#551)
- 0dabaf7 Add production-ready LFM2.5 model support (ml-explore#528)
- 173c163 Add mid-turn steering to ChatSession (ml-explore#608)
- 37424a5 Stop image prompts from running VLM language models in float32 (ml-explore#766)
- c48e55e Add LiquidAI LFM3 model support (ml-explore#750)
- 4ab2679 MLXVLM Qwen35: apply YaRN from rope_parameters on the VLM rotary (ml-explore#761)
- 6e3fe5d Report token log probabilities during speculative decoding (ml-explore#774)
- ec4c966 Batch greedy MTP verification into one GPU readback per round (ml-explore#724)
- c9a9a3d Skip the checkpoint components a model does not have (ml-explore#711)
- a8429d0 Measure the memory of an EmbeddingGemma 2 embedding (ml-explore#787)
- 7b0e790 Parse triple-quoted strings in PythonLiteralParser (ml-explore#786)
- 4c91662 Fix the flaky usage test on the tool-calling path (ml-explore#784)
- d7b94ee Add ModelTypeRegistry.contains(_:configuration:) for shared model types (ml-explore#778)
- 6352907 Use MLXLogger for the model component warning (ml-explore#790)

Conflict resolutions:
- ml-explore#551 load progress: `LoadProgressHandlers` and `progress:` are threaded
  through the fork's async `loadWeights`/`installWeights`. The
  progress-aware `MLXLanguageModel.init(...progress:load:)` and the
  `#huggingFaceLanguageModel` macro also take the fork's
  `speculativeDecoding:`. The fork's tests and benchmark helpers move off the
  now-deprecated download-only loader.
- ml-explore#528 LFM2.5: `RewindableConvolutionCache` lives in ArraysCache.swift
  without upstream's extra `offset +=`, because the fork's `advance` moves
  `offset`. Speculative rewind and verify checks trim it like attention, and
  do not select a Mamba snapshot slot for it. It is also
  `PromptCacheRestorable`, so a saved LFM2 prompt cache restores into the
  model's template. `mtpTargetLayerIdsKey` is added to the fork's MTP
  exchange. `shouldSortExpertRoutes` drives the fork's shared switch
  projection. The fork's in-place verify (`verifiesInPlace`) and its
  greedy-only passthrough string are kept. The upstream tests that expect a
  wrapped sliding window to refuse rewind now expect the fork's behavior:
  the window rewinds the verify write and keeps speculating.
- ml-explore#608 steering: the steering boundary goes into the fork's
  `GenerationLoop.runTokenLoop`, and `Generation.steering` and
  `GenerateStopReason.steered` go into GenerationResults.swift. The fork's
  generation worker keeps its own stream synchronization.
- ml-explore#750 LFM3 is added to HybridRecurrentCacheOffsetTests.
- ml-explore#711: the new test awaits the fork's async `loadWeights`.

Dropped:
- ml-explore#774 (speculative log probabilities): the fork's MTP iterator already
  reports log probabilities by decoding plainly when they are requested.
  Upstream's batched recording in the draft-model iterator does not fit the
  fork's `sampleToken` path, so `ChatSession.ObservationError` stays for
  draft-model speculation.
- ml-explore#724 (batched greedy MTP verification): the fork already batches its
  greedy verify (`verifyDrafts`, MTPGreedyVerificationTests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 21, 2026
Apply the upstream commits dbee7be..cb59e9a (the 18 after 6352907) 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.

- dbee7be Serialize integration tests and their model loading. (ml-explore#760)
- 7dde329 GLM-OCR: count the temporal patch in the pixel budget (ml-explore#783)
- f0d6150 fix: render null tool-call arguments in chat history (ml-explore#780)
- c6c6556 Base Gemma diffusion implementation (ml-explore#352)
- 5ecb13b Add LiquidAI LFM3 text support with extended validation and regression tests (ml-explore#756)
- 7e2c90f Match the DeepSeek-V3 MoE gate to mlx-lm (ml-explore#795)
- 700d8e2 Read r/u prefixes and adjacent string literals in PythonLiteralParser (ml-explore#799)
- c75b537 Keep the DeepSeek-V3 MoE output in the activation dtype (ml-explore#793)
- bc4746e Fix GLM-OCR small images; match smart_resize rounding in QwenVL.targetSize (ml-explore#764)
- b55217c Keep Qwen2-VL vision attention inside each image (ml-explore#755)
- dcfcf79 steering follow up and chat interrupt API (ml-explore#798)
- e589f33 Load Hadamard-rotated ternary checkpoints (prism_hadamard_qwen35) (ml-explore#630)
- cb2bd77 GPT-OSS: clip the SwiGLU with plain Float bounds (ml-explore#792)
- bf5a5d4 Declare measured budget transitions for Muse Glimmer and Qwen3.5 (ml-explore#734)
- 7517abc Let guided generation use the caller's sampler and logit processor (ml-explore#733)
- 5a14024 Refuse LoRA/DoRA on layers the adapters cannot reproduce (ml-explore#800) (ml-explore#803)
- ca661dc Size five float32 test comparisons for TF32 matmuls (ml-explore#802)
- cb59e9a Batching: Apply a per-row mask to each row of Gemma 2's grouped-query scores (ml-explore#772)

Conflict resolutions:
- ml-explore#760: the fork's MTPGreedyVerificationIntegrationTests keeps its fixture
  and moves under ModelLoadingSuite; the fixture loads the target and the
  drafter as one TestModelManager entry. The fork-only MiniMax M3 suites
  drop their private `models` for the shared one. .gitignore keeps both.
- ml-explore#352 diffusion: the edits to the monolithic Evaluate.swift and KVCache.swift
  go into the fork's split files (GenerateParameters, TokenIterators,
  GenerateTokens, GenerationLoop; KVCacheSimple/Chunked, RotatingKVCache,
  QuantizedKVCache). MTPSpeculation.makeTokenIterator builds the
  BlockDiffusionTokenIterator for a diffusion model, and throws
  unsupportedSpeculativeDecoding when a speculation is asked for, so every
  package path (FM executor, recording generate) takes it. ChatSession takes
  the diffusion branch before the fork's MTP eligibility check, with the
  pass's prompt token count; it takes no prompt-end checkpoint. The
  blockDiffusion guard is in the fork's shared private MTP init.
  TurboQuantKVCache saves the head width as a sixth meta-state value; the
  fork's strict prompt-cache validation accepts 5 (old files) or 6 values.
  The upstream KVCacheTests additions go into KVCacheTests and
  KVCacheQuantizationTests; MockMainModel (MLXLMTestSupport) gets
  `capabilities:`. New tests await the fork's async loadWeights.
- ml-explore#756 LFM3: model.validate(tokenizer:) runs before the fork's closed-
  reasoning end guard. The upstream LFM3CheckpointTests await loadWeights.
- ml-explore#755: the doc edit goes into the fork's PromptCacheFile.swift.
- ml-explore#798 interrupt: `.interrupted` and the steering boundary go into the fork's
  GenerationLoop and GenerationResults; TokenLoopHandler keeps
  emitOrCancel with `hasOutput`. Both reasoning-history tests are kept.
- ml-explore#734: the fork's QwenReasoningProtocol.qwen35 (history replay, closed
  thinking-off block) also declares the `.immediate` budget transition;
  upstream's second `qwen35` is folded into it. The family-delta test
  resets the fork's replay and prompt-strategy fields too.
- ml-explore#733: ported into the fork's GuidedDecoder/GuidedGenerationLoop split. A
  caller processor or sampler decodes plainly: guided MTP speculation stays
  greedy-only, so its output stays that of plain greedy decoding.
- ml-explore#802: the speculative log-probability test stays out (ml-explore#774 was dropped).

After the merge (CLAUDE.md):
- No manual `offset +=` after `advance(` in the merged models.
- HybridRecurrentCacheOffsetTests adds prism_hadamard_qwen35 (LLM and VLM
  classes), whose Qwen 3.5 caches include MambaCache.
- LFM3ReferenceTests.testLongContextChunking (gated by
  MLX_LFM3_LONG_CONTEXT) moves ungated to IntegrationTesting as
  LFM3LongContextProfileTests. The env-gated upstream IntegrationTesting
  suites LFM3CheckpointTests and LFM3TokenizerIntegrationTests stay gated.

Tests: MLXLMTests 1227 XCTest and 2459 Swift Testing (3 known issues),
MLXGuidedGenerationTests 85, MLXFoundationModelsTests 537, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 11 pass. Release, IntegrationTesting:
Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests,
PromptCacheSpoolCostAssessmentTests and LFM3LongContextProfileTests pass.

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.

2 participants