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,53 @@
// Copyright © 2026 Apple Inc.

import CoreImage
import Foundation
import HuggingFace
import MLX
import MLXHuggingFace
import MLXLMCommon
import MLXNN
import MLXVLM
import Testing
import Tokenizers

@Suite(.serialized)
struct Qwen3VLComponentIntegrationTests {
/// The real quantized backbone must produce identical hidden states under both load policies.
@Test func onDemandVisionMatchesImmediateOnQuantizedCheckpoint() async throws {
let directory = try await #hubDownloader().download(
id: "mlx-community/Qwen3-VL-4B-Instruct-4bit",
revision: "2fd8dacbdb8f1e54b8c005f081ec5bf79c56376b",
matching: ["*.safetensors", "*.json", "*.jinja"], useLatest: false,
progressHandler: { _ in })
let context = try await VLMModelFactory.shared.load(
from: directory, using: #huggingFaceTokenizerLoader())
let model = try #require(context.model as? Qwen3VL)
let holder = try #require(model.onDemandComponents.first)
let paths = model.parameters().flattened().map(\.0)
let textBytes = model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes }
#expect(!holder.isLoaded)
#expect(paths.allSatisfy { $0.hasPrefix("language_model.") })
let text = try await context.processor.prepare(input: UserInput(prompt: "A red bicycle."))
let textReference = try model.hiddenStates(text)[0, -1, 0...].asArray(Float.self)
#expect(!holder.isLoaded)
let image = CIImage(color: .red).cropped(to: CGRect(x: 0, y: 0, width: 56, height: 56))
let visual = try await context.processor.prepare(
input: UserInput(chat: [.user("A red square.", images: [.ciImage(image)])]))
let visualReference = try model.hiddenStates(visual)[0, -1, 0...].asArray(Float.self)
#expect(holder.isLoaded)
#expect(model.parameters().flattened().map(\.0) == paths)
let base = try JSONDecoder().decode(
BaseConfiguration.self,
from: Data(contentsOf: directory.appendingPathComponent("config.json")))
try await loadWeights(
modelDirectory: directory, model: model,
perLayerQuantization: base.perLayerQuantization,
componentLoading: .immediate)
#expect(try model.hiddenStates(text)[0, -1, 0...].asArray(Float.self) == textReference)
#expect(try model.hiddenStates(visual)[0, -1, 0...].asArray(Float.self) == visualReference)
let fullBytes = model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes }
#expect(fullBytes > textBytes)
print("Qwen3VL text weights: \(textBytes) bytes; immediate weights: \(fullBytes) bytes")
}
}
7 changes: 7 additions & 0 deletions Libraries/MLXLMCommon/ModelComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@ extension ModelComponentsProviding {
}
return evicted
}

/// Preload media off the Swift concurrency pool before a custom forward pass.
package nonisolated(nonsending) func loadMediaComponents(_ needed: Set<ModelComponent>)
async throws
{
try await loadOnDemandComponents(pendingOnDemandComponents(of: self, among: needed))
}
}

extension [CheckpointComponent] {
Expand Down
98 changes: 72 additions & 26 deletions Libraries/MLXVLM/Models/Qwen3VL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import MLXNN

private enum Qwen3VLError: Error {
case featureTokenMismatch(expected: Int, actual: Int)
case invalidEmbeddingInput
}

private let ropeDeltasKey = LMOutput.Key<MLXArray>("qwen35vl.ropeDeltas")
Expand Down Expand Up @@ -1638,16 +1639,28 @@ extension Qwen3VLLanguage {

// MARK: - Model

private final class Qwen3VLVisionStack: Module {
@ModuleInfo(key: "vision_tower") var tower: Qwen3VLVision.VisionModel

init(_ config: Qwen3VLConfiguration.VisionConfiguration) {
_tower.wrappedValue = Qwen3VLVision.VisionModel(config)
}
}

public final class Qwen3VL: Module, VLMModel, KVCacheDimensionProvider {

@ModuleInfo(key: "vision_tower") private var visionModel: Qwen3VLVision.VisionModel
@ModuleInfo(key: "vision_tower") private var visionModel: Qwen3VLVision.VisionModel?
@ModuleInfo(key: "language_model") private var languageModel: Qwen3VLLanguage.LanguageModel
private let onDemandVision: OnDemandComponent<Qwen3VLVisionStack>

public let config: Qwen3VLConfiguration

public init(_ config: Qwen3VLConfiguration) {
self.config = config
_visionModel.wrappedValue = Qwen3VLVision.VisionModel(config.visionConfiguration)
onDemandVision = OnDemandComponent(.vision) {
Qwen3VLVisionStack(config.visionConfiguration)
}
_languageModel.wrappedValue = Qwen3VLLanguage.LanguageModel(config)
}

Expand Down Expand Up @@ -1733,6 +1746,8 @@ public final class Qwen3VL: Module, VLMModel, KVCacheDimensionProvider {
private func visionInputs(_ input: LMInput) throws -> VisionInputs {
var result = VisionInputs()

guard input.image != nil || input.video != nil else { return result }
let visionModel = try visionModel ?? onDemandVision.load().tower
let dtype = visionModel.patchEmbed.proj.weight.dtype
var pixelParts: [MLXArray] = []

Expand Down Expand Up @@ -1787,6 +1802,31 @@ public final class Qwen3VL: Module, VLMModel, KVCacheDimensionProvider {
return result
}

/// Returns final normalized hidden states before vocabulary projection for one unpadded input.
public func hiddenStates(_ input: LMInput) throws -> MLXArray {
let tokens = input.text.tokens
guard tokens.ndim == 2, tokens.dim(0) == 1, tokens.dim(1) > 0,
input.text.mask == nil
|| (input.text.mask?.shape == tokens.shape
&& (input.text.mask?.all().item(Bool.self) ?? false))
else {
throw Qwen3VLError.invalidEmbeddingInput
}
let vision = try visionInputs(input)
let (positions, _) = Qwen3VLLanguage.getRopeIndex(
inputIds: tokens,
imageGridTHW: vision.imageFrames,
videoGridTHW: vision.videoFrames,
spatialMergeSize: config.visionConfiguration.spatialMergeSize,
imageTokenId: config.imageTokenIndex,
videoTokenId: config.videoTokenIndex,
visionStartTokenId: config.visionStartTokenId)
return languageModel.model(
tokens, cache: nil, inputEmbeddings: vision.inputEmbeddings,
mask: nil, positionIds: positions, visualIndices: vision.visualIndices,
deepstackEmbeds: vision.deepstackEmbeds)
}

public func prepare(
_ input: LMInput,
cache: [any KVCache],
Expand Down Expand Up @@ -1964,35 +2004,41 @@ public final class Qwen3VL: Module, VLMModel, KVCacheDimensionProvider {
return result
}

public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] {
var adjusted: [String: MLXArray] = [:]
adjusted.reserveCapacity(weights.count)

for (key, value) in weights {
var newKey = key

if newKey.contains("model") {
if newKey.contains("model.visual") {
newKey = newKey.replacingOccurrences(of: "model.visual", with: "vision_tower")
} else if newKey.contains("model.language_model") {
newKey = newKey.replacingOccurrences(
of: "model.language_model", with: "language_model.model")
}
} else if newKey.contains("lm_head") {
newKey = newKey.replacingOccurrences(of: "lm_head", with: "language_model.lm_head")
}

if config.textConfiguration.tieWordEmbeddings && newKey.contains(".lm_head.") {
// if using tieWordEmbeddings omit these keys as they will not be consumed
continue
}
public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] {
try prepareCheckpoint(.init(weights: weights)).weights
}

adjusted[newKey] = value
public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint {
var rules: [CheckpointNameMapping.Rule] = [
.replacePrefix("model.visual", with: "vision_tower"),
.replacePrefix("visual", with: "vision_tower"),
.replacePrefix("model.vision_tower", with: "vision_tower"),
.replacePrefix("model.language_model", with: "language_model.model"),
.replacePrefix("lm_head", with: "language_model.lm_head"),
]
if config.textConfiguration.tieWordEmbeddings {
rules.append(.excludePrefix("language_model.lm_head"))
}
var checkpoint = try checkpoint.mapNames(using: CheckpointNameMapping(rules))
checkpoint.weights = Qwen3VLVision.VisionModel.sanitize(
weights: checkpoint.weights, config: config.visionConfiguration)
return checkpoint
}
}

let sanitized = visionModel.sanitize(weights: adjusted)
return sanitized
extension Qwen3VL: ModelComponentsProviding {
public var modelComponents: [ModelComponent: [CheckpointComponent]] {
[
.vision: [
CheckpointComponent(
name: "vision_tower",
namespaces: ["vision_tower", "model.vision_tower", "visual", "model.visual"],
destination: "vision_tower")
]
]
}

public var onDemandComponents: [AnyOnDemandComponent] { [onDemandVision] }
}

extension Qwen3VL: PreparedInputSplitting {
Expand Down
5 changes: 3 additions & 2 deletions Libraries/MLXVLM/Models/QwenVL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ public struct QwenVL {
) throws -> [Int] {
// Replace single padding token with correct number for each image or video frame
let placeholderTokens = tokenizer.encode(
text: "<|vision_start|>\(paddingToken)<|vision_end|>")
text: "<|vision_start|>\(paddingToken)<|vision_end|>", addSpecialTokens: false)
let placeholderRanges = promptTokens.ranges(of: placeholderTokens)
guard placeholderRanges.count == frames.count else {
throw VLMError.processing(
Expand All @@ -303,7 +303,8 @@ public struct QwenVL {
let paddingCount = frame.product / mergeLength
return tokenizer.encode(
text:
"<|vision_start|>\(Array(repeating: paddingToken, count: paddingCount).joined())<|vision_end|>"
"<|vision_start|>\(Array(repeating: paddingToken, count: paddingCount).joined())<|vision_end|>",
addSpecialTokens: false
)
}
// Build the final array
Expand Down
5 changes: 5 additions & 0 deletions Libraries/MLXVLM/MultimodalEmbeddingFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@ public typealias MultimodalEmbeddingLoader =
public enum MultimodalEmbeddingTypeRegistry {

public static let shared = ModelTypeRegistry<MultimodalEmbeddingLoader>(creators: [
"qwen3_vl": { _ in qwen3VL },
"embedding_gemma2": { _ in embeddingGemma2 },
"embedding_gemma2_text": { _ in embeddingGemma2 },
])

private static let qwen3VL: MultimodalEmbeddingLoader = {
try await Qwen3VLEmbedding(configuration: $0, tokenizerLoader: $1)
}

private static let embeddingGemma2: MultimodalEmbeddingLoader = {
try await EmbeddingGemma2Embedding(configuration: $0, tokenizerLoader: $1)
}
Expand Down
Loading
Loading