diff --git a/IntegrationTesting/IntegrationTestingTests/Qwen3VLComponentIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/Qwen3VLComponentIntegrationTests.swift new file mode 100644 index 000000000..7d5b5bbc4 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/Qwen3VLComponentIntegrationTests.swift @@ -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") + } +} diff --git a/Libraries/MLXLMCommon/ModelComponent.swift b/Libraries/MLXLMCommon/ModelComponent.swift index b8baa3842..512415061 100644 --- a/Libraries/MLXLMCommon/ModelComponent.swift +++ b/Libraries/MLXLMCommon/ModelComponent.swift @@ -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) + async throws + { + try await loadOnDemandComponents(pendingOnDemandComponents(of: self, among: needed)) + } } extension [CheckpointComponent] { diff --git a/Libraries/MLXVLM/Models/Qwen3VL.swift b/Libraries/MLXVLM/Models/Qwen3VL.swift index ad8af2c17..0790db1bd 100644 --- a/Libraries/MLXVLM/Models/Qwen3VL.swift +++ b/Libraries/MLXVLM/Models/Qwen3VL.swift @@ -10,6 +10,7 @@ import MLXNN private enum Qwen3VLError: Error { case featureTokenMismatch(expected: Int, actual: Int) + case invalidEmbeddingInput } private let ropeDeltasKey = LMOutput.Key("qwen35vl.ropeDeltas") @@ -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 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) } @@ -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] = [] @@ -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], @@ -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 { diff --git a/Libraries/MLXVLM/Models/QwenVL.swift b/Libraries/MLXVLM/Models/QwenVL.swift index e7c7cb9f6..1678b3aa2 100644 --- a/Libraries/MLXVLM/Models/QwenVL.swift +++ b/Libraries/MLXVLM/Models/QwenVL.swift @@ -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( @@ -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 diff --git a/Libraries/MLXVLM/MultimodalEmbeddingFactory.swift b/Libraries/MLXVLM/MultimodalEmbeddingFactory.swift index 8adc573c1..71605d82b 100644 --- a/Libraries/MLXVLM/MultimodalEmbeddingFactory.swift +++ b/Libraries/MLXVLM/MultimodalEmbeddingFactory.swift @@ -12,10 +12,15 @@ public typealias MultimodalEmbeddingLoader = public enum MultimodalEmbeddingTypeRegistry { public static let shared = ModelTypeRegistry(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) } diff --git a/Libraries/MLXVLM/Qwen3VLEmbedding.swift b/Libraries/MLXVLM/Qwen3VLEmbedding.swift new file mode 100644 index 000000000..5f92dee16 --- /dev/null +++ b/Libraries/MLXVLM/Qwen3VLEmbedding.swift @@ -0,0 +1,266 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon + +/// Text and image embeddings from a Qwen3-VL-Embedding checkpoint. +/// Load an embedding-trained checkpoint with ``MultimodalEmbeddingFactory``, or reuse a +/// ``VLMModelFactory`` container. Vision weights load on the first image. +/// This implementation accepts text and images; video and audio are not supported. +public struct Qwen3VLEmbedding: MultimodalEmbedding { + /// One independently pooled item. Images are transferred into the container's isolation. + public struct Input { + public let text: String + public let images: [UserInput.Image] + + public init(text: String = "", images: [UserInput.Image] = []) { + self.text = text + self.images = images + } + } + + public enum Error: Swift.Error, LocalizedError { + case unsupportedModel + case emptyInput + case contextExceeded + case invalidEmbedding + case unsupportedMedia + + public var errorDescription: String? { + switch self { + case .unsupportedModel: "Qwen3-VL embeddings require a Qwen3-VL model." + case .emptyInput: "An embedding input must contain text or images." + case .contextExceeded: "The embedding input exceeds 32768 tokens." + case .invalidEmbedding: "The model returned an invalid embedding." + case .unsupportedMedia: "Qwen3-VL embeddings support text and images only." + } + } + } + + public static let defaultInstruction = "Represent the user's input." + private let container: ModelContainer + + public var supportedModalities: Set { + get async { + await container.perform { context in + context.configuration.excludedComponents.contains(.vision) + ? [.text] : [.text, .image] + } + } + } + + /// The container must contain embedding-trained weights, rather than instruction-model weights. + public init(container: ModelContainer) async throws { + try Task.checkCancellation() + guard await container.perform({ $0.model is Qwen3VL }) else { + throw Error.unsupportedModel + } + try Task.checkCancellation() + self.container = container + } + + /// Loads a local embedding checkpoint, with vision weights and its processor read on first use. + /// Exclude `.vision` to keep the checkpoint text-only. Files must remain readable until use. + public init( + modelDirectory: URL, tokenizerLoader: any TokenizerLoader, + excludedComponents: Set = [], + componentLoading: ComponentLoading = .onFirstUse + ) async throws { + var configuration = ResolvedModelConfiguration(directory: modelDirectory) + configuration.excludedComponents = excludedComponents + try await self.init( + configuration: configuration, tokenizerLoader: tokenizerLoader, + componentLoading: componentLoading) + } + + package init( + configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader, + componentLoading: ComponentLoading = .onFirstUse + ) async throws { + try Task.checkCancellation() + let modelDirectory = configuration.modelDirectory + let data = try Data(contentsOf: modelDirectory.appendingPathComponent("config.json")) + let config = try JSONDecoder.json5().decode(Qwen3VLConfiguration.self, from: data) + let base = try JSONDecoder.json5().decode(BaseConfiguration.self, from: data) + let model = Qwen3VL(config) + try await loadWeights( + modelDirectory: modelDirectory, model: model, + perLayerQuantization: base.perLayerQuantization, + weightFileSelection: configuration.weightFileSelection, + excludedComponents: configuration.excludedComponents, componentLoading: componentLoading + ) + try Task.checkCancellation() + let tokenizer = try await tokenizerLoader.load(from: configuration.tokenizerDirectory) + try Task.checkCancellation() + var contextConfiguration = ModelConfiguration(directory: modelDirectory) + contextConfiguration.excludedComponents = configuration.excludedComponents + self.container = ModelContainer( + context: ModelContext( + configuration: contextConfiguration, + model: model, + processor: Processor(directory: modelDirectory, tokenizer: tokenizer), + tokenizer: tokenizer)) + } + + /// Embeds items in reading order. Task instructions are general defaults; use the + /// instruction overload to tailor a prompt to a particular retrieval task. + /// Titles are not used by this model. + public func embed( + _ inputs: sending [EmbeddingInput], task: EmbeddingTask + ) async throws -> [[Float]] { + let instruction: String? = + switch task { + case .none: nil + case .searchQuery, .document: Self.defaultInstruction + case .clustering: "Identify the topic or theme of the input." + case .classification: "Classify the input." + case .questionAnswering: "Retrieve information that answers the question." + case .factChecking: "Retrieve information that verifies the claim." + case .codeRetrieval: "Retrieve code matching the input." + case .sentenceSimilarity: "Find inputs with similar meaning." + } + return try await embedParts(inputs, instruction: instruction) + } + + /// Returns one unit-length float32 vector, pooling the checkpoint's terminal token. + public func embed( + _ input: consuming sending Input, instruction: String = defaultInstruction + ) async throws -> [Float] { + let vectors = try await embed([input], instruction: instruction) + return vectors[0] + } + + /// Embeds independent items in input order, bounding visual working memory to one item. + /// Use the same instruction for items that will be compared in the same embedding space. + public func embed( + _ inputs: consuming sending [Input], instruction: String = defaultInstruction + ) async throws -> [[Float]] { + let items = inputs.map { + EmbeddingInput($0.images.map(EmbeddingInput.Part.image) + [.text($0.text)]) + } + return try await embedParts(items, instruction: instruction) + } + + private func embedParts( + _ inputs: sending [EmbeddingInput], instruction: String? + ) async throws -> [[Float]] { + try Task.checkCancellation() + return try await container.perform(nonSendable: inputs) { context, inputs in + guard let model = context.model as? Qwen3VL else { throw Error.unsupportedModel } + for input in inputs { + var hasContent = false + for part in input.parts { + switch part { + case .text(let text): + hasContent = + hasContent + || !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + case .image: + hasContent = true + if context.configuration.excludedComponents.contains(.vision) { + throw OnDemandComponentError.unavailable(.vision) + } + case .video, .audio: throw Error.unsupportedMedia + } + } + guard hasContent else { throw Error.emptyInput } + } + var vectors: [[Float]] = [] + vectors.reserveCapacity(inputs.count) + for input in inputs { + try Task.checkCancellation() + var parts: [[String: any Sendable]] = [] + var images: [UserInput.Image] = [] + for part in input.parts { + switch part { + case .text(let text): parts.append(["type": "text", "text": text]) + case .image(let image): + let imageInput = UserInput(chat: [.user("", images: [image])]) + .removingSpecialTokenLabels(using: context.tokenizer) + let generated = Qwen3VLMessageGenerator().generate(from: imageInput) + guard let imageParts = generated.first?["content"] as? [[String: String]] + else { + throw Error.invalidEmbedding + } + parts.append(contentsOf: imageParts.dropLast()) + images.append(image) + case .video, .audio: throw Error.unsupportedMedia + } + } + var messages: [Message] = [] + if let instruction { + messages.append([ + "role": "system", "content": [["type": "text", "text": instruction]], + ]) + } + messages.append(["role": "user", "content": parts]) + let prepared = try await context.processor.prepare( + input: UserInput( + prompt: .messages(messages), images: images, + processing: .init(minPixels: 4_096, maxPixels: 1_310_720))) + // Embedding checkpoints apply their tokenizer postprocessor after the chat template. + // Preserve the terminal token they were trained to pool. + let prompt = context.tokenizer.decode( + tokenIds: prepared.text.tokens.asArray(Int.self), skipSpecialTokens: false) + let tokens = context.tokenizer.encode(text: prompt, addSpecialTokens: true) + guard !tokens.isEmpty else { throw Error.emptyInput } + guard tokens.count <= 32_768 else { throw Error.contextExceeded } + if prepared.image != nil || prepared.video != nil { + try await model.loadMediaComponents([.vision]) + try Task.checkCancellation() + } + let completed = LMInput( + text: .init(tokens: MLXArray(tokens).expandedDimensions(axis: 0)), + image: prepared.image, video: prepared.video) + let hidden = try model.hiddenStates(completed) + let last = hidden[0, -1, 0...].asType(.float32) + let vector = last / MLX.maximum(MLXLinalg.norm(last), MLXArray(Float(1e-12))) + try MLX.checkedEval(vector) + let values = vector.asArray(Float.self) + guard values.allSatisfy(\.isFinite), values.contains(where: { $0 != 0 }) else { + throw Error.invalidEmbedding + } + vectors.append(values) + } + try Task.checkCancellation() + return vectors + } + } +} + +extension Qwen3VLEmbedding { + private final class Processor: UserInputProcessor, @unchecked Sendable { + let directory: URL + let tokenizer: any Tokenizer + private let lock = NSLock() + private var mediaProcessor: Qwen3VLProcessor? + + init(directory: URL, tokenizer: any Tokenizer) { + self.directory = directory + self.tokenizer = tokenizer + } + + func prepare(input: UserInput) async throws -> LMInput { + if input.images.isEmpty, input.videos.isEmpty { + let messages = Qwen3VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) + let tokens = try tokenizer.applyChatTemplate( + messages: messages, tools: input.tools, + additionalContext: input.additionalContext) + return LMInput(tokens: MLXArray(tokens).expandedDimensions(axis: 0)) + } + let processor = try lock.withLock { + if let mediaProcessor { return mediaProcessor } + let data = try Data( + contentsOf: directory.appendingPathComponent("preprocessor_config.json")) + let config = try JSONDecoder().decode( + Qwen3VLProcessorConfiguration.self, from: data) + let processor = Qwen3VLProcessor(config, tokenizer: tokenizer) + mediaProcessor = processor + return processor + } + return try await processor.prepare(input: input) + } + } +} diff --git a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift index 3aad69d12..1466f1698 100644 --- a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift @@ -13,9 +13,11 @@ // count while slicing embeddings, positions, and the visual mask by token // index. The straddling-image tests below are what cover that lockstep. +import CoreImage import Foundation import MLX import MLXLMCommon +import MLXNN import MLXVLM import XCTest @@ -99,6 +101,394 @@ final class Qwen3VLContinuationTests: XCTestCase { continuation.maxAbsDiff(a, b) } + private func embeddingCheckpoint(namespace: String = "vision_tower", quantized: Bool = false) + throws -> (URL, Qwen3VLConfiguration, BaseConfiguration.PerLayerQuantization?) + { + let source = try makeTinyModel() + let override = "vision_tower.blocks.0.attn.qkv" + if quantized { + MLXNN.quantize(model: source) { path, module in + let weight = (module as? Linear)?.weight ?? (module as? Embedding)?.weight + guard let weight, weight.dim(-1) % 32 == 0 else { return nil } + return (32, path == override ? 8 : 4, .affine) + } + } + func rawName(_ name: String) -> String { + if name.hasPrefix("vision_tower.") { + return namespace + name.dropFirst("vision_tower".count) + } + if namespace == "model.visual", name.hasPrefix("language_model.model.") { + return "model.language_model" + name.dropFirst("language_model.model".count) + } + return name + } + var weights = Dictionary( + uniqueKeysWithValues: source.parameters().flattened().map { (rawName($0.0), $0.1) }) + let convolution = namespace + ".patch_embed.proj.weight" + weights[convolution] = weights[convolution]?.transposed(0, 4, 1, 2, 3) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("Qwen3VLEmbedding-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try save(arrays: weights, url: directory.appendingPathComponent("model.safetensors")) + let precision: BaseConfiguration.PerLayerQuantization? = + quantized + ? .init( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: [rawName(override): .quantize(.init(groupSize: 32, bits: 8))]) + : nil + return (directory, source.config, precision) + } + + func testOnDemandVisionMatchesImmediateAcrossCheckpointLayoutsAndQuantization() throws { + for namespace in ["vision_tower", "model.vision_tower", "visual", "model.visual"] { + for quantized in [false, true] { + let (directory, config, precision) = try embeddingCheckpoint( + namespace: namespace, quantized: quantized) + defer { try? FileManager.default.removeItem(at: directory) } + let eager = Qwen3VL(config) + try loadWeights( + modelDirectory: directory, model: eager, perLayerQuantization: precision, + componentLoading: .immediate) + let lazy = Qwen3VL(config) + try loadWeights( + modelDirectory: directory, model: lazy, perLayerQuantization: precision) + let paths = lazy.parameters().flattened().map(\.0) + XCTAssertTrue(paths.allSatisfy { $0.hasPrefix("language_model.") }) + XCTAssertFalse(lazy.onDemandComponents[0].isLoaded) + let text = LMInput(tokens: textTokens(8)) + XCTAssertTrue( + arrayEqual(try lazy.hiddenStates(text), try eager.hiddenStates(text)).item( + Bool.self)) + XCTAssertFalse(lazy.onDemandComponents[0].isLoaded) + let visual = LMInput( + text: .init( + tokens: concatenated([visionStart(), imageRun(), textTokens(4)], axis: 1)), + image: makeImage()) + XCTAssertTrue( + arrayEqual(try lazy.hiddenStates(visual), try eager.hiddenStates(visual)).item( + Bool.self)) + XCTAssertTrue(lazy.onDemandComponents[0].isLoaded) + XCTAssertEqual(lazy.parameters().flattened().map(\.0), paths) + let videoModel = Qwen3VL(config) + try loadWeights( + modelDirectory: directory, model: videoModel, perLayerQuantization: precision) + let pixels = makeImage() + let video = LMInput( + text: .init( + tokens: MLXArray([Int32(502), 501, 501, 501, 501, 1, 2], [1, 7])), + video: .init(pixels: pixels.pixels, frames: pixels.frames)) + XCTAssertTrue( + arrayEqual(try videoModel.hiddenStates(video), try eager.hiddenStates(video)) + .item(Bool.self)) + XCTAssertTrue(videoModel.onDemandComponents[0].isLoaded) + try loadWeights( + modelDirectory: directory, model: lazy, perLayerQuantization: precision, + componentLoading: .immediate) + XCTAssertEqual( + Set(lazy.parameters().flattened().map(\.0)), + Set(eager.parameters().flattened().map(\.0))) + XCTAssertTrue( + arrayEqual(try lazy.hiddenStates(visual), try eager.hiddenStates(visual)).item( + Bool.self)) + } + } + } + + func testExcludedAndMissingVisionKeepTextUsableAndFailedLoadsCanRetry() throws { + let (directory, config, _) = try embeddingCheckpoint(namespace: "model.visual") + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let complete = try Data(contentsOf: url) + let visual = LMInput( + text: .init(tokens: concatenated([visionStart(), imageRun(), textTokens(4)], axis: 1)), + image: makeImage()) + let excluded = Qwen3VL(config) + try loadWeights(modelDirectory: directory, model: excluded, excludedComponents: [.vision]) + XCTAssertThrowsError(try excluded.hiddenStates(visual)) { error in + XCTAssertTrue(error is OnDemandComponentError) + } + let text = LMInput(tokens: textTokens(4)) + let reference = try excluded.hiddenStates(text).asArray(Float.self) + let lazy = Qwen3VL(config) + try loadWeights(modelDirectory: directory, model: lazy) + let textWeights = try loadArrays(url: url).filter { !$0.key.hasPrefix("model.visual.") } + eval(Array(textWeights.values)) + try save(arrays: textWeights, url: url) + XCTAssertThrowsError(try lazy.hiddenStates(visual)) + XCTAssertFalse(lazy.onDemandComponents[0].isLoaded) + XCTAssertEqual(try lazy.hiddenStates(text).asArray(Float.self), reference) + let textOnly = Qwen3VL(config) + try loadWeights(modelDirectory: directory, model: textOnly) + XCTAssertEqual(try textOnly.hiddenStates(text).asArray(Float.self), reference) + try complete.write(to: url) + _ = try lazy.hiddenStates(visual).asArray(Float.self) + XCTAssertTrue(lazy.onDemandComponents[0].isLoaded) + } + + func testHiddenStatesMatchVocabularyProjectionForTextAndPixels() throws { + let model = try makeTinyModel() + let text = textTokens(8) + let visual = concatenated([visionStart(), imageRun(), text], axis: 1) + let inputs = [ + LMInput(tokens: text), LMInput(text: .init(tokens: visual), image: makeImage()), + ] + let weights = Dictionary(uniqueKeysWithValues: model.parameters().flattened()) + let head = try XCTUnwrap(weights["language_model.model.embed_tokens.weight"]) + for input in inputs { + let hidden = try model.hiddenStates(input) + XCTAssertEqual(hidden.shape, [1, input.text.tokens.dim(1), 64]) + let projected = matmul(hidden[0..., (hidden.dim(1) - 1)..., 0...], head.T) + let (logits, _) = try lastLogits( + model.prepare( + input, cache: model.newCache(parameters: nil), state: nil, prefill: .init())) + // TF32 matmuls measured 2.8e-3 here. + XCTAssertLessThan( + maxAbsDiff(projected, logits), + MatmulPrecision.tolerance(float32: 1e-4, reduced: 1e-2)) + let repeated = try model.hiddenStates(input) + XCTAssertLessThan(maxAbsDiff(hidden, repeated), 1e-6) + } + } + + func testHiddenStatesRejectPaddedAndBatchedInputs() throws { + let model = try makeTinyModel() + XCTAssertThrowsError(try model.hiddenStates(LMInput(tokens: textTokens(0)))) + XCTAssertThrowsError( + try model.hiddenStates(LMInput(tokens: broadcast(textTokens(4), to: [2, 4])))) + let mask = MLXArray([Int32(1), 1, 1, 0], [1, 4]) + XCTAssertThrowsError( + try model.hiddenStates(LMInput(text: .init(tokens: textTokens(4), mask: mask)))) + } + + private struct EmbeddingTokenizer: Tokenizer { + var oversized = false + var bosToken: String? { nil } + var eosToken: String? { nil } + var unknownToken: String? { nil } + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + let tokens = + oversized + ? Array(repeating: 1, count: 32_769) + : text.split(separator: ",").compactMap { Int($0) } + return tokens + (addSpecialTokens ? [4] : []) + } + + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map(String.init).joined(separator: ",") + } + + func convertTokenToId(_ token: String) -> Int? { nil } + func convertIdToToken(_ id: Int) -> String? { nil } + func applyChatTemplate( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [1, 2, 3] } + } + + private struct EmbeddingTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { EmbeddingTokenizer() } + } + + func testLocalEmbeddingLoadsTextWithoutVisionWeightsOrProcessorConfiguration() async throws { + let (directory, config, _) = try embeddingCheckpoint() + defer { try? FileManager.default.removeItem(at: directory) } + try JSONEncoder().encode(config).write(to: directory.appendingPathComponent("config.json")) + let url = directory.appendingPathComponent("model.safetensors") + let text = try loadArrays(url: url).filter { $0.key.hasPrefix("language_model.") } + eval(Array(text.values)) + try save(arrays: text, url: url) + let embeddings = try await Qwen3VLEmbedding( + modelDirectory: directory, tokenizerLoader: EmbeddingTokenizerLoader()) + let vector = try await embeddings.embed(.init(text: "Swift")) + XCTAssertEqual(vector.count, 64) + XCTAssertEqual(vector.reduce(0) { $0 + $1 * $1 }, 1, accuracy: 1e-5) + let excluded = try await Qwen3VLEmbedding( + modelDirectory: directory, tokenizerLoader: EmbeddingTokenizerLoader(), + excludedComponents: [.vision]) + let excludedVector = try await excluded.embed(.init(text: "Swift")) + XCTAssertEqual(vector, excludedVector) + let image = CIImage(color: .black).cropped(to: CGRect(x: 0, y: 0, width: 32, height: 32)) + do { + _ = try await excluded.embed(.init(images: [.ciImage(image)])) + XCTFail("Excluded vision must fail before reading processor configuration") + } catch OnDemandComponentError.unavailable(let component) { + XCTAssertEqual(component, .vision) + } + } + + func testSharedFactoryLoadsQwenAndHonorsVisionExclusion() async throws { + let (directory, config, _) = try embeddingCheckpoint() + defer { try? FileManager.default.removeItem(at: directory) } + try JSONEncoder().encode(config).write(to: directory.appendingPathComponent("config.json")) + var configuration = ResolvedModelConfiguration(directory: directory) + configuration.excludedComponents = [.vision] + let embedder = try await MultimodalEmbeddingFactory.shared._load( + configuration: configuration, tokenizerLoader: EmbeddingTokenizerLoader()) + XCTAssertTrue(embedder is Qwen3VLEmbedding) + let modalities = await embedder.supportedModalities + XCTAssertEqual(modalities, [.text]) + let vectors = try await embedder.embed([.init(text: "Swift")], task: .document) + XCTAssertEqual(vectors.count, 1) + XCTAssertEqual(vectors[0].count, 64) + do { + _ = try await embedder.embed([.init([.audio(.url(directory))])], task: .none) + XCTFail("Unsupported media must be rejected") + } catch Qwen3VLEmbedding.Error.unsupportedMedia {} + } + + func testEmbeddingPipelineLoadsOnDemandVisionBeforeItsCustomForwardPass() async throws { + let (directory, config, precision) = try embeddingCheckpoint( + namespace: "model.visual", quantized: true) + defer { try? FileManager.default.removeItem(at: directory) } + let model = Qwen3VL(config) + try await loadWeights( + modelDirectory: directory, model: model, perLayerQuantization: precision) + let holder = model.onDemandComponents[0] + let container = ModelContainer( + context: ModelContext( + configuration: .init(id: "fixture"), model: model, + processor: EmbeddingProcessor(requests: EmbeddingRequests()), + tokenizer: EmbeddingTokenizer())) + let embeddings = try await Qwen3VLEmbedding(container: container) + _ = try await embeddings.embed(.init(text: "Swift")) + XCTAssertFalse(holder.isLoaded) + let image = CIImage(color: .black).cropped(to: CGRect(x: 0, y: 0, width: 32, height: 32)) + let vector = try await embeddings.embed(.init(images: [.ciImage(image)])) + XCTAssertTrue(holder.isLoaded) + XCTAssertEqual(vector.reduce(0) { $0 + $1 * $1 }, 1, accuracy: 1e-5) + } + + private actor EmbeddingRequests { + struct Request: Sendable { + let instruction: String + let imageCount: Int + let minPixels: Int? + let maxPixels: Int? + let partTypes: [String] + } + private(set) var values: [Request] = [] + func record(_ request: Request) { values.append(request) } + } + + private static func embeddingImage() -> LMInput.ProcessedImage { + LMInput.ProcessedImage(pixels: MLX.ones([16, 3 * 2 * 16 * 16]), frames: [THW(1, 4, 4)]) + } + + private struct EmbeddingProcessor: UserInputProcessor { + let requests: EmbeddingRequests + + func prepare(input: UserInput) async throws -> LMInput { + guard case .messages(let messages) = input.prompt, + let content = messages.last?["content"] as? [[String: any Sendable]] + else { throw Qwen3VLEmbedding.Error.emptyInput } + let system = + (messages.first?["role"] as? String) == "system" + ? messages.first?["content"] as? [[String: String]] : nil + await requests.record( + .init( + instruction: system?.first?["text"] ?? "", imageCount: input.images.count, + minPixels: input.processing.minPixels, maxPixels: input.processing.maxPixels, + partTypes: content.compactMap { $0["type"] as? String })) + let text = + content.contains { ($0["text"] as? String) == "second" } + ? [5, 6, 7] : [1, 2, 3] + if input.images.isEmpty { + return LMInput(tokens: MLXArray(text).expandedDimensions(axis: 0)) + } + let tokens = [502, 500, 500, 500, 500] + text + let image = Qwen3VLContinuationTests.embeddingImage() + return LMInput( + text: .init(tokens: MLXArray(tokens).expandedDimensions(axis: 0)), image: image) + } + } + + func testEmbeddingPipelinePoolsPostprocessorTokenForTextAndPixelsInInputOrder() async throws { + let model = try makeTinyModel() + model.train(false) + var expected: [[Float]] = [] + let tokens = [[1, 2, 3, 4], [502, 500, 500, 500, 500, 1, 2, 3, 4], [5, 6, 7, 4]] + for (index, row) in tokens.enumerated() { + let input = LMInput( + text: .init(tokens: MLXArray(row).expandedDimensions(axis: 0)), + image: index == 1 ? Self.embeddingImage() : nil) + let last = try model.hiddenStates(input)[0, -1, 0...].asType(.float32) + let normalized = last / MLXLinalg.norm(last) + eval(normalized) + expected.append(normalized.asArray(Float.self)) + } + let requests = EmbeddingRequests() + let container = ModelContainer( + context: ModelContext( + configuration: .init(id: "fixture"), model: model, + processor: EmbeddingProcessor(requests: requests), tokenizer: EmbeddingTokenizer())) + let embedder = try await Qwen3VLEmbedding(container: container) + let image = CIImage(color: .black).cropped(to: CGRect(x: 0, y: 0, width: 32, height: 32)) + let actual = try await embedder.embed( + [.init(text: "first"), .init(images: [.ciImage(image)]), .init(text: "second")], + instruction: "Retrieve matching images and text.") + XCTAssertEqual(actual.count, expected.count) + for (row, reference) in zip(actual, expected) { + XCTAssertEqual(row.count, 64) + XCTAssertLessThan(zip(row, reference).map { abs($0 - $1) }.max() ?? 1, 1e-5) + XCTAssertEqual(row.reduce(0) { $0 + $1 * $1 }, 1, accuracy: 1e-5) + } + let recorded = await requests.values + XCTAssertEqual(recorded.map(\.imageCount), [0, 1, 0]) + XCTAssertTrue( + recorded.allSatisfy { $0.instruction == "Retrieve matching images and text." }) + XCTAssertTrue(recorded.allSatisfy { $0.minPixels == 4_096 && $0.maxPixels == 1_310_720 }) + let repeated = try await embedder.embed(.init(text: "first")) + XCTAssertLessThan(zip(repeated, expected[0]).map { abs($0 - $1) }.max() ?? 1, 1e-5) + let defaults = await requests.values + XCTAssertEqual(defaults.last?.instruction, Qwen3VLEmbedding.defaultInstruction) + } + + func testSharedEmbeddingPreservesPartOrderAndOmitsNoneInstruction() async throws { + let requests = EmbeddingRequests() + let container = ModelContainer( + context: ModelContext( + configuration: .init(id: "fixture"), model: try makeTinyModel(), + processor: EmbeddingProcessor(requests: requests), tokenizer: EmbeddingTokenizer())) + let embedder: any MultimodalEmbedding = try await Qwen3VLEmbedding(container: container) + let image = CIImage(color: .black).cropped(to: CGRect(x: 0, y: 0, width: 32, height: 32)) + _ = try await embedder.embed( + [.init([.text("first"), .image(.ciImage(image)), .text("last")])], task: .none) + let recorded = await requests.values + XCTAssertEqual(recorded[0].partTypes, ["text", "image", "text"]) + XCTAssertEqual(recorded[0].instruction, "") + } + + func testEmbeddingPipelineRejectsEmptyInputBeforePreparation() async throws { + let requests = EmbeddingRequests() + let container = ModelContainer( + context: ModelContext( + configuration: .init(id: "fixture"), model: try makeTinyModel(), + processor: EmbeddingProcessor(requests: requests), tokenizer: EmbeddingTokenizer())) + let embedder = try await Qwen3VLEmbedding(container: container) + let empty = try await embedder.embed([Qwen3VLEmbedding.Input]()) + XCTAssertTrue(empty.isEmpty) + do { + _ = try await embedder.embed(.init(text: " \n")) + XCTFail("Empty input must be rejected") + } catch Qwen3VLEmbedding.Error.emptyInput {} + let count = await requests.values.count + XCTAssertEqual(count, 0) + } + + func testEmbeddingPipelineRejectsContextOverflowBeforeModelForward() async throws { + let container = ModelContainer( + context: ModelContext( + configuration: .init(id: "fixture"), model: try makeTinyModel(), + processor: EmbeddingProcessor(requests: EmbeddingRequests()), + tokenizer: EmbeddingTokenizer(oversized: true))) + let embedder = try await Qwen3VLEmbedding(container: container) + do { + _ = try await embedder.embed(.init(text: "long")) + XCTFail("Context overflow must be rejected") + } catch Qwen3VLEmbedding.Error.contextExceeded {} + } + // MARK: - Warm continuation /// A warm continuation (prefix already in the cache, remainder prefilled on diff --git a/Tests/MLXLMTests/Qwen3VLProcessorTests.swift b/Tests/MLXLMTests/Qwen3VLProcessorTests.swift index 401ee22c0..6077d6190 100644 --- a/Tests/MLXLMTests/Qwen3VLProcessorTests.swift +++ b/Tests/MLXLMTests/Qwen3VLProcessorTests.swift @@ -19,7 +19,7 @@ final class Qwen3VLProcessorTests: XCTestCase { func encode(text: String, addSpecialTokens: Bool) -> [Int] { if text.contains("<|vision_start|>") { - return [90, 91, 92] + return [90, 91, 92] + (addSpecialTokens ? [99] : []) } return [1, 2, 3] } @@ -112,6 +112,7 @@ final class Qwen3VLProcessorTests: XCTestCase { for (name, processor) in processors { let prepared = try await processor.prepare(input: input) + XCTAssertEqual(prepared.text.tokens.asArray(Int32.self), [90, 91, 92], name) XCTAssertNil(prepared.text.mask, name) XCTAssertNotNil(prepared.image, name) XCTAssertNil(prepared.video, name)