Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright © 2026 Apple Inc.

import Foundation
import HuggingFace
import IntegrationTestHelpers
import MLX
import MLXHuggingFace
import MLXLLM
import MLXLMCommon
import Testing
import Tokenizers

private let models = IntegrationTestModels(
downloader: #hubDownloader(),
tokenizerLoader: #huggingFaceTokenizerLoader()
)

@Suite(.serialized)
struct GenerationObservabilityIntegrationTests {
@Test func composedHandlerPreservesModelGeneration() async throws {
let container = try await models.llmContainer(for: LLMRegistry.llama3_2_1B_4bit)
let prompt = "Explain why the sky is blue in one sentence."
let parameters = GenerateParameters(maxTokens: 32, temperature: 0)
let input = try await container.prepare(input: UserInput(prompt: prompt))
let (referenceStream, referenceTask) = try await container.perform(nonSendable: input) {
context, input in
try generateTokensTask(input: input, parameters: parameters, context: context)
}
var referenceTokens: [Int] = []
for await event in referenceStream {
if let token = event.token { referenceTokens.append(token) }
}
await referenceTask.value
#expect(!referenceTokens.isEmpty)

for topCount in [nil, 0, 5] as [Int?] {
var parameters = parameters
parameters.logProbabilities = topCount
let input = try await container.prepare(input: UserInput(prompt: prompt))
let (stream, task) = try await container.perform(nonSendable: input) {
[parameters] context, input in
let iterator = try TokenIterator(
input: input, model: context.model, parameters: parameters)
return generateLoopTask(
promptTokenCount: input.text.tokens.size,
modelConfiguration: context.configuration,
tokenizer: context.tokenizer, iterator: iterator,
handler: LogProbabilityTokenLoopHandler(RawTokenLoopHandler()))
}

var tokens: [Int] = []
var probabilities: [GenerateTokenLogProbabilities] = []
var completion: GenerateCompletionInfo?
for await event in stream {
switch event {
case .generation(.token(let token)): tokens.append(token)
case .generation(.info(let info)): completion = info
case .probability(let values): probabilities.append(values)
}
}
await task.value

#expect(tokens == referenceTokens)
#expect(completion?.generationTokenCount == tokens.count)
if let topCount {
#expect(probabilities.map(\.chosen.token) == tokens)
#expect(
probabilities.allSatisfy {
$0.chosen.logProbability.isFinite && $0.chosen.logProbability <= 0
&& $0.topLogProbabilities.count == topCount
})
} else {
#expect(probabilities.isEmpty)
}
if let completion {
print(
"Log probabilities \(String(describing: topCount)): \(completion.tokensPerSecond) tokens/s"
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright © 2026 Apple Inc.

import Foundation
import HuggingFace
import MLX
import MLXHuggingFace
import MLXLLM
import MLXLMCommon
import MLXNN
import Testing
import Tokenizers

struct QwenMTPReference: Sendable {
let id: String
let revision: String
let bits: Int
}

private let qwenMTPReferences = [
QwenMTPReference(
id: "mlx-community/Qwen3.5-4B-MTP-4bit",
revision: "ab6f59bc6627196c611ab8851638651078170485", bits: 4),
QwenMTPReference(
id: "mlx-community/Qwen3.5-4B-MTP-5bit",
revision: "aee6a907373f1b758cc8c406da663cf85eb01ed3", bits: 5),
QwenMTPReference(
id: "mlx-community/Qwen3.5-9B-MTP-4bit",
revision: "222dfd2c23fc9518d7b817e4f8e0cb0571787489", bits: 4),
]

@Suite(.serialized)
struct Qwen35CheckpointIntegrationTests {
private let downloader = #hubDownloader()
private let tokenizerLoader = #huggingFaceTokenizerLoader()

@Test(arguments: qwenMTPReferences)
func publishedStandaloneHeadsLoad(reference: QwenMTPReference) async throws {
let drafter = try await loadDrafter(reference)
#expect(drafter.model.parameters().flattened().count == 31)
let projections = drafter.model.modules().compactMap { $0 as? QuantizedLinear }
#expect(projections.count == 8)
#expect(projections.allSatisfy { $0.bits == reference.bits && $0.groupSize == 64 })
}

@Test
func standaloneHeadProducesAcceptedDraftsAndMatchesGreedyTarget() async throws {
let target = try await LLMModelFactory.shared.load(
from: downloader, using: tokenizerLoader,
configuration: .init(
id: "mlx-community/Qwen3.5-4B-4bit",
revision: "0e7ffd5c629ef7719d4cbc04069232580bfa9d9c"))
let drafter = try await loadDrafter(qwenMTPReferences[0])
let input = try await target.processor.prepare(
input: UserInput(chat: [
.user("Why is the sky blue? Explain briefly.")
]))
let parameters = GenerateParameters(maxTokens: 64, temperature: 0)
let baseline = try generateTokens(input: input, parameters: parameters, context: target)
let baselineResult = await collect(baseline)
let speculative = try generateTokens(
input: input, parameters: parameters, context: target,
mtpDrafter: drafter.model, blockSize: 2)
let result = await collect(speculative)
let info = try #require(result.info)
#expect(!result.tokens.isEmpty)
#expect(result.tokens == baselineResult.tokens)
#expect((info.proposedDraftTokens ?? 0) > 0)
#expect((info.acceptedDraftTokens ?? 0) > 0)
#expect(info.passthroughReason == nil)
}

private func loadDrafter(_ reference: QwenMTPReference) async throws -> MTPDrafterContext {
await Qwen35TextMTPRegistration.register()
return try await MTPDrafterModelFactory.shared.load(
from: downloader, using: tokenizerLoader,
configuration: .init(id: reference.id, revision: reference.revision))
}

private func collect(_ stream: AsyncStream<TokenGeneration>) async -> (
tokens: [Int], info: GenerateCompletionInfo?
) {
var tokens = [Int]()
var info: GenerateCompletionInfo?
for await event in stream {
switch event {
case .token(let token): tokens.append(token)
case .info(let completion): info = completion
}
}
return (tokens, info)
}
}
29 changes: 15 additions & 14 deletions Libraries/MLXLLM/Models/Gemma3nText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -961,20 +961,21 @@ public class Gemma3nTextModel: Module, LLMModel {
inputs: inputs, inputsEmbeds: inputsEmbeds, mask: mask, cache: cacheArray)
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
var processedWeights: [String: MLXArray] = [:]

for (key, value) in weights {
if key.hasPrefix("model.language_model.") {
// Remove "model." prefix for VLM-style weights
let newKey = key.replacingOccurrences(
of: "model.language_model.", with: "language_model.")
processedWeights[newKey] = value
} else {
// Keep other weights as-is
processedWeights[key] = value
}
}
public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint {
var checkpoint = try checkpoint.mapNames(
using: .init([
.replacePrefix("model.language_model", with: "language_model")
]))
checkpoint.weights = trimVocabulary(weights: checkpoint.weights)
return checkpoint
}

public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] {
try prepareCheckpoint(.init(weights: weights)).weights
}

private func trimVocabulary(weights: [String: MLXArray]) -> [String: MLXArray] {
var processedWeights = weights

let expectedVocab = config.vocabSize
let keysToCheck = [
Expand Down
45 changes: 26 additions & 19 deletions Libraries/MLXLLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,15 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {
}
}

public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint {
var checkpoint = try Qwen35CheckpointPolicy.prepareTarget(
checkpoint, layout: .text, tiedWordEmbeddings: configuration.tieWordEmbeddings,
retainMTP: MTPConfig.retainMTPWeights)
checkpoint.weights = try sanitize(
weights: checkpoint.weights, metadata: checkpoint.metadata)
return checkpoint
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
let hasUnsanitizedConv1d = weights.contains { key, value in
key.contains("conv1d.weight") && value.dim(-1) != 1
Expand Down Expand Up @@ -1342,10 +1351,8 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {
let shouldShiftNormWeights =
hasUnsanitizedConv1d || (hasMTPWeights && normsLookZeroCentered)

var weights = weights
if !MTPConfig.retainMTPWeights {
weights = weights.filter { !$0.key.contains("mtp.") }
}
var weights = Qwen35CheckpointPolicy.targetWeights(
weights, retainMTP: MTPConfig.retainMTPWeights)

weights = filterLMHeadWeights(
from: weights, tiedWordEmbeddings: configuration.tieWordEmbeddings)
Expand Down Expand Up @@ -1454,22 +1461,22 @@ public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider {
try languageModel.prepare()
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
var sanitized = [String: MLXArray]()
for (key, value) in weights {
if key.hasPrefix("vision_tower") || key.hasPrefix("model.visual") {
continue
}
public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint {
var checkpoint = try Qwen35CheckpointPolicy.prepareTarget(
checkpoint, layout: .wrappedText,
tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings,
retainMTP: MTPConfig.retainMTPWeights)
checkpoint.weights = try sanitize(
weights: checkpoint.weights, metadata: checkpoint.metadata)
return checkpoint
}

var key = key
if key.hasPrefix("model.language_model") {
key = key.replacingOccurrences(
of: "model.language_model", with: "language_model.model")
} else if !key.hasPrefix("language_model.") {
key = "language_model." + key
}
sanitized[key] = value
}
public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] {
let checkpoint = try Qwen35CheckpointPolicy.prepareTarget(
.init(weights: weights), layout: .wrappedText,
tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings,
retainMTP: MTPConfig.retainMTPWeights)
var sanitized = checkpoint.weights

// FP8 block-wise dequantization for Qwen3.6-27B-FP8 (dense checkpoint).
// Official FP8 checkpoints ship each weight tensor alongside a
Expand Down
49 changes: 38 additions & 11 deletions Libraries/MLXLLM/Models/Qwen35MTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,26 @@ public final class Qwen35MTPDraftModel: Module, StatefulMTPDrafterModel {
public let requiresSharedTargetKV = false
public let requiresPromptPrefill = true
public let requiresGreedySampling = true
private let preconvertedNorms: Bool
private let checkpointPolicy: Qwen35CheckpointPolicy

@ModuleInfo(key: "mtp") var mtp: Qwen35MTPPredictor

public init(
public convenience init(
_ configuration: Qwen35TextConfiguration,
preconvertedNorms: Bool = false
) {
self.init(
configuration,
checkpointPolicy: .init(
layout: configuration.modelType == "qwen3_5_mtp" ? .standalone : .embedded,
preconvertedNorms: preconvertedNorms))
}

private init(
_ configuration: Qwen35TextConfiguration, checkpointPolicy: Qwen35CheckpointPolicy
) {
self.configuration = configuration
self.preconvertedNorms = preconvertedNorms
self.checkpointPolicy = checkpointPolicy
_mtp.wrappedValue = Qwen35MTPPredictor(configuration)
super.init()
}
Expand All @@ -89,7 +99,11 @@ public final class Qwen35MTPDraftModel: Module, StatefulMTPDrafterModel {
_ configuration: Qwen35Configuration,
preconvertedNorms: Bool = false
) {
self.init(configuration.textConfig, preconvertedNorms: preconvertedNorms)
self.init(
configuration.textConfig,
checkpointPolicy: .init(
layout: configuration.modelType == "qwen3_5_mtp" ? .standalone : .embedded,
preconvertedNorms: preconvertedNorms))
}

public func makeState(parameters: GenerateParameters?) -> MTPDrafterState {
Expand Down Expand Up @@ -236,13 +250,20 @@ public final class Qwen35MTPDraftModel: Module, StatefulMTPDrafterModel {
state.proposalAppended = 0
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
qwenMTPSanitizeWeights(
weights: weights,
mtpNumHiddenLayers: configuration.mtpNumHiddenLayers,
numExperts: configuration.numExperts,
shiftNormWeights: !preconvertedNorms
)
public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint {
try checkpointPolicy.prepare(
checkpoint, mtpNumHiddenLayers: configuration.mtpNumHiddenLayers,
numExperts: configuration.numExperts)
}

public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] {
try sanitize(weights: weights, metadata: [:])
}

public func sanitize(weights: [String: MLXArray], metadata: [String: String]) throws -> [String:
MLXArray]
{
try prepareCheckpoint(.init(weights: weights, metadata: metadata)).weights
}

private func targetEmbeddingAndHead(_ target: any LanguageModel) -> (Embedding, Linear?) {
Expand All @@ -256,3 +277,9 @@ public final class Qwen35MTPDraftModel: Module, StatefulMTPDrafterModel {
"Qwen35MTPDraftModel requires a Qwen35 target, got \(type(of: target))")
}
}

extension Qwen35MTPDraftModel: ModelConversionMetadataProvider {
public var modelConversionMetadata: [String: String] {
[Qwen35CheckpointPolicy.normMetadataKey: "scale"]
}
}
21 changes: 6 additions & 15 deletions Libraries/MLXLLM/Models/Qwen35MoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,16 @@ public struct Qwen35Configuration: Codable, Sendable {

public class Qwen35MoEModel: Qwen35Model {

override public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
override public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] {
// ── Step 1: FP8 dequantization (official Qwen3.6-35B-A3B-FP8 checkpoint) ──
// The FP8 release stores quantized weights alongside weight_scale_inv tensors.
// We preserve them and stack them so they can be lazily dequantized in SwitchLinear.
// ── Step 2: Key remapping ──
var newWeights = [String: MLXArray]()
for (key, value) in weights {
if key.hasPrefix("vision_tower") || key.hasPrefix("model.visual") {
continue
}
var key = key
if key.hasPrefix("model.language_model") {
key = key.replacingOccurrences(
of: "model.language_model", with: "language_model.model")
} else if !key.hasPrefix("language_model.") {
key = "language_model." + key
}
newWeights[key] = value
}
let checkpoint = try Qwen35CheckpointPolicy.prepareTarget(
.init(weights: weights), layout: .wrappedText,
tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings,
retainMTP: MTPConfig.retainMTPWeights)
var newWeights = checkpoint.weights

// ── Step 3: MoE expert weight stacking (main layers) ──
// Format A: community 4-bit checkpoints ship a pre-stacked "gate_up_proj" → split into gate/up
Expand Down
Loading
Loading