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
3 changes: 2 additions & 1 deletion Libraries/MLXLLM/Models/Qwen35MTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ public final class Qwen35MTPDraftModel: Module, StatefulMTPDrafterModel {
weights: weights,
mtpNumHiddenLayers: configuration.mtpNumHiddenLayers,
numExperts: configuration.numExperts,
shiftNormWeights: !preconvertedNorms
shiftNormWeights: !preconvertedNorms,
standaloneCheckpoint: preconvertedNorms
)
}

Expand Down
16 changes: 14 additions & 2 deletions Libraries/MLXLMCommon/QwenMTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,21 @@ package func qwenMTPSanitizeWeights(
weights: [String: MLXArray],
mtpNumHiddenLayers: Int,
numExperts: Int,
shiftNormWeights: Bool
shiftNormWeights: Bool,
standaloneCheckpoint: Bool = false
) -> [String: MLXArray] {
var sanitized = weights.filter { key, _ in key.hasPrefix("mtp.") }
// Converted standalone drafters may store the predictor at the root
// (fc.*, layers.*, norm.*), without the full model's mtp wrapper. Only
// standalone model registrations admit that layout. Never reinterpret
// a full target checkpoint's bare weights as drafter parameters, or mix
// them into an already namespaced MTP checkpoint.
let source: [String: MLXArray]
if standaloneCheckpoint, !weights.keys.contains(where: { $0.hasPrefix("mtp.") }) {
source = Dictionary(uniqueKeysWithValues: weights.map { ("mtp." + $0.key, $0.value) })
} else {
source = weights
}
var sanitized = source.filter { key, _ in key.hasPrefix("mtp.") }

for layer in 0 ..< max(mtpNumHiddenLayers, 1) {
let prefix = "mtp.layers.\(layer).mlp"
Expand Down
3 changes: 2 additions & 1 deletion Libraries/MLXVLM/Models/Qwen35MTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ public final class Qwen35VLMNextNDraftModel: Module, StatefulMTPDrafterModel {
weights: weights,
mtpNumHiddenLayers: configuration.mtpNumHiddenLayers,
numExperts: configuration.numExperts,
shiftNormWeights: !preconvertedNorms
shiftNormWeights: !preconvertedNorms,
standaloneCheckpoint: preconvertedNorms
)
}
}
Expand Down
32 changes: 31 additions & 1 deletion QWEN38_INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,30 @@ checkpoint revisions, and measures standard decoding. The Director's explicit
reasoning controls are a separate configuration. Benchmark outcomes do not
automatically change production model defaults.

## Standalone MTP weight compatibility

The `qwen3_5_mtp` and `qwen3_8_mtp` standalone drafter registrations accept
converted checkpoints with either bare predictor keys (`fc.*`, `layers.*`,
`norm.*`, `pre_fc_norm_*`) or `mtp.`-prefixed keys. Select the text registry
through `Qwen35TextMTPRegistration.register()` or the vision-language registry
through `Qwen35VLMMTPRegistration.register()` for the corresponding target.
The existing weight loader handles both layouts without editing checkpoint files.

Bare keys receive the `mtp.` namespace only for standalone registrations when
no prefixed keys exist. Already prefixed checkpoints keep their existing
filtering; full target checkpoints never reinterpret bare target weights as MTP
parameters. Converted norm values and quantized weights, scales and biases are
preserved. This compatibility fix does not enable production MTP or change
model defaults, sampling, block size or speculative decoding algorithms.

`Qwen35MTPRegistrationTests` writes tiny synthetic quantized safetensors into
unique temporary directories and loads them through the production weight
loader. Its four text/vision and bare/prefixed combinations verify exact
parameter equality; both bare variants reproduced missing-parameter failures
before the fix and pass afterward. Two further cases verify that full text and
vision checkpoints reject bare target weights. Fixtures require no downloaded
checkpoint or user data and remove their temporary directories afterward.

## Validation

On the M5 Max host, a fresh scratch build and serial full-precision tests passed:
Expand All @@ -49,7 +73,13 @@ MLX_ENABLE_TF32=0 swift test --scratch-path /private/tmp/qwen38-lm-clean \
--skip-build --no-parallel
```

Result: 611 XCTest passes, one skip, and 833 Swift Testing passes across 77 suites.
For the standalone loading fix `600821e`, the 2026-09-06 full run reported
612 XCTest executions: 611 passes, one skipped real-checkpoint benchmark and
zero failures. Swift Testing reported 835 tests across 77 suites with zero
failures; the log also explicitly lists the existing disabled three-test
`ConstraintCachingTests` suite, whose required XGrammar fork API is unavailable
in the vendored version. These counts are dated evidence, not a claim that every
optional integration test ran.
The build used the sibling MLX fork at
`de8a9179a1cd7f68b6322d09771e9db39cb73cff`.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ For some example applications and tools that use MLX Swift LM, check out [MLX Sw

Developers can use these examples in their own programs -- just import the swift package!

- [Fork Qwen3.8 runtime integration](QWEN38_INTEGRATION.md)
- [Fork Qwen3.8 integration and standalone MTP compatibility](QWEN38_INTEGRATION.md)
- [Porting and implementing models](https://swiftpackageindex.com/ml-explore/mlx-swift-lm/main/documentation/mlxlmcommon/porting)
- [Techniques for developing in mlx-swift-lm](https://swiftpackageindex.com/ml-explore/mlx-swift-lm/main/documentation/mlxlmcommon/developing)
- [MLXLLMCommon](https://swiftpackageindex.com/ml-explore/mlx-swift-lm/main/documentation/mlxlmcommon): Common API for LLM and VLM
Expand Down
54 changes: 54 additions & 0 deletions Tests/MLXLMTests/Qwen35MTPTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Foundation
import MLX
import MLXLMCommon
import MLXNN
import Testing

@testable import MLXLLM
Expand Down Expand Up @@ -375,6 +376,59 @@ struct Qwen35MTPMetalTests {

@Suite(.serialized)
struct Qwen35MTPRegistrationTests {
@Test(arguments: [false, true], [false, true])
func standaloneCheckpointLoadsConvertedWeights(vision: Bool, prefixed: Bool) async throws {
await MLXLLM.Qwen35TextMTPRegistration.register()
await MLXVLM.Qwen35VLMMTPRegistration.register()
let registry =
vision ? MTPDrafterTypeRegistry.visionLanguage : MTPDrafterTypeRegistry.shared
let config = Data(qwen35StandaloneMTPConfigJSON().utf8)
let reference = try await registry.createModel(
configuration: config, modelType: "qwen3_5_mtp")
// Exercise packed tensors and their scales/biases as well as converted
// norms, with the standalone key layout used by the published drafter.
quantize(model: reference, groupSize: 32, bits: 4, filter: { path, _ in path == "mtp.fc" })
let expected = Dictionary(uniqueKeysWithValues: reference.parameters().flattened())
let arrays = Dictionary(
uniqueKeysWithValues: expected.map { key, value in
(prefixed ? key : String(key.dropFirst("mtp.".count)), value)
})
let directory = FileManager.default.temporaryDirectory
.appending(component: "qwen-mtp-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
try save(arrays: arrays, url: directory.appending(component: "model.safetensors"))

let loaded = try await registry.createModel(configuration: config, modelType: "qwen3_5_mtp")
try await loadWeights(
modelDirectory: directory, model: loaded,
quantization: .init(groupSize: 32, bits: 4))
let actual = Dictionary(uniqueKeysWithValues: loaded.parameters().flattened())
#expect(Set(actual.keys) == Set(expected.keys))
#expect(actual["mtp.fc.scales"] != nil)
for (key, value) in expected {
let loadedValue = try #require(actual[key])
#expect(allClose(loadedValue, value, rtol: 0, atol: 0).item(Bool.self))
}
}

@Test(arguments: [false, true])
func fullCheckpointDoesNotTreatBareTargetWeightsAsMTP(vision: Bool) throws {
let drafter: any MTPDrafterModel
if vision {
let config = try JSONDecoder().decode(
MLXVLM.Qwen35Configuration.self,
from: Data(qwen35VLMConfigJSON(mtpLayers: 1).utf8))
drafter = MLXVLM.Qwen35VLMNextNDraftModel(config)
} else {
let config = try JSONDecoder().decode(
MLXLLM.Qwen35TextConfiguration.self,
from: Data(qwen35TextConfigJSON(mtpLayers: 1).utf8))
drafter = MLXLLM.Qwen35MTPDraftModel(config)
}
#expect(drafter.sanitize(weights: ["norm.weight": MLXArray.ones([16])]).isEmpty)
}

@Test
func registrationsCreateTextAndVLMDrafters() async throws {
await MLXLLM.Qwen35TextMTPRegistration.register()
Expand Down