Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions Libraries/MLXLLM/Models/DeepseekV4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -894,21 +894,31 @@ public class DeepseekV4Model: Module, LLMModel, KVCacheDimensionProvider, LoRAMo
/// norm.weight → model.norm.weight
/// head.weight → lm_head.weight
/// ffn.experts.{E}.{w1|w2|w3}.* → mlp.switch_mlp.{gate|down|up}_proj.* (stacked)
///
/// **MTP gating.** When `MLXLoader.mtpLoadEnabledFromEnv` is true
/// (i.e. `MLX_MTP_ENABLED=1` is set at process start), the MTP layer
/// at index `numHiddenLayers` and any `mtp.*`-prefixed keys are
/// PRESERVED. Otherwise (the default path) they're dropped. Spec 030.
public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
// Minimal sanitize for the official mlx-community DSv4 safetensors
// layout. After matching @ModuleInfo names directly to file keys
// (attn/ffn/attn_norm/ffn_norm/switch_mlp/embed_tokens/norm),
// most weights pass through unchanged. We only need to:
// 1. Drop the multi-token-prediction (MTP) layer at index
// `numHiddenLayers` (one extra layer beyond the 43 we model).
// `numHiddenLayers` (one extra layer beyond the 43 we model)
// UNLESS `MLX_MTP_ENABLED=1` (spec 030 / `MTPLoader`).
// 2. Drop any rotary inv_freq buffers (computed at runtime).
// 3. Map official `model.hc_head.{base,fn,scale}` → bundle-style
// `hc_head_{base,fn,scale}` keys for the HyperHead's
// @ParameterInfo names.
let keepMTP = MTPLoader.mtpLoadEnabledFromEnv
let mtpLayerPrefix = "model.layers.\(self.config.numHiddenLayers)"
var out = weights.filter { (key, _) in
!key.hasPrefix("model.layers.\(self.config.numHiddenLayers)")
&& !key.contains("rotary_emb.inv_freq")
&& !key.hasPrefix("mtp.")
if key.contains("rotary_emb.inv_freq") { return false }
if keepMTP { return true }
if key.hasPrefix(mtpLayerPrefix) { return false }
if key.hasPrefix("mtp.") { return false }
return true
}
for src in ["base", "fn", "scale"] {
let from = "model.hc_head.\(src)"
Expand Down
112 changes: 112 additions & 0 deletions Libraries/MLXLMCommon/AssistantDraftRegistry.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright © 2026 ekryski.
//
// Multi-token prediction (MTP) — variant B: companion EAGLE-style
// "assistant" drafts. Maps a target HF id to an assistant-draft HF id
// so `MLXLMCommon.generate(...)` can auto-resolve the draft and route
// through the existing `SpeculativeTokenIterator`.
//
// Spec: specs/030-multi-token-prediction.md (variant B).
//
// Initial coverage: Google's gemma-4-*-it-assistant family. These are
// EAGLE-style standalone draft transformers (78M / 78.8M / 0.4B / 0.5B
// params) that share the target's tokenizer and (per the model card)
// produce byte-identical output at temperature 0 with --draft-block-size
// 6 single / 3 batched.

import Foundation

/// Mapping from a target HF id to the recommended assistant draft id +
/// recommended `numDraftTokens`. The match function is a longest-prefix
/// resolver: a target id like
/// `mlx-community/gemma-4-26B-A4B-it-bf16` matches the registry
/// entry for `mlx-community/gemma-4-26B-A4B-it`.
public enum AssistantDraftRegistry {

/// One mapping rule.
public struct Entry: Sendable {
/// Target HF id prefix. Matched against
/// `ModelConfiguration.name` via `hasPrefix`.
public let targetPrefix: String
/// Draft model HF id to load when the target matches.
public let draftId: String
/// Recommended `numDraftTokens`. Per the gemma-4 assistant
/// model card, 6 is best for single-batch decode; 3 for
/// batched. Mirrors HF Transformers' `--draft-block-size`.
public let recommendedNumDraftTokens: Int
/// Optional human-readable note printed in diagnostic logs.
public let note: String?

public init(
targetPrefix: String,
draftId: String,
recommendedNumDraftTokens: Int,
note: String? = nil
) {
self.targetPrefix = targetPrefix
self.draftId = draftId
self.recommendedNumDraftTokens = recommendedNumDraftTokens
self.note = note
}
}

/// Built-in registry. Listed longest-prefix-first so the matcher
/// picks the most specific entry.
public static let entries: [Entry] = [
// Gemma 4 assistants (Google's EAGLE-style drafts; mirrored to
// mlx-community).
Entry(
targetPrefix: "mlx-community/gemma-4-26B-A4B-it",
draftId: "mlx-community/gemma-4-26B-A4B-it-assistant-bf16",
recommendedNumDraftTokens: 6,
note: "Gemma-4 26B-A4B EAGLE-style assistant draft (~0.4B)"),
Entry(
targetPrefix: "mlx-community/gemma-4-31B-it",
draftId: "mlx-community/gemma-4-31B-it-assistant-bf16",
recommendedNumDraftTokens: 6,
note: "Gemma-4 31B EAGLE-style assistant draft (~0.5B)"),
Entry(
targetPrefix: "mlx-community/gemma-4-E2B-it",
draftId: "mlx-community/gemma-4-E2B-it-assistant-bf16",
recommendedNumDraftTokens: 6,
note: "Gemma-4 E2B EAGLE-style assistant draft (~78M)"),
Entry(
targetPrefix: "mlx-community/gemma-4-E4B-it",
draftId: "mlx-community/gemma-4-E4B-it-assistant-bf16",
recommendedNumDraftTokens: 6,
note: "Gemma-4 E4B EAGLE-style assistant draft (~78.8M)"),
]

/// Resolve an assistant draft for the given target HF id (or
/// `ModelConfiguration.name`). Returns `nil` if no entry matches.
///
/// Matching:
/// - Exact prefix match against `entries[i].targetPrefix`. The
/// entries list is searched in declared order; first match
/// wins. Order entries longest-prefix-first.
/// - Org-strip fallback: if no entry matches the full id, retry
/// after stripping a leading `<org>/` prefix. Lets local-only
/// bundles (e.g. `LocalDir/gemma-4-26B-A4B-it`) match the
/// `mlx-community/gemma-4-26B-A4B-it` rule.
public static func resolve(targetId: String) -> Entry? {
for entry in entries {
if targetId.hasPrefix(entry.targetPrefix) { return entry }
}
// Org-strip fallback.
if let slashIdx = targetId.firstIndex(of: "/") {
let stripped = String(targetId[targetId.index(after: slashIdx)...])
for entry in entries {
let entrySlashIdx = entry.targetPrefix.firstIndex(of: "/")
let entryStripped: String
if let entrySlashIdx {
entryStripped = String(
entry.targetPrefix[
entry.targetPrefix.index(after: entrySlashIdx)...])
} else {
entryStripped = entry.targetPrefix
}
if stripped.hasPrefix(entryStripped) { return entry }
}
}
return nil
}
}
76 changes: 76 additions & 0 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,38 @@ public struct GenerateParameters: Sendable {
/// `ngramSize, ngramSize-1, ..., 2` until it finds a match or runs out.
public var minNgramSize: Int

/// Multi-token prediction (MTP) opt-in. When true, models conforming
/// to ``MTPInjector`` with MTP heads loaded route through
/// ``MTPSelfSpeculativeTokenIterator`` (variant A — self-speculative,
/// in-trunk MTP heads); models matched by ``AssistantDraftRegistry``
/// route through the standard ``SpeculativeTokenIterator`` with the
/// registered companion draft (variant B — EAGLE-style assistant).
/// MTP also gates loader-side preservation of `mtp.*` weight keys
/// (see ``MTPLoader/mtpLoadEnabledFromEnv``).
///
/// **Default: false.** Set ``mtpEnabled`` = `true` or
/// `MLX_MTP_ENABLED=1` to opt in. Phase 1 is greedy-only
/// (`temperature == 0`).
///
/// See `specs/030-multi-token-prediction.md`.
public var mtpEnabled: Bool

/// Number of MTP draft tokens to propose per cycle (variant A).
/// Bounded by `MTPInjector.mtpContract.maxHeads` at iterator init.
/// Per-family defaults: DeepSeek-V3/V4 = 1, Qwen3-Next / MiMo = 2.
///
/// Has no effect on variant B — that path uses the registry's
/// `recommendedNumDraftTokens` (gemma-4 = 6 single, 3 batched).
///
/// **Default: 0** (treated as 1 when ``mtpEnabled`` is engaged).
public var mtpDraftCount: Int

/// Optional override for the variant-B assistant draft id. When
/// non-nil, this draft is used instead of the
/// ``AssistantDraftRegistry`` lookup. Useful for benchmark sweeps
/// across draft sizes or for local re-converted bundles.
public var mtpAssistantDraftId: String?

/// Token ID marking the start of a thinking phase (e.g., <think> token).
/// When set with thinkEndTokenId, log probabilities are tracked separately
/// for thinking vs. generation phases in GenerateCompletionInfo.
Expand Down Expand Up @@ -236,6 +268,9 @@ public struct GenerateParameters: Sendable {
ngramDraftMin: Int = 1,
ngramMinHits: Int = 1,
minNgramSize: Int = 2,
mtpEnabled: Bool = false,
mtpDraftCount: Int = 0,
mtpAssistantDraftId: String? = nil,
thinkStartTokenId: Int32? = nil,
thinkEndTokenId: Int32? = nil,
thinkingPhasePrefilled: Bool = false,
Expand Down Expand Up @@ -268,6 +303,9 @@ public struct GenerateParameters: Sendable {
self.ngramDraftMin = ngramDraftMin
self.ngramMinHits = ngramMinHits
self.minNgramSize = minNgramSize
self.mtpEnabled = mtpEnabled
self.mtpDraftCount = mtpDraftCount
self.mtpAssistantDraftId = mtpAssistantDraftId
self.thinkStartTokenId = thinkStartTokenId
self.thinkEndTokenId = thinkEndTokenId
self.thinkingPhasePrefilled = thinkingPhasePrefilled
Expand Down Expand Up @@ -2052,6 +2090,44 @@ public func generate(
input: LMInput, cache: [KVCache]? = nil, parameters: GenerateParameters, context: ModelContext,
wiredMemoryTicket: WiredMemoryTicket? = nil
) throws -> AsyncStream<Generation> {
// Auto-route to ``MTPSelfSpeculativeTokenIterator`` (variant A) first
// when the caller has opted in (via ``GenerateParameters/mtpEnabled``
// or `MLX_MTP_ENABLED=1`) AND the model conforms to ``MTPInjector``
// with MTP heads loaded AND the trunk cache is fully trimmable. MTP
// takes precedence over n-gram because trained-head proposals carry
// a higher acceptance ceiling than prompt-lookup. See spec 030.
let mtpRoute = mtpRouteDecision(parameters: parameters)
if mtpRoute.shouldEngage,
let mtpModel = context.model as? any (LanguageModel & MTPInjector),
mtpModel.isMTPLoaded
{
let probeCache = cache ?? mtpModel.newCache(parameters: mtpRoute.parameters)
if canTrimPromptCache(probeCache) {
do {
let mtpIterator = try MTPSelfSpeculativeTokenIterator(
input: input,
model: mtpModel,
trunkCache: probeCache,
parameters: mtpRoute.parameters)
let (stream, _) = generateLoopTask(
promptTokenCount: input.text.tokens.size,
modelConfiguration: context.configuration,
tokenizer: context.tokenizer,
iterator: mtpIterator,
wiredMemoryTicket: wiredMemoryTicket,
handler: TextToolTokenLoopHandler(
tokenizer: context.tokenizer,
format: context.configuration.toolCallFormat ?? .json
)
)
return stream
} catch {
// Init refused (greedy-only, hybrid cache, etc.). Fall
// through to the next route.
}
}
}

// Auto-route to ``NGramSpeculativeTokenIterator`` when the caller has
// opted in (via parameters or `MLX_NGRAM_ENABLED=1`) AND the
// configuration is compatible: greedy sampling, no logit processors
Expand Down
Loading