Skip to content

feat(mtp): MTP self-speculative decoding scaffolding (variants A + B) - #190

Draft
ekryski wants to merge 1 commit into
alphafrom
ek/mtp-bootstrap
Draft

ekryski wants to merge 1 commit into
alphafrom
ek/mtp-bootstrap

Conversation

@ekryski

@ekryski ekryski commented May 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

Spec 030 phase 1a — multi-token prediction (MTP) self-speculative decoding scaffolding for both variants:

  • Variant A (in-trunk MTP heads, DeepSeek-style): MTPInjector protocol + MTPSelfSpeculativeTokenIterator (greedy mode) + auto-routing in MLXLMCommon.generate(...). Reference: youssofal/MTPLX.
  • Variant B (companion EAGLE-style assistant draft, Google's "MTP" branding for Gemma 4): AssistantDraftRegistry mapping target HF id → assistant draft id + recommended numDraftTokens. Caller wires the resolved draft into the existing SpeculativeTokenIterator.

Phase 1a deliberately stops short of the per-model MTPInjector conformance. The DeepseekV4MTP head implementation needs validation against a running model + MTPLX reference outputs before we can ship it confidently — that's a focused follow-up where the architecture choices (concat order, hidden-variant norm, eh_proj shape) can be measured rather than guessed. The scaffolding here is the substantial work; conformance is comparatively small once you have a model in hand.

What ships in this PR

File Purpose
Libraries/MLXLMCommon/MTPInjector.swift Protocol surface + MTPContract (per-family hiddenVariant / concatOrder / maxHeads / family) + MTPLoader (key-prefix probing + env-gate helpers).
Libraries/MLXLMCommon/MTPSelfSpeculativeDecoding.swift MTPSelfSpeculativeTokenIterator — greedy AR + MTP-draft + batched-verify + accept/trim cycle. Standard TokenIteratorProtocol surface; reports specDecodeProposed / specDecodeAccepted like the existing iterators. mtpRouteDecision for auto-routing eligibility.
Libraries/MLXLMCommon/AssistantDraftRegistry.swift Hard-coded Gemma-4 *-it-assistant-bf16 mappings. Prefix-match + org-strip resolver for local bundles.
Libraries/MLXLMCommon/Evaluate.swift GenerateParameters.{mtpEnabled, mtpDraftCount, mtpAssistantDraftId} (default off). Variant-A auto-routing block in the standard generate(...) — engages before n-gram when a conforming model is present.
Libraries/MLXLLM/Models/DeepseekV4.swift Sanitize gate: with MLX_MTP_ENABLED=1, the mtp.* and layer-N MTP keys are now PRESERVED through sanitize(weights:). Default behaviour unchanged.
Tests/MLXLMTests/MTPTests.swift 18 unit tests — route decision, registry resolution (E2B / E4B / 26B-A4B / 31B + org-strip + miss), key-prefix probing, parameter threading, contract value-type.

Auto-routing precedence

Spec 030 + 015 ordering — MTP takes precedence over n-gram (trained-head proposals carry a higher acceptance ceiling):

if dflash-eligible        → DFlashSpeculativeTokenIterator   (spec 015 — not yet)
elif mtp-A-eligible       → MTPSelfSpeculativeTokenIterator  (THIS PR)
elif ngram-eligible       → NGramSpeculativeTokenIterator    (existing)
else                      → TokenIterator

Variant A engages only when (1) the model conforms to MTPInjector, (2) isMTPLoaded is true, (3) the trunk cache is fully trimmable, and (4) temperature == 0. Failed inits fall through cleanly.

Variant B doesn't ride the same auto-routing because MLXLMCommon.generate(...) doesn't have access to a downloader — the caller resolves via AssistantDraftRegistry explicitly, then passes the loaded draft to the speculative generate(...) overload.

How to use

Variant A (once a model conforms)

var params = GenerateParameters(temperature: 0.0)
params.mtpEnabled = true
params.mtpDraftCount = 1   // or via MLX_MTP_ENABLED=1
let stream = try generate(input: input, parameters: params, context: context)

Variant B (Gemma 4 assistant — works today)

let entry = AssistantDraftRegistry.resolve(targetId: targetContext.configuration.name)!
let draftCtx = try await loadModelContainer(/* draftId from entry */)
let stream = try generate(
    input: input, parameters: params, context: targetContext,
    draftModel: draftCtx.model, numDraftTokens: entry.recommendedNumDraftTokens)

On the MTP-head pruning question

The DeepSeek-V4 sanitize gate is the load-bearing change for variant A. The mlx-community/DeepSeek-V4-Flash-2bit-DQ bundle ships the MTP layer at model.layers.{numHiddenLayers}.* — our sanitize had been actively dropping it. With MLX_MTP_ENABLED=1 the layer is now preserved through load, ready to bind to a future DeepseekV4MTP module.

For Qwen 3.5/3.6 the same sanitize-gate pattern needs replication (and is blocked on spec 020 tape-replay before the iterator can engage on those hybrid GDN trunks). For Gemma 4, the original bundles don't ship in-trunk heads — variant B is the path there.

Test plan

  • swift build — library + tests target both compile clean
  • swift test --filter MTPTests — 18/18 pass
  • No regression in existing tests (ResolveTests etc. still pass)
  • Variant B integration on Gemma-4-26B-A4B once the bench harness wires AssistantDraftRegistry.resolve(...) (follow-up — can be slotted into the next bench-harness PR)
  • Variant A integration once a DeepseekV4MTP conformance lands (separate PR — needs running model for validation)

Follow-ups

  1. DeepseekV4MTP module — the actual head architecture (enorm, hnorm, eh_proj + reused DSV4 attention/MoE block). Validate against MTPLX Python reference token-by-token at temp 0 before merge.
  2. Custom converter (scripts/mtp_convert.py) — for in-trunk families where mlx-community bundles already pruned the heads (DeepSeek-V3 4-bit, MiMo).
  3. Stochastic accept/reject (spec 030 phase 3) — port the spec-023 sampler to share with MTP.
  4. Hybrid GDN conformance (Qwen 3.5/3.6/Qwen3-Next variant A) — gated on spec 020 phase 2/3.
  5. Bench harness --mtp flag — drive variant B on Gemma 4 from the existing sweep tooling.

@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 9, 2026
Spec 030 phase 1a — protocol surface, iterator, variant-B registry, and
DeepseekV4 sanitize-strip gating. No model conformance for variant A
yet (DeepseekV4MTP head deferred to a follow-up where it can be
validated against a running model + MTPLX reference outputs).

Adds:
  - `MTPInjector` protocol + `MTPContract` (per-family hidden_variant +
    concat_order) + `MTPLoader` (key-prefix probing, env gate).
  - `MTPSelfSpeculativeTokenIterator` (variant A) — greedy-only cycle
    of AR forward → MTP head draft → batched verify → accept/trim.
    Per-head KV caches, per-cycle accept/proposed metrics on the
    standard `TokenIteratorProtocol` surface.
  - `mtpRouteDecision` for auto-routing in
    `MLXLMCommon.generate(...)`. MTP takes precedence over n-gram when
    a model conforms to `MTPInjector` with heads loaded; init-failure
    falls through cleanly to the next route.
  - `AssistantDraftRegistry` (variant B) — Gemma-4
    `*-it-assistant-bf16` mappings (E2B / E4B / 26B-A4B / 31B). Caller
    resolves the entry, loads the draft via the existing factory, and
    constructs `SpeculativeTokenIterator` with the registered
    `recommendedNumDraftTokens` (6 single, 3 batched per the model
    card). Org-strip fallback for local bundles.
  - `GenerateParameters`: `mtpEnabled`, `mtpDraftCount`,
    `mtpAssistantDraftId`. Default off — opt in via Swift parameters
    or `MLX_MTP_ENABLED=1`.
  - `DeepseekV4.sanitize`: stops dropping `mtp.*` and the layer-N MTP
    keys when `MLXLoader.mtpLoadEnabledFromEnv` (driven by
    `MLX_MTP_ENABLED=1`). Default behaviour unchanged.

Tests: 18 unit tests in `Tests/MLXLMTests/MTPTests.swift` cover route
decision, registry resolution, key-prefix probing, parameter
threading, and contract value-type. All pass under `swift test`.

Variant A is end-to-end ready against any future `MTPInjector`
conformance. Variant B is end-to-end ready today — bench harness can
import the registry and resolve the draft explicitly.

DeepseekV4 conformance + Qwen 3.5/3.6/Qwen3-Next conformance follow
in subsequent PRs (the latter blocked on spec 020 tape-replay).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/mtp-bootstrap branch from 1753fae to f8c1a1e Compare May 9, 2026 19:20
@ekryski
ekryski marked this pull request as draft May 12, 2026 08:34
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
* fix(mimo): accept bounded PCM WAV audio at native sample rates

* fix(mimo): decode bounded AAC video audio at its source rate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant