diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 0a3aeb04e3..6fb3900d6e 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -1,6 +1,8 @@ name: Build and Test -on: pull_request +on: + pull_request: + workflow_dispatch: permissions: contents: read diff --git a/IntegrationTesting/IntegrationTestingTests/AttachmentLabelTemplateIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/AttachmentLabelTemplateIntegrationTests.swift new file mode 100644 index 0000000000..8610e3525b --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/AttachmentLabelTemplateIntegrationTests.swift @@ -0,0 +1,244 @@ +// Copyright © 2026 Apple Inc. + +import CoreImage +import Foundation +import HuggingFace +import MLX +import MLXHuggingFace +import MLXLMCommon +import MLXVLM +import Testing +import Tokenizers + +#if FoundationModelsIntegration && canImport(FoundationModels, _version: 2) +import FoundationModels + +@testable import MLXFoundationModels +#endif + +private let templateDownloader: any Downloader = #hubDownloader() +private let templateTokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader() + +struct LabeledPromptFamily: Sendable, CustomStringConvertible { + let family: String + let modelID: String + let revision: String + let generator: any MessageGenerator + let placeholder: String + + var description: String { family } +} + +/// SmolVLM2 is left out. Its chat template writes the content as one string. A message +/// with an image then renders as a printed list of dictionaries, with or without labels. +let labeledPromptFamilies: [LabeledPromptFamily] = [ + .init( + family: "Qwen2VL", modelID: "mlx-community/Qwen2-VL-2B-Instruct-4bit", + revision: "01af461cdb9574acc09084a0ef94e216e142b085", + generator: Qwen2VLMessageGenerator(), + placeholder: "<|vision_start|><|image_pad|><|vision_end|>"), + .init( + family: "Qwen25VL", modelID: "mlx-community/Qwen2.5-VL-3B-Instruct-4bit", + revision: "46d4cf06a06ffc1a766c214174f9cbed2f45bcab", + generator: Qwen2VLMessageGenerator(), + placeholder: "<|vision_start|><|image_pad|><|vision_end|>"), + .init( + family: "Qwen3VL", modelID: "mlx-community/Qwen3-VL-2B-Instruct-4bit", + revision: "9c4f5209e57b31f4b9dfba735de3fb983739c9cc", + generator: Qwen3VLMessageGenerator(), + placeholder: "<|vision_start|><|image_pad|><|vision_end|>"), + .init( + family: "Gemma4", modelID: "mlx-community/gemma-4-e4b-it-4bit", + revision: "475b9088d29754a3379866cf5aeb6b41acd313c2", + generator: Gemma4MessageGenerator(), placeholder: "<|image|>"), + .init( + family: "Gemma3", modelID: "mlx-community/gemma-3-4b-it-qat-4bit", + revision: "3d9ef289111449933c22761961f16a5df237ce2a", + generator: Qwen2VLMessageGenerator(), placeholder: ""), + .init( + family: "GlmOcr", modelID: "mlx-community/GLM-OCR-4bit", + revision: "97f587506984cc92fa69b2694b4128e53db6b081", + generator: GlmOcrMessageGenerator(), + placeholder: "<|begin_of_image|><|image|><|end_of_image|>"), + .init( + family: "Mistral3", + modelID: "mlx-community/Mistral-Small-3.1-24B-Instruct-2503-4bit", + revision: "46135ef3c556bfed61013d8789bd26af02e416c4", + generator: Mistral3MessageGenerator(), placeholder: "[IMG]"), + .init( + family: "FastVLM", modelID: "mlx-community/FastVLM-0.5B-bf16", + revision: "81ffe929046666c43de53691147b1669ba0f3a4c", + generator: FastVLMMessageGenerator(), placeholder: ""), + .init( + family: "LFM2VL", modelID: "mlx-community/LFM2-VL-1.6B-4bit", + revision: "be587c055231b0905e846f2c99803dd6d7f33a7a", + generator: Qwen2VLMessageGenerator(), placeholder: ""), + .init( + family: "MuseGlimmer", modelID: "mlx-community/Muse-Glimmer-30B-4bit", + revision: "3e7677d7a40d348a3daba263a2b1c0aa41910710", + generator: Qwen2VLMessageGenerator(), placeholder: "<|patch|>"), +] + +@Suite(.serialized) +struct AttachmentLabelTemplateIntegrationTests { + + static let prose = "which one is blue?" + + private func tokenizer(for family: LabeledPromptFamily) async throws -> any MLXLMCommon + .Tokenizer + { + let directory = try await templateDownloader.download( + id: family.modelID, + revision: family.revision, + matching: ["*.json", "*.jinja"], + useLatest: false, + progressHandler: { _ in }) + return try await templateTokenizerLoader.load(from: directory) + } + + private func rendered( + _ family: LabeledPromptFamily, content: [[String: String]] + ) async throws -> String { + let tokenizer = try await tokenizer(for: family) + let messages: [MLXLMCommon.Message] = [["role": "user", "content": content]] + let tokens = try tokenizer.applyChatTemplate(messages: messages) + return tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) + } + + @Test(arguments: labeledPromptFamilies) + func labelLandsBesideItsImage(family: LabeledPromptFamily) async throws { + let message = Chat.Message.user( + Self.prose, + images: [ + .url(URL(fileURLWithPath: "/tmp/a.png"), label: "A"), + .url(URL(fileURLWithPath: "/tmp/b.png"), label: "B"), + ]) + let parts = try #require( + family.generator.generate(message: message)["content"] as? [[String: String]]) + let prompt = try await rendered(family, content: parts) + + #expect( + prompt.contains("[A]" + family.placeholder), + "\(family): first label must precede its own image placeholder; got: \(prompt)") + #expect( + prompt.contains("[B]" + family.placeholder), + "\(family): second label must precede its own image placeholder; got: \(prompt)") + #expect( + prompt.contains(Self.prose), + "\(family): the caller's text must survive; got: \(prompt)") + #expect( + prompt.components(separatedBy: family.placeholder).count - 1 == 2, + "\(family): expected one placeholder per image; got: \(prompt)") + } + + @Test(arguments: labeledPromptFamilies) + func noSeparatorReachesThePrompt(family: LabeledPromptFamily) async throws { + let message = Chat.Message.user( + Self.prose, + images: [ + .url(URL(fileURLWithPath: "/tmp/a.png"), label: "A"), + .url(URL(fileURLWithPath: "/tmp/b.png"), label: "B"), + ]) + let parts = try #require( + family.generator.generate(message: message)["content"] as? [[String: String]]) + let prompt = try await rendered(family, content: parts) + + #expect( + !prompt.contains("\u{2060}"), + "\(family): a word joiner reached the prompt; got: \(prompt)") + #expect( + !prompt.contains("\u{200B}"), + "\(family): a zero width space reached the prompt; got: \(prompt)") + } + + @Test(arguments: labeledPromptFamilies) + func noLabelTrailsItsImage(family: LabeledPromptFamily) async throws { + let message = Chat.Message.user( + Self.prose, + images: [ + .url(URL(fileURLWithPath: "/tmp/a.png"), label: "A"), + .url(URL(fileURLWithPath: "/tmp/b.png"), label: "B"), + ]) + let parts = try #require( + family.generator.generate(message: message)["content"] as? [[String: String]]) + let prompt = try await rendered(family, content: parts) + + #expect( + !prompt.contains(family.placeholder + "[A]"), + "\(family): the first label must not follow a placeholder; got: \(prompt)") + } + + /// The label `IMG` renders as `[IMG]`, and `Mistral3VLMProcessor` splits the decoded + /// prompt on that text. + @Test func mistral3LabelDoesNotAddAnImageBlock() async throws { + let directory = try await templateDownloader.download( + id: "mlx-community/Ministral-3-3B-Instruct-2512-4bit", + revision: "a962dcb09eee4169c890e544c9eb938f1113fdee", + matching: ["*.json", "*.jinja"], + useLatest: false, + progressHandler: { _ in }) + let tokenizer = try await templateTokenizerLoader.load(from: directory) + let processor = try await VLMProcessorTypeRegistry.shared.createModel( + configuration: try Data( + contentsOf: directory.appending(component: "processor_config.json")), + processorType: "Mistral3Processor", tokenizer: tokenizer) + let imageTokenID = try #require(tokenizer.convertTokenToId("[IMG]")) + let image = CIImage(color: .red).cropped(to: CGRect(x: 0, y: 0, width: 64, height: 64)) + + func imageTokenCount(label: String?) async throws -> Int { + let input = UserInput(chat: [ + .user(Self.prose, images: [.ciImage(image, label: label)]) + ]) + let prepared = try await processor.prepare(input: input) + return prepared.text.tokens.asType(.int32).asArray(Int32.self) + .filter { Int($0) == imageTokenID }.count + } + + let unlabeled = try await imageTokenCount(label: nil) + let labeled = try await imageTokenCount(label: "IMG") + #expect(unlabeled > 0, "the unlabeled prompt must carry one image block") + #expect( + labeled == unlabeled, + "one image must give one image block; got \(labeled) image tokens, expected \(unlabeled)" + ) + } + + #if FoundationModelsIntegration && canImport(FoundationModels, _version: 2) + + @Test(arguments: labeledPromptFamilies) + func theFamilysOwnPlaceholderIsRefusedAsALabel(family: LabeledPromptFamily) async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let tokenizer = try await tokenizer(for: family) + let entry = Transcript.Entry.prompt( + Transcript.Prompt( + segments: [.text(Transcript.TextSegment(content: Self.prose))], + responseFormat: nil)) + + // Check each token alone, so the middle token of a three-token placeholder gets + // its own check. GLM-OCR does not flag that token as special. + for marker in family.placeholder.markerTokens { + let attachment = TranscriptConverter.LabeledAttachment(label: marker, entry: entry) + #expect(throws: LanguageModelError.self) { + try AttachmentLabelValidator.default.validate([attachment], with: tokenizer) + } + } + } + + #endif +} + +extension String { + fileprivate var markerTokens: [String] { + var tokens: [String] = [] + var current = "" + for character in self { + current.append(character) + if character == ">" || character == "]" { + tokens.append(current) + current = "" + } + } + if !current.isEmpty { tokens.append(current) } + return tokens + } +} diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GenerableRoundTripTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GenerableRoundTripTests.swift index 8d6663d932..20c58ec4a0 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GenerableRoundTripTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GenerableRoundTripTests.swift @@ -280,13 +280,13 @@ struct GenerableRoundTripTests { kvBits: Int? = nil ) async throws -> String { try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: jsonSchema, fastForward: true, hostTokenizer: context.tokenizer @@ -320,7 +320,7 @@ struct GenerableRoundTripTests { context: context, constraint: constraint, maxTokens: maxTokens, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), kvBits: kvBits, completionReserve: completionReserve, hardReserve: hardReserve, diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/EmitStopSignalTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/EmitStopSignalTests.swift index 16502f0549..e5b6a04de7 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/EmitStopSignalTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/EmitStopSignalTests.swift @@ -53,12 +53,12 @@ struct EmitStopSignalTests { let container = try await loadTestModelContainer(id: TestFixtures.defaultModelID) try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: TestFixtures.defaultModelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -83,7 +83,7 @@ struct EmitStopSignalTests { context: context, constraint: constraint, maxTokens: 128, - vocabSize: Int(xgTokenizer.vocabSize) + vocabSize: Int(grammarTokenizer.vocabSize) ) { _ in callCount += 1 if firstFalseAt != nil { diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/FastForwardTokenizationDisagreementTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/FastForwardTokenizationDisagreementTests.swift index d2e79aab82..195be23410 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/FastForwardTokenizationDisagreementTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/Grammar/FastForwardTokenizationDisagreementTests.swift @@ -162,7 +162,7 @@ struct FastForwardTokenizationDisagreementTests { } try await qwenContainer.perform { qwenContext in - let xgTokenizer = try GrammarTokenizer( + let grammarTokenizer = try GrammarTokenizer( vocab: seeds.vocab, vocabType: seeds.vocabType, eosTokenId: seeds.eosTokenId @@ -173,7 +173,7 @@ struct FastForwardTokenizationDisagreementTests { // Gemma-bound matcher does not have in its current mask. let grammar = "root ::= \"\(Self.forcedPayload)\"\n" let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, grammar: grammar, fastForward: true, hostTokenizer: qwenContext.tokenizer diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationBenchmarkTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationBenchmarkTests.swift index a258f668df..a042d065e1 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationBenchmarkTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationBenchmarkTests.swift @@ -322,13 +322,13 @@ struct GuidedGenerationBenchmarkTests { let container = try await loadTestModelContainer(id: TestFixtures.defaultModelID) let modelID = TestFixtures.defaultModelID - let (xgTokenizer, hostTokenizer): (GrammarTokenizer, any Tokenizer) = + let (grammarTokenizer, hostTokenizer): (GrammarTokenizer, any Tokenizer) = try await container.perform { context in - let xg = try await MLXLanguageModel.makeXGTokenizer( + let tokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) - return (xg, context.tokenizer) + return (tokenizer, context.tokenizer) } let schema = """ @@ -349,7 +349,7 @@ struct GuidedGenerationBenchmarkTests { for _ in 0 ..< iterations { let start = ContinuousClock.now let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: hostTokenizer @@ -447,12 +447,12 @@ struct GuidedGenerationBenchmarkTests { modelID: String = TestFixtures.defaultModelID ) async throws -> RunResult { try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: Self.benchmarkSchema, fastForward: true, hostTokenizer: context.tokenizer @@ -472,7 +472,7 @@ struct GuidedGenerationBenchmarkTests { context: context, constraint: constraint, maxTokens: Self.benchmarkMaxTokens, - vocabSize: Int(xgTokenizer.vocabSize) + vocabSize: Int(grammarTokenizer.vocabSize) ) { text in charCount += text.count deltaCount += 1 diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationTests.swift index 78af325940..82060f8db8 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/GuidedGenerationTests.swift @@ -324,12 +324,12 @@ struct GuidedGenerationTests { let container = try await loadTestModelContainer(id: modelID) let raw: String = try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -364,7 +364,7 @@ struct GuidedGenerationTests { context: context, constraint: constraint, maxTokens: maxTokens, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: reserve, hardReserve: hardReserve, closingBias: closingBias, @@ -490,12 +490,12 @@ struct GuidedGenerationTests { let schema = Self.unboundedSchema let raw: String = try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -536,7 +536,7 @@ struct GuidedGenerationTests { context: context, constraint: constraint, maxTokens: 256, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: reserve, hardReserve: hardReserve, closingBias: closingBias, diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/HardReserveStressTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/HardReserveStressTests.swift index 40f7691e13..89dfbf2f5c 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/HardReserveStressTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/HardReserveStressTests.swift @@ -158,12 +158,12 @@ struct HardReserveStressTests { let container = try await loadTestModelContainer(id: modelID) let raw: String = try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -208,7 +208,7 @@ struct HardReserveStressTests { context: context, constraint: constraint, maxTokens: maxTokens, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: softReserve, hardReserve: hardReserve, closingBias: closingBias, diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MaxTokenTruncationTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MaxTokenTruncationTests.swift index 05cd656d82..94ef012297 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MaxTokenTruncationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MaxTokenTruncationTests.swift @@ -43,13 +43,13 @@ struct MaxTokenTruncationTests { } """ - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: TestFixtures.defaultModelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: complexSchema, fastForward: true, hostTokenizer: context.tokenizer @@ -68,7 +68,7 @@ struct MaxTokenTruncationTests { context: context, constraint: constraint, maxTokens: 5, - vocabSize: Int(xgTokenizer.vocabSize) + vocabSize: Int(grammarTokenizer.vocabSize) ) { _ in true } } } @@ -122,7 +122,7 @@ struct MaxTokenTruncationTests { let container = try await loadTestModelContainer(id: TestFixtures.defaultModelID) try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: TestFixtures.defaultModelID, tokenizer: context.tokenizer ) @@ -138,7 +138,7 @@ struct MaxTokenTruncationTests { """ let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: arraySchema, fastForward: true, hostTokenizer: context.tokenizer @@ -157,7 +157,7 @@ struct MaxTokenTruncationTests { context: context, constraint: constraint, maxTokens: 3, - vocabSize: Int(xgTokenizer.vocabSize) + vocabSize: Int(grammarTokenizer.vocabSize) ) { _ in true } } } diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MultiModelGuidedGenerationTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MultiModelGuidedGenerationTests.swift index 1fa8947a37..738d1b3de2 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MultiModelGuidedGenerationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/MultiModelGuidedGenerationTests.swift @@ -120,12 +120,12 @@ struct MultiModelGuidedGenerationTests { """ let raw: String = try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -155,7 +155,7 @@ struct MultiModelGuidedGenerationTests { context: context, constraint: constraint, maxTokens: 1024, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: reserve, closingBias: closingBias, whitespaceBias: whitespaceBias, @@ -246,12 +246,12 @@ struct MultiModelGuidedGenerationTests { """ let raw: String = try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer @@ -284,7 +284,7 @@ struct MultiModelGuidedGenerationTests { context: context, constraint: constraint, maxTokens: 4096, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: reserve, closingBias: closingBias, whitespaceBias: whitespaceBias, @@ -438,12 +438,12 @@ struct MultiModelGuidedGenerationTests { let modelID = Self.gemmaModelID let container = try await loadTestModelContainer(id: modelID) try await container.perform { context in - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) let constraint = try GrammarConstraint( - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, jsonSchema: schema, fastForward: true, hostTokenizer: context.tokenizer diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/PrewarmGrammarTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/PrewarmGrammarTests.swift index 50226193e8..8a6a224d80 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/PrewarmGrammarTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/GuidedGeneration/PrewarmGrammarTests.swift @@ -13,7 +13,7 @@ import FoundationModels struct PrewarmGrammarTests { @Test - func prewarmCreatesXGTokenizer() async throws { + func prewarmCreatesGrammarTokenizer() async throws { guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } let model = makeTestModel(TestFixtures.defaultModelID) let executor = try makeMLXExecutor(for: model) @@ -26,7 +26,7 @@ struct PrewarmGrammarTests { // Assert the genuine cache hit, not merely that a later respond works // (a guided respond succeeds with or without warmup — only the seam // proves warmUp did the pre-creation). - let cached = await MLXLanguageModel.hasCachedXGTokenizer(modelID: model.modelID) + let cached = await MLXLanguageModel.hasCachedGrammarTokenizer(modelID: model.modelID) #expect(cached, "warmUp should pre-create the GrammarTokenizer") // And a guided generation still succeeds end-to-end after warmUp. diff --git a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/ToolCalling/MultiTurnToolCallingTests.swift b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/ToolCalling/MultiTurnToolCallingTests.swift index 622c3e38c1..1e2be3478c 100644 --- a/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/ToolCalling/MultiTurnToolCallingTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MLXFoundationModelsIntegration/ToolCalling/MultiTurnToolCallingTests.swift @@ -249,7 +249,7 @@ struct MultiTurnToolCallingTests { let transcript = try continuationTranscript() let decoded = try await container.perform { context in - let messages = TranscriptConverter.mlxMessages(for: transcript) + let messages = try TranscriptConverter.mlxMessages(for: transcript) let raw = DefaultMessageGenerator().generate(messages: messages) let tokens = try context.tokenizer.applyChatTemplate(messages: raw) return context.tokenizer.decode(tokenIds: tokens) @@ -272,7 +272,7 @@ struct MultiTurnToolCallingTests { let transcript = try structuredContinuationTranscript() let decoded = try await container.perform { context in - let messages = TranscriptConverter.mlxMessages(for: transcript) + let messages = try TranscriptConverter.mlxMessages(for: transcript) let raw = DefaultMessageGenerator().generate(messages: messages) let tokens = try context.tokenizer.applyChatTemplate(messages: raw) return context.tokenizer.decode(tokenIds: tokens) diff --git a/IntegrationTesting/IntegrationTestingTests/Qwen35CheckpointIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/Qwen35CheckpointIntegrationTests.swift new file mode 100644 index 0000000000..43a7e6d447 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/Qwen35CheckpointIntegrationTests.swift @@ -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) 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) + } +} diff --git a/IntegrationTesting/IntegrationTestingTests/VisionIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/VisionIntegrationTests.swift index 043e78dd33..9449486382 100644 --- a/IntegrationTesting/IntegrationTestingTests/VisionIntegrationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/VisionIntegrationTests.swift @@ -10,21 +10,21 @@ import Testing #if FoundationModelsIntegration && canImport(FoundationModels, _version: 2) -/// Opt-in end-to-end VLM test: drives a real `Qwen3-VL-4B-Instruct-4bit` through -/// the FoundationModels adapter with a labeled image attachment and `.vision` -/// declared, proving the labeled-attachment path reaches the already -/// multimodal MLX pipeline. -/// -/// The input is a synthetic solid-color square built in-memory (no binary -/// fixture); the test is parameterized over two colors and asserts the model -/// names the matching color as a whole word. Two colors give an implicit -/// negative control — a model that always answers "red" fails the blue case — -/// and word-level matching keeps "colored"/"coloured" from satisfying a color -/// name. This keeps the adapter end-to-end coverage while removing the -/// photographic fixture. -/// +let labeledVisionModels = [ + "mlx-community/Qwen2.5-VL-7B-Instruct-4bit", + "mlx-community/gemma-4-e4b-it-4bit", +] + +@available(iOS 27.0, macOS 27.0, visionOS 27.0, *) +@Generable +struct ColorReport { + var image: ImageReference + var color: String +} + /// Skipped unless `MLX_RUN_VLM_INTEGRATION=1`, so default CI never downloads /// multi-GB weights; run on Apple silicon on demand. +/// If you run `xcodebuild`, prefix the variable with `TEST_RUNNER_`, or every test is skipped. /// /// The OS gate is an in-body `guard #available` rather than an `@available` /// on the suite: the swift-testing `@Suite`/`@Test` macros reject an @@ -50,11 +50,13 @@ struct VisionIntegrationTests { func namesImageColor(color: TestColor) async throws { guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } let model = makeTestModel( - "mlx-community/Qwen3-VL-4B-Instruct-4bit", + "mlx-community/Qwen2.5-VL-7B-Instruct-4bit", capabilities: [.vision]) let session = LanguageModelSession(model: model, tools: [], instructions: nil) let image = VisionTestImages.solidColor(color.ciColor) - let response = try await session.respond { + let response = try await session.respond( + options: GenerationOptions(samplingMode: .greedy) + ) { "What color is this image? Reply with just the color name." Attachment(image).label("color") } @@ -68,6 +70,77 @@ struct VisionIntegrationTests { words.contains(color.rawValue), "expected the model to name the color \(color.rawValue); got: \(response.content)") } + + @Test(arguments: labeledVisionModels) + func namesTheLabelOfTheRequestedImage(modelID: String) async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let model = makeTestModel(modelID, capabilities: [.vision]) + let session = LanguageModelSession(model: model, tools: [], instructions: nil) + + let response = try await session.respond( + options: GenerationOptions(samplingMode: .greedy) + ) { + "Which label goes with the blue image? Reply with only the label." + Attachment(VisionTestImages.solidColor(.red)).label("Photo_A1B2C3") + Attachment(VisionTestImages.solidColor(.blue)).label("Photo_D4E5F6") + } + let text = response.content + #expect( + text.contains("D4E5F6"), + "expected the blue image's label; got: \(text)") + #expect( + !text.contains("A1B2C3"), + "expected only the blue image's label; got: \(text)") + } + + @Test(arguments: labeledVisionModels) + func namesTheLabelOfTheMiddleOfThreeImages(modelID: String) async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let model = makeTestModel(modelID, capabilities: [.vision]) + let session = LanguageModelSession(model: model, tools: [], instructions: nil) + + let response = try await session.respond( + options: GenerationOptions(samplingMode: .greedy) + ) { + "Which label goes with the blue image? Reply with only the label." + Attachment(VisionTestImages.solidColor(.red)).label("Photo_A1B2C3") + Attachment(VisionTestImages.solidColor(.blue)).label("Photo_D4E5F6") + Attachment(VisionTestImages.solidColor(.green)).label("Photo_G7H8I9") + } + let text = response.content + #expect( + text.contains("D4E5F6"), + "expected the blue image's label; got: \(text)") + #expect( + !text.contains("A1B2C3") && !text.contains("G7H8I9"), + "expected only the blue image's label; got: \(text)") + } + + @Test(arguments: labeledVisionModels) + func generatedImageReferenceResolvesBackToTheAttachment(modelID: String) async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let model = makeTestModel( + modelID, capabilities: [.vision, .guidedGeneration]) + let session = LanguageModelSession(model: model, tools: [], instructions: nil) + + let response = try await session.respond( + generating: ColorReport.self, + options: GenerationOptions(samplingMode: .greedy) + ) { + "Report which label goes with the blue image, and name its color." + Attachment(VisionTestImages.solidColor(.red)).label("Aurora") + Attachment(VisionTestImages.solidColor(.blue)).label("Beacon") + } + + // A model may write `[Beacon]`, and the SDK resolves that form too, so do not + // require an exact match. + let label = response.content.image.attachmentLabel + #expect( + label.contains("Beacon"), + "expected the blue image's name; got: \(label)") + let resolved = response.content.image.resolved(in: session.transcript) + #expect(resolved != nil, "expected the reference to resolve to an attachment") + } } #endif // FoundationModelsIntegration diff --git a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift index c1f00e9739..14b4e4a952 100644 --- a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift +++ b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift @@ -905,10 +905,10 @@ public enum RerankerIntegrationTests { response.scoreKind == .cosineSimilarity, "\(modelID) must return cosine-similarity scores") try check(response.results.count == 2, "\(modelID) returned an unexpected score count") - // Generated by rerank.py from the pinned MLX checkpoint revision above. The upstream - // checkpoint holds the same bfloat16 weights, so it has to reproduce them too. + // Generated by rerank.py from the pinned MLX checkpoint revision above. + // The source projector is bfloat16; the converted MLX projector is float32. let expectedScores = [-0.156_369_954_347_610_47, 0.402_552_098_035_812_4] - // Quantized kernels can vary slightly with backend evaluation order. + // Allow for projector precision and backend evaluation order. let tolerance = 3e-3 for index in expectedScores.indices { let result = response.results[index] diff --git a/Libraries/MLXEmbedders/README.md b/Libraries/MLXEmbedders/README.md index 10d9c54081..fa30e11622 100644 --- a/Libraries/MLXEmbedders/README.md +++ b/Libraries/MLXEmbedders/README.md @@ -5,13 +5,18 @@ This directory contains ports of popular Encoders / Embedding Models. ## Usage Example ```swift +import Foundation +import MLX import MLXEmbedders -import MLXEmbeddersHuggingFace -import MLXLMTokenizers - -let modelContainer = try await loadModelContainer( - using: TokenizersLoader(), - configuration: .nomic_text_v1_5 +import MLXLMCommon +import MLXHuggingFace +import HuggingFace +import Tokenizers + +let modelContainer = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), + configuration: EmbedderRegistry.nomic_text_v1_5 ) let searchInputs = [ "search_query: Animals in Tropical Climates.", @@ -21,10 +26,9 @@ let searchInputs = [ ] // Generate embeddings -let resultEmbeddings = await modelContainer.perform { - (model: EmbeddingModel, tokenizer: Tokenizer, pooling: Pooling) -> [[Float]] in +let resultEmbeddings = await modelContainer.perform { context -> [[Float]] in let inputs = searchInputs.map { - tokenizer.encode(text: $0, addSpecialTokens: true) + context.tokenizer.encode(text: $0, addSpecialTokens: true) } // Pad to longest let maxLength = inputs.reduce(into: 16) { acc, elem in @@ -36,16 +40,17 @@ let resultEmbeddings = await modelContainer.perform { MLXArray( elem + Array( - repeating: tokenizer.eosTokenId ?? 0, + repeating: context.tokenizer.eosTokenId ?? 0, count: maxLength - elem.count)) }) - let mask = (padded .!= tokenizer.eosTokenId ?? 0) + let mask = (padded .!= context.tokenizer.eosTokenId ?? 0) let tokenTypes = MLXArray.zeros(like: padded) - let result = pooling( - model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask), + let result = context.pooling( + context.model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask), normalize: true, applyLayerNorm: true ) result.eval() + // MLXArray is not Sendable; convert before returning from perform return result.map { $0.asArray(Float.self) } } ``` @@ -53,37 +58,46 @@ let resultEmbeddings = await modelContainer.perform { Load from a local directory: ```swift +import Foundation import MLXEmbedders -import MLXLMTokenizers +import MLXLMCommon +import MLXHuggingFace +import Tokenizers let modelDirectory = URL(filePath: "/path/to/embedder") -let modelContainer = try await loadModelContainer( +let modelContainer = try await EmbedderModelFactory.shared.loadContainer( from: modelDirectory, - using: TokenizersLoader() + using: #huggingFaceTokenizerLoader() ) ``` Use a custom Hugging Face client: ```swift +import Foundation import MLXEmbedders -import MLXEmbeddersHuggingFace -import MLXLMTokenizers - -let hub = HubClient(token: "hf_...") -let modelContainer = try await loadModelContainer( - from: hub, - using: TokenizersLoader(), - configuration: .nomic_text_v1_5 +import MLXLMCommon +import MLXHuggingFace +import HuggingFace +import Tokenizers + +// HubClient comes from the HuggingFace module; wrap it with #hubDownloader(_:). +let hub = HubClient(host: HubClient.defaultHost, bearerToken: "hf_...") +let modelContainer = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(hub), + using: #huggingFaceTokenizerLoader(), + configuration: EmbedderRegistry.nomic_text_v1_5 ) ``` Use a custom downloader: ```swift +import Foundation import MLXEmbedders import MLXLMCommon -import MLXLMTokenizers +import MLXHuggingFace +import Tokenizers struct S3Downloader: Downloader { func download( @@ -98,9 +112,9 @@ struct S3Downloader: Downloader { } } -let modelContainer = try await loadModelContainer( +let modelContainer = try await EmbedderModelFactory.shared.loadContainer( from: S3Downloader(), - using: TokenizersLoader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "my-bucket/my-embedder") ) ``` diff --git a/Libraries/MLXFoundationModels/AttachmentLabelValidator.swift b/Libraries/MLXFoundationModels/AttachmentLabelValidator.swift new file mode 100644 index 0000000000..161201d6a7 --- /dev/null +++ b/Libraries/MLXFoundationModels/AttachmentLabelValidator.swift @@ -0,0 +1,64 @@ +// Copyright © 2026 Apple Inc. + +#if FoundationModelsIntegration +#if canImport(FoundationModels, _version: 2) + +import Foundation +import FoundationModels +import MLXLMCommon + +@available(iOS 27.0, macOS 27.0, visionOS 27.0, *) +struct AttachmentLabelValidator { + + static let `default` = AttachmentLabelValidator() + + func validate( + _ attachments: [TranscriptConverter.LabeledAttachment], + with tokenizer: any MLXLMCommon.Tokenizer + ) throws { + for attachment in attachments { + // Run the tokenizer check first, because its error names the special token. + if let names = tokenizer.specialTokenNames(inImageLabel: attachment.label) { + let named = + names.isEmpty + ? "a tokenizer special token" + : names.map { "`\($0)`" }.joined(separator: ", ") + throw Self.rejection( + attachment, + because: + "holds \(named). This model's tokenizer turns that into a special " + + "token instead of text, which corrupts the prompt's image " + + "placeholders." + ) + } + + if let character = attachment.label.first( + where: UserInput.Image.markerCharacters.contains) + { + throw Self.rejection( + attachment, + because: + "holds `\(character)`. Vision models build their image placeholders " + + "from `<`, `>`, `|`, `[` and `]`. A label that holds one of them can " + + "reach the prompt as a placeholder, and then the model counts more " + + "images than you gave it." + ) + } + } + } + + private static func rejection( + _ attachment: TranscriptConverter.LabeledAttachment, because reason: String + ) -> LanguageModelError { + LanguageModelError.unsupportedTranscriptContent( + LanguageModelError.UnsupportedTranscriptContent( + unsupportedContent: [attachment.entry], + debugDescription: + "The image attachment label \"\(attachment.label)\" \(reason) " + + "Use a label made of ordinary text." + )) + } +} + +#endif // canImport(FoundationModels) +#endif // FoundationModelsIntegration diff --git a/Libraries/MLXFoundationModels/GuidedGeneration/SchemaConverter.swift b/Libraries/MLXFoundationModels/GuidedGeneration/SchemaConverter.swift index 010d2894ee..e5244a15be 100644 --- a/Libraries/MLXFoundationModels/GuidedGeneration/SchemaConverter.swift +++ b/Libraries/MLXFoundationModels/GuidedGeneration/SchemaConverter.swift @@ -4,16 +4,13 @@ #if canImport(FoundationModels, _version: 2) import Foundation -import os import FoundationModels +import MLX /// Converts FoundationModels.GenerationSchema to a JSON string for xgrammar. @available(iOS 27.0, macOS 27.0, visionOS 27.0, *) enum SchemaConverter { - private static let logger = Logger( - subsystem: "com.apple.FoundationModels-MLX", - category: "SchemaConverter" - ) + private static let logger = MLXLogger(label: "SchemaConverter") /// Encodes a GenerationSchema to a standard JSON Schema string. /// diff --git a/Libraries/MLXFoundationModels/MLXDownloadProgress.swift b/Libraries/MLXFoundationModels/MLXDownloadProgress.swift index 4affdce89a..f53ef2211d 100644 --- a/Libraries/MLXFoundationModels/MLXDownloadProgress.swift +++ b/Libraries/MLXFoundationModels/MLXDownloadProgress.swift @@ -9,9 +9,36 @@ import Foundation +/// One reported change to a model's load. +/// +/// Carries only `Sendable` primitives, so a producer on any thread builds one +/// without an isolation check. +enum DownloadProgressUpdate: Sendable { + case started(modelID: String, loadID: UUID) + case progress(modelID: String, loadID: UUID, fraction: Double, completed: Int64, total: Int64) + case ended(modelID: String, loadID: UUID) +} + +/// The shared instance's inbox. +/// +/// A producer yields synchronously from whatever thread it is on, and +/// `AsyncStream` delivers in yield order. Order matters for one model's own +/// updates: an end applied before its start would leave the entry stranded. The +/// buffering policy is stated rather than defaulted, because a policy that drops +/// elements would break both the order and the start-to-end pairing. +private let sharedProgressInbox = AsyncStream.makeStream( + bufferingPolicy: .unbounded) + +/// Reads `MLXDownloadProgress.shared` once, which is what starts the drain. +/// Nothing else does, so without this the inbox buffers every update for the +/// life of the process. A global initializer runs lazily and exactly once. +private let startProgressDrainOnce: Void = { + Task { @MainActor in _ = MLXDownloadProgress.shared } +}() + /// Observable download progress for MLX model loading. /// -/// Tracks whether a model is being downloaded/loaded and reports progress. +/// Tracks one entry per model the adapter is downloading, and aggregates them. /// Shared singleton so any view in the app can observe download state. /// /// Usage: @@ -20,8 +47,10 @@ import Foundation /// var downloadProgress = MLXDownloadProgress.shared /// /// var body: some View { -/// if downloadProgress.isActive { -/// ProgressView(value: downloadProgress.fractionCompleted) +/// ForEach(downloadProgress.activeDownloads) { download in +/// ProgressView(value: download.fractionCompleted) { +/// Text(download.modelID) +/// } /// } /// } /// } @@ -30,124 +59,215 @@ import Foundation @Observable public final class MLXDownloadProgress { - /// Shared singleton instance. - public static let shared = MLXDownloadProgress() + /// One model's download progress. + /// + /// A value, so a consumer reads it once and holds it across an actor hop. + public struct Download: Sendable, Identifiable { - /// Whether a model is currently being downloaded or loaded. - public private(set) var isActive = false + /// The model identifier, as `ModelConfiguration.name` gives it. A + /// repository ID or a path fragment, never a display name. + public let modelID: String - /// Download progress from 0.0 to 1.0. - public private(set) var fractionCompleted: Double = 0 + /// The model identifier, which is what distinguishes one download here. + public var id: String { modelID } - /// The model identifier being downloaded, if any. - public private(set) var modelName: String? + /// Progress from 0.0 to 1.0. + public let fractionCompleted: Double - /// When the current download started. nil when inactive. - /// Consumers can compute elapsed time as `Date.now.timeIntervalSince(startedAt)`. - public private(set) var startedAt: Date? + /// Bytes downloaded so far, from `Progress.completedUnitCount`. + public let completedBytes: Int64 - /// Bytes downloaded so far for the current download. Derived from the - /// underlying `Progress.completedUnitCount`. - public private(set) var completedBytes: Int64 = 0 + /// Total bytes, from `Progress.totalUnitCount`. + public let totalBytes: Int64 - /// Total bytes for the current download. Derived from the underlying - /// `Progress.totalUnitCount`. May be 0 before the first progress report. - public private(set) var totalBytes: Int64 = 0 + /// When the load now running first reported progress for this model. + public let startedAt: Date + + /// Rolling average throughput over the last five seconds of samples. nil + /// until two samples span more than a tenth of a second. + public let throughputBytesPerSecond: Double? + } + + /// Shared singleton instance, and the only instance that drains + /// `sharedProgressInbox`. + public static let shared: MLXDownloadProgress = { + let progress = MLXDownloadProgress() + progress.consume(sharedProgressInbox.stream) + return progress + }() + + /// One entry per model being loaded. An entry whose `download` is nil has + /// started and has not reported yet, so it is not a download. + private var states: [String: State] = [:] + + private struct State { + /// Which load owns this entry. Eviction cancels a load and forgets it at + /// once, so a replacement load can start while the cancelled one is still + /// unwinding a network read. Every update the cancelled load still sends + /// carries its own identifier, and this is what rejects it. + let loadID: UUID + var download: Download? + var samples: [(time: Date, bytes: Int64)] = [] + } - /// Rolling average throughput in bytes per second, computed over the - /// most recent ~5 seconds of progress samples. nil until we have at - /// least two samples spanning a meaningful window. + /// Width of the throughput window. Short enough that a stall shows within a + /// few seconds, long enough to smooth the jitter in chunk arrivals. + private static let throughputWindow: TimeInterval = 5 + + /// Internal, so a test builds an isolated instance and calls ``apply(_:)`` on + /// it. An instance other than ``shared`` drains no inbox, so nothing reaches + /// it except a direct ``apply(_:)`` call. + init() {} + + // MARK: - Reading + + /// Unsorted, for the aggregates. ``activeDownloads`` is the published order. + private var reportedDownloads: [Download] { + states.values.compactMap(\.download) + } + + /// Every model downloading now, earliest first. Empty when none is. + public var activeDownloads: [Download] { + reportedDownloads.sorted { ($0.startedAt, $0.modelID) < ($1.startedAt, $1.modelID) } + } + + /// This model's download, or nil when it is not downloading or has not + /// reported progress yet. + public func download(forModelID modelID: String) -> Download? { + states[modelID]?.download + } + + /// Combined progress across every downloading model, weighted by bytes. 0 + /// before the first report carries a total. + public var fractionCompleted: Double { + let total = totalBytes + guard total > 0 else { return 0 } + return Double(completedBytes) / Double(total) + } + + /// Bytes downloaded so far, across every downloading model. + public var completedBytes: Int64 { + reportedDownloads.reduce(0) { $0 + $1.completedBytes } + } + + /// Total bytes, across every downloading model. + public var totalBytes: Int64 { + reportedDownloads.reduce(0) { $0 + $1.totalBytes } + } + + /// When the earliest download still running first reported, and nil when none + /// is running. Consumers can compute elapsed time as + /// `Date.now.timeIntervalSince(startedAt)`. + public var startedAt: Date? { + reportedDownloads.map(\.startedAt).min() + } + + /// Combined throughput across every downloading model, and nil when no model + /// has enough samples yet. /// - /// Rolling (not cumulative) so a stall shows up immediately as the - /// number dropping toward 0 -- consumers can show "still moving" vs - /// "stuck" without needing a separate indicator. - public private(set) var throughputBytesPerSec: Double? - - /// Width of the throughput rolling window. Short enough that stalls - /// are visible within a few seconds; long enough to smooth out the - /// natural jitter in HF chunk arrivals. - private let throughputWindow: TimeInterval = 5.0 - - /// Samples used to compute rolling throughput. Pruned to - /// `throughputWindow` on every `reportProgress` call. - private var samples: [(time: Date, bytes: Int64)] = [] - - private init() {} - - /// Nonisolated entry point for `reportProgress` so callers from sendable - /// closures (e.g. the cache loader's `progressHandler`) don't have to - /// hop to the main actor just to read `.shared`. The instance method is - /// already nonisolated; this shim only forwards. - nonisolated public static func report(progress: Progress, modelID: String) { - Task { @MainActor in - shared.reportProgress(progress, modelID: modelID) - } + /// Rolling (not cumulative) so a stall shows up immediately as the number + /// dropping toward 0 -- consumers can show "still moving" vs "stuck" without + /// needing a separate indicator. + public var throughputBytesPerSecond: Double? { + let rates = reportedDownloads.compactMap(\.throughputBytesPerSecond) + return rates.isEmpty ? nil : rates.reduce(0, +) } - /// Nonisolated entry point for `reportCompleted`. Same rationale as - /// ``report(progress:modelID:)``. - nonisolated public static func reportCompleted() { - Task { @MainActor in - shared.reportCompleted() - } + // MARK: - Reporting + + /// Reports that a load for `modelID` started. `loadID` identifies this load + /// attempt, and every later call for it must carry the same value. + /// + /// Pair every call with ``reportEnded(modelID:loadID:)``, or that model's + /// progress never clears. + nonisolated static func reportStarted(modelID: String, loadID: UUID) { + _ = startProgressDrainOnce + sharedProgressInbox.continuation.yield(.started(modelID: modelID, loadID: loadID)) + } + + /// Reports one progress change for the load `loadID` identifies. + /// + /// Nonisolated so a producer inside a sendable closure, for example the cache + /// loader's `progressHandler`, reaches the inbox without a hop to the main + /// actor. A hop here would lose the order the reports were made in. + nonisolated static func report(progress: Progress, modelID: String, loadID: UUID) { + _ = startProgressDrainOnce + sharedProgressInbox.continuation.yield( + .progress( + modelID: modelID, + loadID: loadID, + fraction: progress.fractionCompleted, + completed: progress.completedUnitCount, + total: progress.totalUnitCount)) + } + + /// Reports that the load `loadID` identifies ended, whether it succeeded, + /// failed, or was cancelled. + nonisolated static func reportEnded(modelID: String, loadID: UUID) { + _ = startProgressDrainOnce + sharedProgressInbox.continuation.yield(.ended(modelID: modelID, loadID: loadID)) } - nonisolated func reportProgress(_ progress: Progress, modelID: String) { - let fraction = progress.fractionCompleted - // Don't show the progress UI for already-cached models (immediate 100%) - guard fraction < 1.0 else { return } - let completed = progress.completedUnitCount - let total = progress.totalUnitCount + // MARK: - Applying + + /// Drains `updates` for the life of this instance. Only ``shared`` calls it. + /// A second consumer would take updates the shared instance needs. + private func consume(_ updates: AsyncStream) { Task { @MainActor in - if self.startedAt == nil { - self.startedAt = Date() - self.samples.removeAll() + for await update in updates { + self.apply(update) } - self.isActive = true - self.fractionCompleted = fraction - self.modelName = modelID - self.completedBytes = completed - self.totalBytes = total - self.appendSampleAndRecompute(bytes: completed) } } - nonisolated func reportCompleted() { - Task { @MainActor in - self.isActive = false - self.fractionCompleted = 1.0 - self.modelName = nil - self.startedAt = nil - self.completedBytes = 0 - self.totalBytes = 0 - self.throughputBytesPerSec = nil - self.samples.removeAll() + /// Folds one update into the published state, in the order it was yielded. + /// + /// An update from a load that no longer owns its model's entry is dropped, so + /// a load that was cancelled cannot disturb the load that replaced it. + func apply(_ update: DownloadProgressUpdate) { + switch update { + case .started(let modelID, let loadID): + // Replaces any earlier entry, so the newest load owns the model and + // brings its own start time and samples. Nothing is published for it + // until it reports. + states[modelID] = State(loadID: loadID) + + case .progress(let modelID, let loadID, let fraction, let completed, let total): + // A model already on disk reports 1.0 at once. Publishing it would + // flash a full progress bar for one frame. A finishing download's + // final 1.0 is dropped for the same reason, and its entry goes away + // when its load ends. + guard fraction < 1 else { return } + guard var state = states[modelID], state.loadID == loadID else { return } + + let now = Date.now + state.samples.append((time: now, bytes: completed)) + let cutoff = now.addingTimeInterval(-Self.throughputWindow) + state.samples.removeAll { $0.time < cutoff } + state.download = Download( + modelID: modelID, + fractionCompleted: fraction, + completedBytes: completed, + totalBytes: total, + startedAt: state.download?.startedAt ?? now, + throughputBytesPerSecond: Self.throughput(across: state.samples)) + states[modelID] = state + + case .ended(let modelID, let loadID): + guard states[modelID]?.loadID == loadID else { return } + states[modelID] = nil } } - /// Append the latest byte count, prune samples outside the rolling - /// window, and recompute throughput. Requires at least 2 samples - /// spanning a non-trivial time interval to produce a meaningful rate. - private func appendSampleAndRecompute(bytes: Int64) { - let now = Date() - samples.append((time: now, bytes: bytes)) - let cutoff = now.addingTimeInterval(-throughputWindow) - samples.removeAll { $0.time < cutoff } - - guard let oldest = samples.first, - let newest = samples.last, - samples.count >= 2 - else { - throughputBytesPerSec = nil - return - } - let dt = newest.time.timeIntervalSince(oldest.time) - guard dt > 0.1 else { - throughputBytesPerSec = nil - return - } - let db = newest.bytes - oldest.bytes - throughputBytesPerSec = Double(db) / dt + /// Rate across the retained samples. nil below two samples, and nil when they + /// span a tenth of a second or less, because a shorter span gives a + /// meaningless rate. + private static func throughput(across samples: [(time: Date, bytes: Int64)]) -> Double? { + guard samples.count >= 2, let oldest = samples.first, let newest = samples.last + else { return nil } + let seconds = newest.time.timeIntervalSince(oldest.time) + guard seconds > 0.1 else { return nil } + return Double(newest.bytes - oldest.bytes) / seconds } } diff --git a/Libraries/MLXFoundationModels/MLXLanguageModel.swift b/Libraries/MLXFoundationModels/MLXLanguageModel.swift index 1392828172..4d57f1a551 100644 --- a/Libraries/MLXFoundationModels/MLXLanguageModel.swift +++ b/Libraries/MLXFoundationModels/MLXLanguageModel.swift @@ -15,284 +15,8 @@ import Foundation import FoundationModels import MLXLMCommon import MLX -import os.log import MLXGuidedGeneration -// MARK: - Constraint Cache Kind - -/// Selects which xgrammar constructor a cached template was compiled -/// with. Used by the constraint cache so a JSON-schema source and a -/// structural-tag source can never alias even if their text collides. -enum ConstraintKind { - case json - case structuralTag -} - -// MARK: - Tokenizer Bias Cache Entry - -/// Tokenizer-derived logit biases, cached per model. Both arrays are pure -/// functions of the tokenizer, so they are identical for a model's lifetime. -/// `@unchecked Sendable`: every field is `let` and read-only after construction -/// (the arrays are only *added* to logits in `GuidedGenerationLoop`, never -/// mutated), and the entry is shared across actors via `ModelCache` — the same -/// pattern as `GrammarTokenizer`/`GrammarConstraint` in `XGrammarBridge.swift`. -final class TokenizerBias: @unchecked Sendable { - let closing: MLXArray - let whitespace: MLXArray - let whitespaceTokenIDs: Set - - init(closing: MLXArray, whitespace: MLXArray, whitespaceTokenIDs: Set) { - self.closing = closing - self.whitespace = whitespace - self.whitespaceTokenIDs = whitespaceTokenIDs - } -} - -// MARK: - Model Cache Actor - -/// Thread-safe model cache using Swift actor isolation. -/// Prevents race conditions when multiple concurrent requests try to load the model. -/// Supports caching multiple models by their identifiers. -private actor ModelCache { - /// Class wrapper around `Task` so actor-reentrancy supersession guards can - /// use `===` identity comparison. `Task` is a value type; a wrapper lets us - /// detect whether `evictAll()` replaced a loading entry mid-flight. - private final class LoadTask { - let task: Task - init(_ task: Task) { self.task = task } - } - - private var containers: [String: ModelContainer] = [:] - private var loadingTasks: [String: LoadTask] = [:] - /// In-flight loads tagged as a warmup of an already-present model, which - /// must NOT surface as `.downloading` (there is no user-facing download). - /// A subset of `loadingTasks`' keys. See `load` and `isDownloading`. - private var suppressedLoadIDs: Set = [] - private var xgTokenizers: [String: GrammarTokenizer] = [:] - /// Cached compiled constraint templates keyed by (modelID, schemaJSON). - /// Clone from template instead of recompiling the grammar each request. - private var constraintTemplates: [String: GrammarConstraint] = [:] - /// Cached per-model logit biases (closing + whitespace). Pure functions of - /// the tokenizer, so computed once per model and reused across requests. - private var tokenizerBiases: [String: TokenizerBias] = [:] - /// Most recent load error per model. Cleared on a subsequent successful - /// load. Surfaced through `MLXLanguageModel.availability` so callers can - /// distinguish "never tried" from "tried and failed". - private var lastErrors: [String: any Error] = [:] - - /// Gets the cached model container for the given model ID, loading it if necessary. - /// Concurrent callers for the same model will share the same loading task, preventing duplicate loads. - /// - /// The `loader` closure carries the transport types (downloader, tokenizer - /// loader). Keeping them out of the cache means the cache itself stays - /// agnostic of how a container is acquired -- first caller wins; later - /// callers reuse the cached container regardless of which loader they - /// brought along. - func load( - modelID: String, - suppressDownloadingState: Bool = false, - loader: @Sendable @escaping () async throws -> ModelContainer - ) async throws -> ModelContainer { - if let cached = containers[modelID] { - return cached - } - - if let existingLoadTask = loadingTasks[modelID] { - // Coalesced onto an in-flight load: the first caller's - // classification (downloading vs. suppressed) stands — we do not - // re-tag. This collision is benign because the suppress decision is - // conditioned on disk-presence: a warmup and a genuine download for - // a not-yet-present model both classify as downloading, so they - // agree; when the model IS present, `availability` resolves to - // `.available` regardless of the in-flight load. - return try await existingLoadTask.task.value - } - - let loadTask = LoadTask( - Task { - try await loader() - }) - loadingTasks[modelID] = loadTask - // Tag a warmup-of-an-already-present model out of the `.downloading` - // signal (computed by the caller as warmup AND modelExistsOnDisk()). - if suppressDownloadingState { - suppressedLoadIDs.insert(modelID) - } - - do { - let loaded = try await loadTask.task.value - // Supersession guard: `evict()`/`evictAll()` may have removed this - // load while it was suspended (actor reentrancy). If we are no longer - // the registered task, hand the awaiter its container but do NOT - // re-populate the cache — ARC frees the weights when the awaiter - // releases it. - guard loadingTasks[modelID] === loadTask else { return loaded } - containers[modelID] = loaded - loadingTasks[modelID] = nil - suppressedLoadIDs.remove(modelID) - lastErrors[modelID] = nil - return loaded - } catch { - // Same guard on the failure path: a superseded load must not re-add a - // stale lastErrors entry for a model nobody holds. - if loadingTasks[modelID] === loadTask { - loadingTasks[modelID] = nil - suppressedLoadIDs.remove(modelID) - lastErrors[modelID] = error - } - throw error - } - } - - /// Whether a *genuine download* is in flight for the given model: a load - /// task is running and it was not tagged as a warmup of an already-present - /// model. Drives `availability`'s `.downloading` state, so a background - /// warmup of an already-downloaded model does not spuriously report - /// `.downloading`. (A warmup that triggers a real fetch is not tagged and - /// does report here.) - func isDownloading(modelID: String) -> Bool { - loadingTasks[modelID] != nil && !suppressedLoadIDs.contains(modelID) - } - - /// The most recent load error for the given model, if a previous attempt - /// failed and no successful load has happened since. - func lastError(modelID: String) -> (any Error)? { - lastErrors[modelID] - } - - /// Gets or creates a cached GrammarTokenizer for the given model. - func makeXGTokenizer( - modelID: String, - tokenizer: any Tokenizer - ) throws -> GrammarTokenizer { - if let cached = xgTokenizers[modelID] { - return cached - } - let vocab = TokenizerVocabExtractor.extractForGrammar(from: tokenizer) - let xgTok = try GrammarTokenizer( - vocab: vocab.vocab, - vocabType: vocab.vocabType, - eosTokenId: Int32(tokenizer.eosTokenId ?? 0) - ) - xgTokenizers[modelID] = xgTok - return xgTok - } - - /// Whether an `GrammarTokenizer` is already cached for the given model. - /// Used by `MLXLanguageModel.hasCachedXGTokenizer` so tests can assert - /// that `warmUp()` pre-created it (a genuine cache hit) rather than only - /// that a later guided respond happens to succeed. - func hasCachedXGTokenizer(modelID: String) -> Bool { - xgTokenizers[modelID] != nil - } - - /// Gets or creates the cached tokenizer-derived logit biases for a model. - func makeTokenizerBias( - modelID: String, - tokenizer: any Tokenizer - ) -> TokenizerBias { - if let cached = tokenizerBiases[modelID] { - return cached - } - let closing = ClosingTokenBias.compute( - tokenizer: tokenizer, - eosTokenId: tokenizer.eosTokenId - ) - let (whitespace, whitespaceTokenIDs) = WhitespaceTokenBias.compute( - tokenizer: tokenizer - ) - let bias = TokenizerBias( - closing: closing, - whitespace: whitespace, - whitespaceTokenIDs: whitespaceTokenIDs - ) - tokenizerBiases[modelID] = bias - return bias - } - - /// Gets a fresh constraint by cloning a cached template, or compiles and caches one first. - /// - /// Grammar compilation is expensive (~5-20ms). By caching the compiled template - /// and cloning it (~0.1ms), repeated requests with the same schema skip recompilation. - /// When Fork() is unavailable (xgrammar < v0.1.34), the clone attempt fails gracefully - /// and each request compiles a fresh constraint instead. - func makeConstraint( - modelID: String, - kind: ConstraintKind, - source: String, - tokenizer: GrammarTokenizer, - hostTokenizer: any Tokenizer, - fastForward: Bool - ) throws -> GrammarConstraint { - let cacheKey = "\(modelID):\(kind):\(source)" - if let template = constraintTemplates[cacheKey] { - do { - return try template.clone() - } catch GrammarError.forkFailed { - constraintTemplates.removeValue(forKey: cacheKey) - } - } - let constraint: GrammarConstraint - switch kind { - case .json: - constraint = try GrammarConstraint( - tokenizer: tokenizer, - jsonSchema: source, - fastForward: fastForward, - hostTokenizer: hostTokenizer - ) - case .structuralTag: - constraint = try GrammarConstraint( - tokenizer: tokenizer, - structuralTag: source, - fastForward: fastForward, - hostTokenizer: hostTokenizer - ) - } - if let cloned = try? constraint.clone() { - constraintTemplates[cacheKey] = constraint - return cloned - } - return constraint - } - - /// Evicts all cached state: model containers, tokenizers, constraint - /// templates, and per-model tokenizer biases. No GPU-stream synchronization - /// is required — in-flight callers retain their own `ModelContainer` and - /// free it via ARC on completion. - func evictAll() { - containers.removeAll() - loadingTasks.removeAll() - suppressedLoadIDs.removeAll() - xgTokenizers.removeAll() - constraintTemplates.removeAll() - tokenizerBiases.removeAll() - lastErrors.removeAll() - } - - /// Evicts a single model's state across every per-model cache: its container, - /// xgrammar tokenizer, all compiled constraint templates, tokenizer bias, - /// last load error, the suppressed-download tag, and any in-flight load - /// registration. - /// Best-effort cancels an in-flight load (the load path is not - /// cancellation-aware today, so this is a no-op safety net); the - /// load-completion guard in `load()` is what prevents a superseded load - /// from re-populating after removal. - func remove(modelID: String) { - // `loadingTasks` holds a `LoadTask` box; cancel the wrapped `Task`. - loadingTasks[modelID]?.task.cancel() - loadingTasks.removeValue(forKey: modelID) - suppressedLoadIDs.remove(modelID) - containers.removeValue(forKey: modelID) - xgTokenizers.removeValue(forKey: modelID) - constraintTemplates = constraintTemplates.filter { - !$0.key.hasPrefix("\(modelID):") - } - tokenizerBiases.removeValue(forKey: modelID) - lastErrors.removeValue(forKey: modelID) - } -} - // MARK: - MLXLanguageModel /// A language model implementation that uses MLX for local inference. @@ -362,6 +86,10 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { /// Loads the model container for a configuration, forwarding download /// progress. Injected so this module carries no HuggingFace or /// swift-transformers dependency; the HuggingFace wiring lives in callers. + /// + /// This closure must honor cancellation while it is suspended. ``evict()`` + /// and ``evictAll()`` cancel the load task tied to this closure. A closure + /// that ignores cancellation keeps running and keeps its caller waiting. public typealias ContainerLoader = @Sendable ( _ configuration: ModelConfiguration, @@ -410,20 +138,26 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { // Configure the buffer pool once per process rather than on every // load, so a consumer's own `Memory.cacheLimit` survives our loads. _ = Self.configureGPUCacheOnce - let container = try await load(configuration) { progress in - MLXDownloadProgress.report(progress: progress, modelID: configuration.name) + // One identifier per load attempt. Eviction cancels a load and + // forgets it at once, so a replacement can start while this one is + // still unwinding, and the progress observable needs to tell them + // apart. + let loadID = UUID() + MLXDownloadProgress.reportStarted(modelID: configuration.name, loadID: loadID) + defer { MLXDownloadProgress.reportEnded(modelID: configuration.name, loadID: loadID) } + return try await load(configuration) { progress in + MLXDownloadProgress.report( + progress: progress, modelID: configuration.name, loadID: loadID) } - MLXDownloadProgress.reportCompleted() - return container } } /// Gets or creates a cached GrammarTokenizer for the given model. - static func makeXGTokenizer( + static func makeGrammarTokenizer( modelID: String, tokenizer: any Tokenizer ) async throws -> GrammarTokenizer { - try await cache.makeXGTokenizer(modelID: modelID, tokenizer: tokenizer) + try await cache.makeGrammarTokenizer(modelID: modelID, tokenizer: tokenizer) } /// Gets the cached per-model tokenizer-derived logit biases (closing + @@ -457,18 +191,27 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { /// Whether the shared cache already holds an `GrammarTokenizer` for the model. /// Internal test seam (not public API): lets `PrewarmGrammarTests` confirm /// `warmUp()` pre-created the tokenizer. - static func hasCachedXGTokenizer(modelID: String) async -> Bool { - await cache.hasCachedXGTokenizer(modelID: modelID) + static func hasCachedGrammarTokenizer(modelID: String) async -> Bool { + await cache.hasCachedGrammarTokenizer(modelID: modelID) } /// Evicts every cached model, tokenizer, constraint template, and per-model /// tokenizer bias, freeing the GPU memory held by model weights. Subsequent - /// requests reload from the on-disk cache. + /// requests reload from the on-disk cache. Cancels every registered + /// in-flight load task, the same way ``evict()`` does for one model. /// - /// Safe to call during in-flight `respond()`/`warmUp()` work: each holds its - /// own strong reference to the `ModelContainer` and synchronizes the GPU on - /// exit, so dropping the cache's reference cannot free weights out from under - /// a live kernel — the weights free via ARC once that work returns. + /// Safe to call during in-flight `respond()`/`warmUp()` work that already holds + /// a `ModelContainer`: that work keeps its own strong reference and synchronizes + /// the GPU on exit, so dropping the cache's reference cannot free weights out + /// from under a live kernel — the weights free via ARC once that work returns. + /// + /// Work still inside its load phase is the other case. This call cancels every + /// registered load task, so if the loader honors cancellation, an awaiting + /// `preload()` or `respond()` fails instead of completing. The loader decides + /// the error type, so it may not be `CancellationError`. The cache coalesces + /// concurrent callers for one model onto a single load task, so one such + /// failure reaches every caller waiting on that load, including callers that + /// never asked for an eviction. public static func evictAll() async { await cache.evictAll() } @@ -479,8 +222,10 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { /// /// Safe to call during an in-flight `respond()`: that call retains its own /// `ModelContainer` and finishes normally; the weights free via ARC once it - /// returns. Evicting a model whose load is still in flight removes it cleanly - /// — the in-flight load completes but does not re-populate the cache. + /// returns. Evicting a model with an in-flight load cancels that load's task. + /// If the loader honors cancellation, the awaiting `preload()` or `respond()` + /// call fails instead of completing. The loader decides the error type, so it + /// may not be `CancellationError`. public func evict() async { await Self.cache.remove(modelID: modelID) } @@ -636,7 +381,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { // per-request schema/tool grammar that prewarm doesn't possess — a // pre-built constraint would land under a key no real respond() reads. let tokenizer = await container.tokenizer - _ = try await Self.makeXGTokenizer( + _ = try await Self.makeGrammarTokenizer( modelID: modelID, tokenizer: tokenizer) // Force Metal shader JIT with a minimal 1-token generate, run inside @@ -863,10 +608,8 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { /// prewarm (bad id, network gone, OOM). Note it cannot intercept a /// Metal command-buffer assertion abort — that is a process crash, not /// a catchable Swift error. - private static let logger = Logger( - subsystem: "com.apple.FoundationModels-MLX", category: "Prewarm") - private static let protocolLogger = Logger( - subsystem: "com.apple.FoundationModels-MLX", category: "TokenStreamProtocol") + private static let logger = MLXLogger(label: "Prewarm") + private static let protocolLogger = MLXLogger(label: "TokenStreamProtocol") /// Prewarms the model: loads weights and pre-compiles Metal shaders so /// the first `respond()` pays no cold-start shader-JIT cost. @@ -895,7 +638,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { try await model.warmUp() } catch { Self.logger.error( - "MLX prewarm failed for \(model.modelID, privacy: .public): \(error.localizedDescription, privacy: .public)" + "MLX prewarm failed for \(model.modelID): \(error.localizedDescription)" ) } } @@ -912,20 +655,15 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { model: MLXLanguageModel, streamingInto channel: LanguageModelExecutorGenerationChannel ) async throws { - var collected = TranscriptConverter.mlxMessages(for: request.transcript) + var collected = try TranscriptConverter.mlxMessages(for: request.transcript) // MLX tokenizer crashes on empty chat input; provide a fallback. if collected.isEmpty { collected = [Chat.Message.user("")] } let messages = collected - // Vision capability gate (adapter-side). Labeled image - // attachments arrive as public `.attachment` segments that - // the SDK's own vision guard never inspects, so the adapter - // is the only place that can enforce `.vision` for this path. - // Throw the same typed error the SDK would, before loading - // any weights, so a model declared without `.vision` fails - // fast and identically across the tool / schema / plain paths. + // The SDK's vision check does not cover `.attachment` segments, so the adapter + // must enforce `.vision` for image attachments itself. if !model.capabilities.contains(.vision), messages.contains(where: { !$0.images.isEmpty }) { @@ -973,6 +711,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { // reasoning config we route on. let declaresReasoning = model.capabilities.contains(.reasoning) let configurationResolver = model.configurationResolver + let labeledAttachments = TranscriptConverter.labeledAttachments(in: request.transcript) do { // Send metadata first @@ -985,6 +724,9 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { // .Video are not Sendable), so route the array through // perform(nonSendable:_:) which boxes it across the actor hop. try await container.perform(nonSendable: messages) { context, messages in + try AttachmentLabelValidator.default.validate( + labeledAttachments, with: context.tokenizer) + // Render the prompt through the model's UserInputProcessor. let userInput = UserInput(chat: messages) let input = try await context.processor.prepare(input: userInput) @@ -1263,7 +1005,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { tools: requiredToolDefinitions ) - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer ) @@ -1271,7 +1013,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { modelID: modelID, kind: .structuralTag, source: toolCallingGrammar, - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, hostTokenizer: context.tokenizer, fastForward: true ) @@ -1356,7 +1098,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { context: context, constraint: constraint, maxTokens: phase2MaxTokens, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: completionReserve, hardReserve: hardReserve, closingBias: closingBias, @@ -1651,14 +1393,14 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { context: ModelContext, channel: LanguageModelExecutorGenerationChannel ) async throws { - let xgTokenizer = try await MLXLanguageModel.makeXGTokenizer( + let grammarTokenizer = try await MLXLanguageModel.makeGrammarTokenizer( modelID: modelID, tokenizer: context.tokenizer) let constraint = try await MLXLanguageModel.makeConstraint( modelID: modelID, kind: .json, source: schemaJSON, - tokenizer: xgTokenizer, + tokenizer: grammarTokenizer, hostTokenizer: context.tokenizer, fastForward: true) let maxTokens = requestedMaxTokens ?? Self.defaultMaxTokens @@ -1690,7 +1432,7 @@ public struct MLXLanguageModel: FoundationModels.LanguageModel, Sendable { context: context, constraint: constraint, maxTokens: maxTokens, - vocabSize: Int(xgTokenizer.vocabSize), + vocabSize: Int(grammarTokenizer.vocabSize), completionReserve: completionReserve, hardReserve: hardReserve, closingBias: bias.closing, diff --git a/Libraries/MLXFoundationModels/ModelCache.swift b/Libraries/MLXFoundationModels/ModelCache.swift new file mode 100644 index 0000000000..161680239f --- /dev/null +++ b/Libraries/MLXFoundationModels/ModelCache.swift @@ -0,0 +1,298 @@ +// Copyright © 2026 Apple Inc. + +#if FoundationModelsIntegration +#if canImport(FoundationModels, _version: 2) + +import Foundation +import MLX +import MLXGuidedGeneration +import MLXLMCommon + +// MARK: - Constraint Cache Kind + +/// Selects which xgrammar constructor a cached template was compiled +/// with. Used by the constraint cache so a JSON-schema source and a +/// structural-tag source can never alias even if their text collides. +enum ConstraintKind { + case json + case structuralTag +} + +// MARK: - Tokenizer Bias Cache Entry + +/// Tokenizer-derived logit biases, cached per model. Both arrays are pure +/// functions of the tokenizer, so they are identical for a model's lifetime. +/// `@unchecked Sendable`: every field is `let` and read-only after construction +/// (the arrays are only *added* to logits in `GuidedGenerationLoop`, never +/// mutated), and the entry is shared across actors via `ModelCache` — the same +/// pattern as `GrammarTokenizer`/`GrammarConstraint` in `XGrammarBridge.swift`. +final class TokenizerBias: @unchecked Sendable { + let closing: MLXArray + let whitespace: MLXArray + let whitespaceTokenIDs: Set + + init(closing: MLXArray, whitespace: MLXArray, whitespaceTokenIDs: Set) { + self.closing = closing + self.whitespace = whitespace + self.whitespaceTokenIDs = whitespaceTokenIDs + } +} + +// MARK: - Model Cache Actor + +/// Thread-safe model cache using Swift actor isolation. +/// Prevents race conditions when multiple concurrent requests try to load the model. +/// Supports caching multiple models by their identifiers. +actor ModelCache { + /// Class wrapper around `Task` so actor-reentrancy supersession guards can + /// use `===` identity comparison. `Task` is a value type; a wrapper lets us + /// detect whether `evictAll()` replaced a loading entry mid-flight. + private final class LoadTask { + let task: Task + init(_ task: Task) { self.task = task } + } + + private var containers: [String: ModelContainer] = [:] + private var loadingTasks: [String: LoadTask] = [:] + /// In-flight loads tagged as a warmup of an already-present model, which + /// must NOT surface as `.downloading` (there is no user-facing download). + /// A subset of `loadingTasks`' keys. See `load` and `isDownloading`. + private var suppressedLoadIDs: Set = [] + private var grammarTokenizers: [String: GrammarTokenizer] = [:] + /// Cached compiled constraint templates keyed by (modelID, schemaJSON). + /// Clone from template instead of recompiling the grammar each request. + private var constraintTemplates: [String: GrammarConstraint] = [:] + /// Cached per-model logit biases (closing + whitespace). Pure functions of + /// the tokenizer, so computed once per model and reused across requests. + private var tokenizerBiases: [String: TokenizerBias] = [:] + /// Most recent load error per model. Cleared on a subsequent successful + /// load. Surfaced through `MLXLanguageModel.availability` so callers can + /// distinguish "never tried" from "tried and failed". + private var lastErrors: [String: any Error] = [:] + + /// Gets the cached model container for the given model ID, loading it if necessary. + /// Concurrent callers for the same model will share the same loading task, preventing duplicate loads. + /// + /// The `loader` closure carries the transport types (downloader, tokenizer + /// loader). Keeping them out of the cache means the cache itself stays + /// agnostic of how a container is acquired -- first caller wins; later + /// callers reuse the cached container regardless of which loader they + /// brought along. + /// + /// The loader must honor cancellation while it is suspended: `evictAll()` and + /// `remove(modelID:)` cancel the registered load task, and a loader that + /// ignores cancellation keeps running and keeps its awaiter waiting. + func load( + modelID: String, + suppressDownloadingState: Bool = false, + loader: @Sendable @escaping () async throws -> ModelContainer + ) async throws -> ModelContainer { + if let cached = containers[modelID] { + return cached + } + + if let existingLoadTask = loadingTasks[modelID] { + // Coalesced onto an in-flight load: the first caller's + // classification (downloading vs. suppressed) stands — we do not + // re-tag. This collision is benign because the suppress decision is + // conditioned on disk-presence: a warmup and a genuine download for + // a not-yet-present model both classify as downloading, so they + // agree; when the model IS present, `availability` resolves to + // `.available` regardless of the in-flight load. + return try await existingLoadTask.task.value + } + + let loadTask = LoadTask( + Task { + try await loader() + }) + loadingTasks[modelID] = loadTask + // Tag a warmup-of-an-already-present model out of the `.downloading` + // signal (computed by the caller as warmup AND modelExistsOnDisk()). + if suppressDownloadingState { + suppressedLoadIDs.insert(modelID) + } + + do { + let loaded = try await loadTask.task.value + // Supersession guard: `evict()`/`evictAll()` may have removed this + // load while it was suspended (actor reentrancy). If we are no longer + // the registered task, hand the awaiter its container but do NOT + // re-populate the cache — ARC frees the weights when the awaiter + // releases it. + guard loadingTasks[modelID] === loadTask else { return loaded } + containers[modelID] = loaded + loadingTasks[modelID] = nil + suppressedLoadIDs.remove(modelID) + lastErrors[modelID] = nil + return loaded + } catch { + // Same guard on the failure path: a superseded load must not re-add a + // stale lastErrors entry for a model nobody holds. + if loadingTasks[modelID] === loadTask { + loadingTasks[modelID] = nil + suppressedLoadIDs.remove(modelID) + lastErrors[modelID] = error + } + throw error + } + } + + /// Whether a *genuine download* is in flight for the given model: a load + /// task is running and it was not tagged as a warmup of an already-present + /// model. Drives `availability`'s `.downloading` state, so a background + /// warmup of an already-downloaded model does not spuriously report + /// `.downloading`. (A warmup that triggers a real fetch is not tagged and + /// does report here.) + func isDownloading(modelID: String) -> Bool { + loadingTasks[modelID] != nil && !suppressedLoadIDs.contains(modelID) + } + + /// The most recent load error for the given model, if a previous attempt + /// failed and no successful load has happened since. + func lastError(modelID: String) -> (any Error)? { + lastErrors[modelID] + } + + /// Gets or creates a cached GrammarTokenizer for the given model. + func makeGrammarTokenizer( + modelID: String, + tokenizer: any Tokenizer + ) throws -> GrammarTokenizer { + if let cached = grammarTokenizers[modelID] { + return cached + } + let vocabulary = TokenizerVocabExtractor.extractForGrammar(from: tokenizer) + let grammarTokenizer = try GrammarTokenizer( + vocab: vocabulary.vocab, + vocabType: vocabulary.vocabType, + eosTokenId: Int32(tokenizer.eosTokenId ?? 0) + ) + grammarTokenizers[modelID] = grammarTokenizer + return grammarTokenizer + } + + /// Whether an `GrammarTokenizer` is already cached for the given model. + /// Used by `MLXLanguageModel.hasCachedGrammarTokenizer` so tests can assert + /// that `warmUp()` pre-created it (a genuine cache hit) rather than only + /// that a later guided respond happens to succeed. + func hasCachedGrammarTokenizer(modelID: String) -> Bool { + grammarTokenizers[modelID] != nil + } + + /// Gets or creates the cached tokenizer-derived logit biases for a model. + func makeTokenizerBias( + modelID: String, + tokenizer: any Tokenizer + ) -> TokenizerBias { + if let cached = tokenizerBiases[modelID] { + return cached + } + let closing = ClosingTokenBias.compute( + tokenizer: tokenizer, + eosTokenId: tokenizer.eosTokenId + ) + let (whitespace, whitespaceTokenIDs) = WhitespaceTokenBias.compute( + tokenizer: tokenizer + ) + let bias = TokenizerBias( + closing: closing, + whitespace: whitespace, + whitespaceTokenIDs: whitespaceTokenIDs + ) + tokenizerBiases[modelID] = bias + return bias + } + + /// Gets a fresh constraint by cloning a cached template, or compiles and caches one first. + /// + /// Grammar compilation is expensive (~5-20ms). By caching the compiled template + /// and cloning it (~0.1ms), repeated requests with the same schema skip recompilation. + /// When Fork() is unavailable (xgrammar < v0.1.34), the clone attempt fails gracefully + /// and each request compiles a fresh constraint instead. Any other clone failure + /// reaches the caller. + func makeConstraint( + modelID: String, + kind: ConstraintKind, + source: String, + tokenizer: GrammarTokenizer, + hostTokenizer: any Tokenizer, + fastForward: Bool + ) throws -> GrammarConstraint { + let cacheKey = "\(modelID):\(kind):\(source)" + if let template = constraintTemplates[cacheKey] { + do { + return try template.clone() + } catch GrammarError.forkFailed { + constraintTemplates.removeValue(forKey: cacheKey) + } + } + let constraint: GrammarConstraint + switch kind { + case .json: + constraint = try GrammarConstraint( + tokenizer: tokenizer, + jsonSchema: source, + fastForward: fastForward, + hostTokenizer: hostTokenizer + ) + case .structuralTag: + constraint = try GrammarConstraint( + tokenizer: tokenizer, + structuralTag: source, + fastForward: fastForward, + hostTokenizer: hostTokenizer + ) + } + do { + let clone = try constraint.clone() + constraintTemplates[cacheKey] = constraint + return clone + } catch GrammarError.forkFailed { + return constraint + } + } + + /// Evicts all cached state: model containers, tokenizers, constraint + /// templates, and per-model tokenizer biases. Cancels every registered load + /// task, as `remove(modelID:)` does for a single model. No GPU-stream + /// synchronization is required — in-flight callers retain their own + /// `ModelContainer` and free it via ARC on completion. + func evictAll() { + containers.removeAll() + for loadTask in loadingTasks.values { + loadTask.task.cancel() + } + loadingTasks.removeAll() + suppressedLoadIDs.removeAll() + grammarTokenizers.removeAll() + constraintTemplates.removeAll() + tokenizerBiases.removeAll() + lastErrors.removeAll() + } + + /// Evicts a single model's state across every per-model cache: its container, + /// xgrammar tokenizer, all compiled constraint templates, tokenizer bias, + /// last load error, the suppressed-download tag, and any in-flight load + /// registration. + /// + /// Cancels an in-flight load and drops its registration. A loader that honors + /// cancellation stops early. The load-completion guard in `load()` is + /// what prevents any superseded load from re-populating after removal. + func remove(modelID: String) { + // `loadingTasks` holds a `LoadTask` box; cancel the wrapped `Task`. + loadingTasks[modelID]?.task.cancel() + loadingTasks.removeValue(forKey: modelID) + suppressedLoadIDs.remove(modelID) + containers.removeValue(forKey: modelID) + grammarTokenizers.removeValue(forKey: modelID) + constraintTemplates = constraintTemplates.filter { + !$0.key.hasPrefix("\(modelID):") + } + tokenizerBiases.removeValue(forKey: modelID) + lastErrors.removeValue(forKey: modelID) + } +} + +#endif // canImport(FoundationModels) +#endif // FoundationModelsIntegration diff --git a/Libraries/MLXFoundationModels/ToolCalling/ToolCallingConversions.swift b/Libraries/MLXFoundationModels/ToolCalling/ToolCallingConversions.swift index 95e589ab14..53c643585e 100644 --- a/Libraries/MLXFoundationModels/ToolCalling/ToolCallingConversions.swift +++ b/Libraries/MLXFoundationModels/ToolCalling/ToolCallingConversions.swift @@ -37,10 +37,8 @@ enum ToolCallingConversions { { let schema: GenerationSchema = tool.parameters let paramsData = try JSONEncoder().encode(schema) - guard - let paramsAny = try JSONSerialization.jsonObject(with: paramsData) - as? [String: any Sendable] - else { + let paramsObject = try JSONSerialization.jsonObject(with: paramsData) + guard let paramsAny = unboxingBooleans(in: paramsObject) as? [String: any Sendable] else { throw ToolCallingConversionError.invalidParameterSchema } @@ -54,6 +52,22 @@ enum ToolCallingConversions { ] } + /// swift-jinja's `Value(any:)` matches `Int` before `Bool`, so it converts a + /// `false` that `JSONSerialization` boxed in an `NSNumber` to `0`. + private static func unboxingBooleans(in value: Any) -> Any { + // Keep the type ID check. A boxed `0` or `1` also passes `as? Bool`. + if let number = value as? NSNumber { + return CFGetTypeID(number) == CFBooleanGetTypeID() ? number.boolValue : number + } + if let array = value as? [Any] { + return array.map(unboxingBooleans(in:)) + } + if let object = value as? [String: Any] { + return object.mapValues(unboxingBooleans(in:)) + } + return value + } + /// Converts an array of tool definitions, preserving order. Throws on the /// first conversion failure (unexpected -- `GenerationSchema` is `Codable` /// and tool parameter schemas should always encode cleanly). diff --git a/Libraries/MLXFoundationModels/TranscriptConverter.swift b/Libraries/MLXFoundationModels/TranscriptConverter.swift index 805d7a6beb..fa0721d38d 100644 --- a/Libraries/MLXFoundationModels/TranscriptConverter.swift +++ b/Libraries/MLXFoundationModels/TranscriptConverter.swift @@ -3,52 +3,56 @@ #if FoundationModelsIntegration #if canImport(FoundationModels, _version: 2) +import CoreImage import Foundation import FoundationModels +import MLX import MLXLMCommon -import os.log /// Converts FoundationModels transcript entries to MLX chat message format. @available(iOS 27.0, macOS 27.0, visionOS 27.0, *) struct TranscriptConverter { - private static let logger = Logger( - subsystem: "com.apple.FoundationModels-MLX", category: "TranscriptConverter") + private static let logger = MLXLogger(label: "TranscriptConverter") /// The MLX `Chat.Message` array for a collection of transcript entries. /// /// - Parameter entries: Transcript entries from FoundationModels /// - Returns: Array of MLX Chat.Message objects - static func mlxMessages(for entries: some Collection) -> [Chat + static func mlxMessages(for entries: some Collection) throws -> [Chat .Message] { - entries.compactMap { entry -> Chat.Message? in + try entries.compactMap { entry -> Chat.Message? in switch entry { case .instructions(let instructions): - // System message for model instructions. Labeled image - // attachments ride along as message images, mirroring the - // prompt path, so the `.vision` gate sees them and they are - // not silently dropped. + // Drop instruction attachments, as FoundationModels does. + // Some chat templates, such as Qwen3-VL's, write no image placeholder for a + // system message. The processor would then get pixels without a placeholder. let text = extractText(from: instructions.segments) - let images = extractImages(from: instructions.segments) - guard text != nil || !images.isEmpty else { + let dropped = try extractImages(from: instructions.segments, in: entry) + if !dropped.isEmpty { logger.warning( - "Skipping instructions entry with no text or image content") + "Dropping \(dropped.count) image attachment(s) in an instructions entry; attach images to a prompt instead so the model receives them" + ) + } + guard let text else { + logger.warning("Skipping instructions entry with no text content") return nil } - return Chat.Message.system(text ?? "", images: images) + return Chat.Message.system(text) case .prompt(let prompt): // User message for prompts. Labeled image attachments // (public `.attachment` segments) ride along as message // images; text is still concatenated as before. let text = extractText(from: prompt.segments) - let images = extractImages(from: prompt.segments) - guard text != nil || !images.isEmpty else { + let images = try extractImages(from: prompt.segments, in: entry) + let content = text ?? "" + guard !content.isEmpty || !images.isEmpty else { logger.warning("Skipping prompt entry with no text or image content") return nil } - return Chat.Message.user(text ?? "", images: images) + return Chat.Message.user(content, images: images) case .response(let response): // Assistant message for previous responses @@ -82,7 +86,7 @@ struct TranscriptConverter { arguments = decoded } else { logger.warning( - "Failed to decode arguments for tool: \(call.toolName, privacy: .public)" + "Failed to decode arguments for tool: \(call.toolName)" ) arguments = [:] } @@ -130,6 +134,11 @@ struct TranscriptConverter { return textSegment.content case .structure(let structuredSegment): return structuredSegment.content.jsonString + case .attachment(let attachment): + logger.warning( + "Dropping an attachment in tool output. Tool-output images are not yet forwarded to the model", + metadata: ["label": attachment.label ?? "none"]) + return nil default: logger.debug("Skipping unsupported tool-output segment") return nil @@ -163,23 +172,60 @@ struct TranscriptConverter { /// Extracts image inputs from image attachment segments. /// - /// Each image attachment is handed over as its already-decoded - /// `CIImage`. Segments that carry no image produce no input. + /// `Transcript.ImageAttachment.ciImage` does not apply `orientation`, so this function + /// must apply it. /// /// - Parameter segments: Array of transcript segments /// - Returns: The image inputs found, in segment order - private static func extractImages(from segments: [Transcript.Segment]) - -> [UserInput.Image] + /// - Throws: `LanguageModelError.unsupportedTranscriptContent` if an attachment is + /// not an image. + private static func extractImages( + from segments: [Transcript.Segment], + in entry: Transcript.Entry + ) throws -> [UserInput.Image] { + try segments.compactMap { segment -> UserInput.Image? in + guard case .attachment(let attachment) = segment else { return nil } + switch attachment.content { + case .image(let imageAttachment): + return .ciImage( + imageAttachment.ciImage.oriented(imageAttachment.orientation), + label: attachment.label) + @unknown default: + throw LanguageModelError.unsupportedTranscriptContent( + LanguageModelError.UnsupportedTranscriptContent( + unsupportedContent: [entry], + debugDescription: + "This attachment carries content the MLX adapter cannot render. Only image attachments are supported." + )) + } + } + } + + struct LabeledAttachment: Sendable { + let label: String + let entry: Transcript.Entry + } + + /// Reads only prompt entries, because the adapter drops the attachments of every other entry. + static func labeledAttachments(in entries: some Collection) + -> [LabeledAttachment] { - segments.compactMap { segment -> UserInput.Image? in - guard case .attachment(let attachment) = segment, - case .image(let imageAttachment) = attachment.content - else { - return nil + var seen = Set() + var ordered: [LabeledAttachment] = [] + for entry in entries { + guard case .prompt(let prompt) = entry else { continue } + for segment in prompt.segments { + guard case .attachment(let attachment) = segment, + let label = attachment.label + else { continue } + if seen.insert(label).inserted { + ordered.append(LabeledAttachment(label: label, entry: entry)) + } } - return .ciImage(imageAttachment.ciImage) } + return ordered } + } #endif // canImport(FoundationModels) diff --git a/Libraries/MLXLLM/Documentation.docc/evaluation.md b/Libraries/MLXLLM/Documentation.docc/evaluation.md index 29db5face1..7badef9d56 100644 --- a/Libraries/MLXLLM/Documentation.docc/evaluation.md +++ b/Libraries/MLXLLM/Documentation.docc/evaluation.md @@ -5,8 +5,16 @@ The simplified LLM/VLM API allows you to load a model and evaluate prompts with For example, this loads a model and asks a question and a follow-on question: ```swift +import Foundation +import MLXLLM +import MLXLMCommon +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace +import Tokenizers + let model = try await loadModel( - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen3-4B-4bit" ) let session = ChatSession(model) @@ -30,7 +38,8 @@ a stream: ```swift let model = try await loadModel( - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen3-4B-4bit" ) let session = ChatSession(model) @@ -137,7 +146,8 @@ to the `ChatSession`: ```swift let model = try await loadModel( - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen2.5-VL-3B-Instruct-4bit" ) let session = ChatSession(model) diff --git a/Libraries/MLXLLM/Documentation.docc/using-model.md b/Libraries/MLXLLM/Documentation.docc/using-model.md index e1cbc6045c..5e918f895b 100644 --- a/Libraries/MLXLLM/Documentation.docc/using-model.md +++ b/Libraries/MLXLLM/Documentation.docc/using-model.md @@ -16,10 +16,14 @@ let modelFactory: ModelFactory // e.g. LLMRegistry.llama3_8B_4bit let modelConfiguration: ModelConfiguration -// e.g. TokenizersLoader() from MLXLMTokenizers +// e.g. #hubDownloader() from MLXHuggingFace +let downloader: any Downloader + +// e.g. #huggingFaceTokenizerLoader() from MLXHuggingFace let tokenizerLoader: any TokenizerLoader let container = try await modelFactory.loadContainer( + from: downloader, using: tokenizerLoader, configuration: modelConfiguration ) diff --git a/Libraries/MLXLLM/Models/Gemma3nText.swift b/Libraries/MLXLLM/Models/Gemma3nText.swift index 92acbf508b..6a25776e7a 100644 --- a/Libraries/MLXLLM/Models/Gemma3nText.swift +++ b/Libraries/MLXLLM/Models/Gemma3nText.swift @@ -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 = [ diff --git a/Libraries/MLXLLM/Models/JinaReranker.swift b/Libraries/MLXLLM/Models/JinaReranker.swift index b7de33a4d6..dbf210bd6f 100644 --- a/Libraries/MLXLLM/Models/JinaReranker.swift +++ b/Libraries/MLXLLM/Models/JinaReranker.swift @@ -131,6 +131,9 @@ public final class JinaRerankerModel: Module, LanguageModel, KVCacheDimensionPro } func jinaCosineSimilarity(_ documents: MLXArray, _ query: MLXArray) -> MLXArray { + // The reference reranker computes final cosine scores from float32 embeddings. + let documents = documents.asType(.float32) + let query = query.asType(.float32) let numerator = MLX.sum(documents * query, axis: -1) let documentNorm = MLX.sqrt(MLX.sum(documents * documents, axis: -1)) let queryNorm = MLX.sqrt(MLX.sum(query * query, axis: -1)) diff --git a/Libraries/MLXLLM/Models/NemotronH.swift b/Libraries/MLXLLM/Models/NemotronH.swift index 69c0853902..8f8aabe679 100644 --- a/Libraries/MLXLLM/Models/NemotronH.swift +++ b/Libraries/MLXLLM/Models/NemotronH.swift @@ -886,12 +886,18 @@ public struct NemotronHConfiguration: Codable, Sendable { convKernel = try container.decode(Int.self, forKey: .convKernel) nGroups = try container.decode(Int.self, forKey: .nGroups) intermediateSize = try container.decode(Int.self, forKey: .intermediateSize) - moeIntermediateSize = try container.decode(Int.self, forKey: .moeIntermediateSize) - moeSharedExpertIntermediateSize = try container.decode( - Int.self, forKey: .moeSharedExpertIntermediateSize) - nRoutedExperts = try container.decode(Int.self, forKey: .nRoutedExperts) + // Dense Nemotron-H checkpoints (e.g. NVIDIA-Nemotron-3-Nano-4B) have no "E" + // layers in hybrid_override_pattern and ship no MoE keys at all, so these + // are only required when an MoE layer will actually be built. + moeIntermediateSize = + try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) ?? 0 + moeSharedExpertIntermediateSize = + try container.decodeIfPresent( + Int.self, forKey: .moeSharedExpertIntermediateSize) ?? 0 + nRoutedExperts = try container.decodeIfPresent(Int.self, forKey: .nRoutedExperts) ?? 0 nSharedExperts = try container.decodeIfPresent(Int.self, forKey: .nSharedExperts) - numExpertsPerTok = try container.decode(Int.self, forKey: .numExpertsPerTok) + numExpertsPerTok = + try container.decodeIfPresent(Int.self, forKey: .numExpertsPerTok) ?? 0 layerNormEpsilon = try container.decodeIfPresent(Float.self, forKey: .layerNormEpsilon) ?? 1e-5 mlpBias = try container.decodeIfPresent(Bool.self, forKey: .mlpBias) ?? false diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index 5745be83bc..337c6e5d4c 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -203,6 +203,19 @@ public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider { } } +extension Qwen3Model: CausalRerankerModel { + package func lastTokenLogits(_ inputs: MLXArray, sequenceLengths: [Int]) -> MLXArray { + let hidden = model(inputs, cache: nil) + let lastHidden = stacked( + sequenceLengths.enumerated().map { row, length in hidden[row, length - 1] }) + if let lmHead { + return lmHead(lastHidden) + } else { + return model.embedTokens.asLinear(lastHidden) + } + } +} + public struct Qwen3Configuration: Codable, Sendable { var hiddenSize: Int var hiddenLayers: Int diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 630c078769..b27ff854a6 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -277,6 +277,14 @@ final class Qwen35GatedDeltaNet: Module { var hasFusedInputProjection: Bool { fusedInputProjection.isPrepared } + /// The fused projection as compile state for a trace that runs this + /// layer. It is not a registered child (the checkpoint topology stays the + /// four projections), so a trace would otherwise read its arrays as tape + /// constants, and MLX keeps such constants alive after the trace is erased. + var fusedProjectionTraceState: [Module] { + fusedInputProjection.fused.map { [$0] } ?? [] + } + /// Build one physical quantized projection while retaining the four named /// module paths as storage-sharing views. This runs at most once between /// parameter/module updates; failed eligibility checks are not repeated on @@ -759,11 +767,13 @@ final class Qwen35DecoderLayer: Module { // Every body stays inside this layer, so each trace's default state (the // layer's own weights) is complete. - private let compiledLinearLayer = CompiledTrace { layer, arguments in - let (out, newConvState, newRecState) = layer.linearLayerBody( - x: arguments[0], convState: arguments[1], recState: arguments[2]) - return [out, newConvState, newRecState] - } + private let compiledLinearLayer = CompiledTrace( + state: { [$0] + ($0.linearAttn?.fusedProjectionTraceState ?? []) }, + body: { layer, arguments in + let (out, newConvState, newRecState) = layer.linearLayerBody( + x: arguments[0], convState: arguments[1], recState: arguments[2]) + return [out, newConvState, newRecState] + }) private let compiledAttentionPre = CompiledTrace { layer, arguments in let (queries, gate, keys, values) = layer.attentionPreBody(x: arguments[0]) @@ -887,9 +897,10 @@ public class Qwen35TextModelInner: Module { self.compiledSegments = CompiledDecodeSegmentCache( count: segments.count, state: { model, index in - // Everything `segmentBody` reads: the layers it runs, the - // embedding it starts from, the final norm it ends with. - var modules: [Module] = segments[index].layerIndices.map { model.layers[$0] } + // Everything `segmentBody` reads: the layers it runs (with a + // GDN layer's fused projection), the embedding it starts + // from, the final norm it ends with. + var modules = model.traceState(forLayers: segments[index].layerIndices) if index == 0 { modules.append(model.embedTokens) } @@ -995,6 +1006,15 @@ public class Qwen35TextModelInner: Module { return [hiddenStates] + states } + /// The compile state of a trace that runs `indices`: each layer and, for + /// a GDN layer, its fused projection. + func traceState(forLayers indices: [Int]) -> [Module] { + indices.flatMap { index -> [Module] in + let layer = layers[index] + return [layer] + (layer.linearAttn?.fusedProjectionTraceState ?? []) + } + } + /// One decode step through the compiled segments, or nil when this is not /// the plain single-token case the schedule assumes — the caller then /// takes the general path. Segments split at each KV write: the cache @@ -1145,6 +1165,14 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { } } + public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + var checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + checkpoint, layout: .text, tiedWordEmbeddings: configuration.tieWordEmbeddings) + 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 @@ -1155,7 +1183,7 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { // layout is the reliable signal on its own. let shouldShiftNormWeights = hasUnsanitizedConv1d - var weights = weights.filter { !$0.key.contains("mtp.") } + var weights = Qwen35CheckpointPolicy.targetWeights(weights) weights = filterLMHeadWeights( from: weights, tiedWordEmbeddings: configuration.tieWordEmbeddings) @@ -1253,24 +1281,20 @@ 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 - } - - 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 prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + var checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + checkpoint, layout: .wrappedText, + tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings) + checkpoint.weights = try sanitize( + weights: checkpoint.weights, metadata: checkpoint.metadata) + return checkpoint + } - return languageModel.sanitize(weights: sanitized) + public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + let checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + .init(weights: weights), layout: .wrappedText, + tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings) + return languageModel.sanitize(weights: checkpoint.weights) } } diff --git a/Libraries/MLXLLM/Models/Qwen35MTP.swift b/Libraries/MLXLLM/Models/Qwen35MTP.swift index 4665b0ba0c..cd4039601a 100644 --- a/Libraries/MLXLLM/Models/Qwen35MTP.swift +++ b/Libraries/MLXLLM/Models/Qwen35MTP.swift @@ -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() } @@ -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 { @@ -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?) { @@ -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"] + } +} diff --git a/Libraries/MLXLLM/Models/Qwen35MoE.swift b/Libraries/MLXLLM/Models/Qwen35MoE.swift index 59662c8934..c261363699 100644 --- a/Libraries/MLXLLM/Models/Qwen35MoE.swift +++ b/Libraries/MLXLLM/Models/Qwen35MoE.swift @@ -37,21 +37,11 @@ public struct Qwen35Configuration: Codable, Sendable { public class Qwen35MoEModel: Qwen35Model { - override public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { - 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 - } + override public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + let checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + .init(weights: weights), layout: .wrappedText, + tiedWordEmbeddings: languageModel.configuration.tieWordEmbeddings) + var newWeights = checkpoint.weights for l in 0 ..< languageModel.configuration.hiddenLayers { let prefix = "language_model.model.layers.\(l).mlp" diff --git a/Libraries/MLXLLM/README.md b/Libraries/MLXLLM/README.md index 1b7f85c4fe..7310ab61ed 100644 --- a/Libraries/MLXLLM/README.md +++ b/Libraries/MLXLLM/README.md @@ -72,13 +72,16 @@ See [llm-tool](../../Tools/llm-tool) Using LLMs and VLMs from MLXLMCommon is as easy as: ```swift +import Foundation import MLXLLM import MLXLMCommon -import MLXLMHuggingFace -import MLXLMTokenizers +import MLXHuggingFace +import HuggingFace +import Tokenizers let model = try await loadModel( - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen3-4B-4bit" ) let session = ChatSession(model) diff --git a/Libraries/MLXLMCommon/CacheConfiguration.swift b/Libraries/MLXLMCommon/CacheConfiguration.swift index 2e833c516c..9560bd69ed 100644 --- a/Libraries/MLXLMCommon/CacheConfiguration.swift +++ b/Libraries/MLXLMCommon/CacheConfiguration.swift @@ -155,6 +155,11 @@ public struct KVCacheStatus: Sendable, Hashable { layers.count { $0.state == .skipped } } + /// Bytes allocated across all layers. + public var memoryBytes: Int { + layers.reduce(0) { $0 + $1.memoryBytes } + } + /// Inspect a raw cache array using a typed request. public init( cache: [KVCache], diff --git a/Libraries/MLXLMCommon/Chat.swift b/Libraries/MLXLMCommon/Chat.swift index a1b57235ae..1f4b64d460 100644 --- a/Libraries/MLXLMCommon/Chat.swift +++ b/Libraries/MLXLMCommon/Chat.swift @@ -1,5 +1,15 @@ // Copyright © 2025 Apple Inc. +import MLX + +private let messageContentLogger = MLXLogger(label: "MessageContent") + +package enum MessageContentLayout: Sendable { + case imagesThenVideosThenText + case imagesThenText + case textThenImages +} + public enum Chat { public struct Message { /// The role of the message sender. @@ -174,6 +184,44 @@ extension MessageGenerator { } } + package func contentParts( + for message: Chat.Message, layout: MessageContentLayout + ) -> [[String: String]] { + var parts: [[String: String]] = [] + + func appendText(_ text: String) { + parts.append(["type": "text", "text": text]) + } + + func appendImages() { + for image in message.images { + if let marker = image.labelMarkerCharacter { + messageContentLogger.warning( + "Leaving an image name out of the prompt: it holds `\(marker)`, which vision models build their image placeholders from" + ) + } else if let label = image.label { + appendText(UserInput.Image.promptText(forLabel: label)) + } + parts.append(["type": "image"]) + } + } + + switch layout { + case .imagesThenVideosThenText: + appendImages() + parts.append(contentsOf: message.videos.map { _ in ["type": "video"] }) + appendText(message.content) + case .imagesThenText: + appendImages() + appendText(message.content) + case .textThenImages: + appendText(message.content) + appendImages() + } + + return parts + } + public func generate(messages: [Chat.Message]) -> [Message] { var rawMessages: [Message] = [] @@ -228,3 +276,31 @@ public struct NoSystemMessageGenerator: MessageGenerator { .map { generate(message: $0) } } } + +extension UserInput { + + /// Returns the input unchanged if its prompt is not `.chat`. Call this method before a + /// message generator turns the prompt into `.messages`. + package func removingSpecialTokenLabels(using tokenizer: any Tokenizer) -> UserInput { + guard case .chat(let messages) = prompt else { return self } + var screened = self + screened.prompt = .chat( + messages.map { message in + var message = message + message.images = message.images.map { image in + guard let label = image.label, + let names = tokenizer.specialTokenNames(inImageLabel: label) + else { return image } + let named = names.isEmpty ? "a special token" : names.joined(separator: ", ") + messageContentLogger.warning( + "Leaving an image name out of the prompt, because this model's tokenizer reads it as \(named)" + ) + var image = image + image.label = nil + return image + } + return message + }) + return screened + } +} diff --git a/Libraries/MLXLMCommon/CheckpointComponent.swift b/Libraries/MLXLMCommon/CheckpointComponent.swift new file mode 100644 index 0000000000..5ae57470cf --- /dev/null +++ b/Libraries/MLXLMCommon/CheckpointComponent.swift @@ -0,0 +1,82 @@ +// Copyright © 2026 Apple Inc. + +import Foundation + +/// A checkpoint component's serialized namespaces and runtime destination. +public struct CheckpointComponent: Sendable { + public let name: String + public let namespaces: [String] + public let destination: String + public let excludedNamespaces: [String] + + public init( + name: String, namespaces: [String], destination: String, + excludedNamespaces: [String] = [] + ) { + self.name = name + self.namespaces = namespaces + self.destination = destination + self.excludedNamespaces = excludedNamespaces + } + + public enum Source: Equatable, Sendable { + case embedded(namespace: String) + case standalone + } + + public struct Selection { + public let checkpoint: ModelCheckpoint + public let source: Source + } + + /// Resolve one embedded namespace, or a root component explicitly declared by the caller. + /// Unknown paths remain in the result for strict model validation. + public func select(from checkpoint: ModelCheckpoint, standalone: Bool = false) throws + -> Selection + { + let present = Set(namespaces).filter { namespace in + checkpoint.weights.keys.contains { + CheckpointNameMapping.relativeName($0, in: namespace) != nil + } + }.sorted() + guard present.count <= 1 else { + throw SelectionError.ambiguousComponent(name, namespaces: present) + } + if let namespace = present.first { + let exclusions = CheckpointNameMapping(excludedNamespaces.map { .excludePrefix($0) }) + // Select the component before excluding its enclosing sibling namespaces. + let selected = try checkpoint.mapNames { name in + if CheckpointNameMapping.relativeName(name, in: namespace) != nil { return name } + return exclusions.mapName(name) + } + let mapping = CheckpointNameMapping([.replacePrefix(namespace, with: destination)]) + return Selection( + checkpoint: try selected.mapNames(using: mapping), + source: .embedded(namespace: namespace)) + } + guard standalone, !checkpoint.weights.isEmpty else { + throw SelectionError.missingComponent(name) + } + let mapping = CheckpointNameMapping([.replacePrefix("", with: destination)]) + return Selection(checkpoint: try checkpoint.mapNames(using: mapping), source: .standalone) + } + + /// Exclude this component when loading a sibling, including its layer settings. + public func excluding(from checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + try checkpoint.mapNames(using: .init(namespaces.map { .excludePrefix($0) })) + } + + public enum SelectionError: LocalizedError { + case missingComponent(String) + case ambiguousComponent(String, namespaces: [String]) + + public var errorDescription: String? { + switch self { + case .missingComponent(let name): + "Checkpoint does not contain the requested '\(name)' component." + case .ambiguousComponent(let name, let namespaces): + "Checkpoint contains competing '\(name)' namespaces: \(namespaces.joined(separator: ", "))." + } + } + } +} diff --git a/Libraries/MLXLMCommon/CheckpointNameMapping.swift b/Libraries/MLXLMCommon/CheckpointNameMapping.swift new file mode 100644 index 0000000000..c94ad288a9 --- /dev/null +++ b/Libraries/MLXLMCommon/CheckpointNameMapping.swift @@ -0,0 +1,55 @@ +// Copyright © 2026 Apple Inc. + +/// Ordered module-path mappings shared by tensors and per-layer quantization settings. +public struct CheckpointNameMapping: Sendable { + public enum Rule: Sendable { + case replacePrefix(String, with: String) + case excludePrefix(String) + case excludeModule(String) + } + + public let rules: [Rule] + + /// Prefixes are dot-separated module paths without a trailing dot. + /// An empty replacement removes a wrapper; an empty source adds one. + public init(_ rules: [Rule]) { + self.rules = rules + } + + public func mapName(_ name: String) -> String? { + var name = name + for rule in rules { + switch rule { + case .replacePrefix(let source, let destination): + if let relative = Self.relativeName(name, in: source) { + name = Self.join(destination, relative) + } + case .excludePrefix(let prefix): + if Self.relativeName(name, in: prefix) != nil { return nil } + case .excludeModule(let module): + if name.split(separator: ".").contains(Substring(module)) { return nil } + } + } + return name + } + + static func relativeName(_ name: String, in namespace: String) -> String? { + if namespace.isEmpty { return name } + if name == namespace { return "" } + guard name.hasPrefix(namespace + ".") else { return nil } + return String(name.dropFirst(namespace.count + 1)) + } + + private static func join(_ namespace: String, _ name: String) -> String { + if namespace.isEmpty { return name } + if name.isEmpty { return namespace } + return namespace + "." + name + } +} + +extension ModelCheckpoint { + /// Apply the same declarative mapping to tensors, provenance, and layer settings. + public func mapNames(using mapping: CheckpointNameMapping) throws -> Self { + try mapNames(mapping.mapName) + } +} diff --git a/Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md b/Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md index ace17c7540..d37ad9b3d6 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md +++ b/Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md @@ -64,9 +64,10 @@ before inference. A bounded compressed ring cache is not currently implemented. ``ChatSession/cacheStatus()`` is the unified diagnostic surface for legacy and typed configuration. It reports the normalized request, request source, planned or realized phase, flattened cache topology, per-layer capacity source, -strategy state, skip reason, and the container-owned `processedTokenCount`. -Aggregate compressed, pending, skipped, and capacity-application counts are -available on the same value. +strategy state, skip reason, allocated bytes, and the container-owned +`processedTokenCount`. Aggregate compressed, pending, skipped, and +capacity-application counts, and the total `memoryBytes`, are available on the +same value. ``LanguageModel/cacheStatus(parameters:)`` and ``ModelContainer/cacheStatus(parameters:)`` provide the same shape for planned caches. The lower-level ``kvCacheRuntimeReport(cache:configuration:)`` remains diff --git a/Libraries/MLXLMCommon/Documentation.docc/model-compatibility.md b/Libraries/MLXLMCommon/Documentation.docc/model-compatibility.md index 4e64ac7fbd..5cff6240ac 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/model-compatibility.md +++ b/Libraries/MLXLMCommon/Documentation.docc/model-compatibility.md @@ -35,6 +35,50 @@ A repository is a good candidate when the following are true: - The model fits the target machine's memory budget, including weights, KV cache, processor tensors, and prompt context. +## Checkpoint Components And Name Mappings + +``BaseLanguageModel/prepareCheckpoint(_:)`` runs before quantization and strict +parameter validation. Its ``ModelCheckpoint`` value keeps tensor names, per-file +metadata, and per-layer quantization settings together. The loading sequence is: + +1. Read tensors with the metadata of the file that supplied each tensor. +2. Select the requested component and normalize its names and tensor layout. +3. Quantize runtime modules using the normalized layer settings. +4. Update the model with strict parameter validation, then prepare it for inference. + +``CheckpointComponent`` declares accepted serialized namespaces, a runtime +destination, and known sibling namespaces to exclude. It resolves exactly one +embedded component. A root component requires an explicit standalone declaration +from the model's configuration. Unknown paths remain for strict validation; +missing or competing components fail before quantization. + +``CheckpointNameMapping`` applies ordered prefix replacements and module +exclusions at complete path boundaries. Use ``ModelCheckpoint/mapNames(using:)`` +to apply these rules to tensors, source metadata, and layer settings together. +``ModelCheckpoint/mapNames(_:)`` supports custom mappings with the same collision +checks. Aliases cannot overwrite a tensor or a precision declaration. + +The shared loader has no architecture-specific namespace or conversion rules. +Models describe their layouts through these value types and implement numeric +transformations in ``BaseLanguageModel/prepareCheckpoint(_:)``. Gemma3n uses the +same mapping API to remove its serialized wrapper while preserving layer +precision. Qwen uses component selection for its MTP predictor. Existing models +still use their sanitizer through the default implementation; migrate renaming +sanitizers to the checkpoint hook so their precision declarations follow renames. + +Qwen3.5 targets exclude the MTP component. Drafters accept embedded `mtp.*` and +converted `language_model.mtp.*` components, and unprefixed heads declared as +`qwen3_5_mtp`. An ordinary target without MTP weights is not a standalone head. +Unknown tensors and missing parameters still fail strict loading. + +New Swift MTP conversions write `mlx_swift_lm.qwen_mtp.norm_convention=scale`. +`offset` declares upstream zero-centered RMSNorm weights that require adding one; +`scale` declares the runtime multiplicative weights. Explicit declarations take +precedence. For existing exports, standalone heads and `language_model.mtp.*` +use scales; `mtp.*` uses offsets unless its own file declares `format=mlx` or the +caller sets `preconvertedNorms`. Metadata from a target shard does not classify +a separate MTP shard. Conflicting norm declarations fail before model update. + ## Finding The Source Of Truth The model factories and registries are the authoritative compatibility list. diff --git a/Libraries/MLXLMCommon/Documentation.docc/porting.md b/Libraries/MLXLMCommon/Documentation.docc/porting.md index 74e43cc4df..71ef373a9f 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/porting.md +++ b/Libraries/MLXLMCommon/Documentation.docc/porting.md @@ -16,6 +16,13 @@ do development _in_ mlx-swift-lm. ## Porting Models from MLX in Python +Checkpoint namespaces can differ from runtime module paths. Implement +``BaseLanguageModel/prepareCheckpoint(_:)`` with ``CheckpointNameMapping`` for +renames and exclusions, or ``CheckpointComponent`` to select a component from a +larger checkpoint. These operations preserve source metadata and per-layer +precision. Keep architecture-specific numeric conversions in the model's hook. +See for the loading contract and validation rules. + Let's consider a concrete example, [gemma.py](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gemma.py). For reference, here is the current port [Gemma.swift](https://github.com/ml-explore/mlx-swift-lm/blob/main/Libraries/MLXLLM/Models/Gemma.swift). ### Imports @@ -600,11 +607,12 @@ Now we can load the model using `llm-tool` or the `LLMEval` example application, ```swift let modelConfiguration = ModelConfiguration(id: "mlx-community/quantized-gemma-2b-it") -// e.g. TokenizersLoader() from MLXLMTokenizers +// e.g. #huggingFaceTokenizerLoader() from MLXHuggingFace let tokenizerLoader: any TokenizerLoader // This will download the weights and load the model -let container = try await MLXModelFactory.shared.loadContainer( +let container = try await LLMModelFactory.shared.loadContainer( + from: #hubDownloader(), using: tokenizerLoader, configuration: modelConfiguration ) @@ -613,23 +621,14 @@ let container = try await MLXModelFactory.shared.loadContainer( let generateParameters = GenerateParameters() let input = UserInput(prompt: "Are cherries sweet?") -// Run inference -let result = try await modelContainer.perform { [input] context in - // Convert the UserInput into LMInput - let input = try context.processor.prepare(input: input) - - return generate(input: input, parameters: generateParameters, context: context) { tokens in - // This could potentially use NaiveStreamingDetokenizer and print - // text as it was generated - if tokens.count >= 20 { - return .stop - } else { - return .more - } +// Convert the UserInput into LMInput and run inference +let lmInput = try await container.prepare(input: input) +let stream = try await container.generate(input: lmInput, parameters: generateParameters) +for await generation in stream { + if let chunk = generation.chunk { + print(chunk, terminator: "") } } - -print(result.output) ``` ## Notes diff --git a/Libraries/MLXLMCommon/Documentation.docc/upgrade.md b/Libraries/MLXLMCommon/Documentation.docc/upgrade.md index 55f1395fa5..2ad01e1951 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/upgrade.md +++ b/Libraries/MLXLMCommon/Documentation.docc/upgrade.md @@ -40,6 +40,7 @@ let model = try await loadModelContainer(configuration: modelConfiguration) you would convert that like this: ```swift +import Foundation import MLXLLM import MLXLMCommon import MLXHuggingFace @@ -59,6 +60,7 @@ If you want a little more control over the downloader or the tokenizer loader, t expands to this: ```swift +import Foundation import MLXLLM import MLXLMCommon import MLXHuggingFace @@ -93,14 +95,17 @@ let model = try await loadModelContainer(configuration: modelConfiguration) becomes: ```swift +import Foundation import MLXLLM import MLXLMCommon - -import IntegrationPackage +import MLXHuggingFace +import HuggingFace +import Tokenizers let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit let model = try await loadModelContainer( - from: HubClient(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: modelConfiguration ) @@ -132,6 +137,7 @@ now, using the (see packages): ```swift +import Foundation import MLXEmbedders import MLXLMCommon import MLXHuggingFace @@ -149,7 +155,7 @@ let loader = #huggingFaceTokenizerLoader() let container = try await EmbedderModelFactory.shared.loadContainer( from: hub, using: loader, - configuration: configuration + configuration: defaultModelConfiguration ) // use it ... @@ -186,7 +192,12 @@ let container = try await loadModelContainer( ) // After (3.x) – Using HuggingFace integration macros +import Foundation +import MLXLLM +import MLXLMCommon import MLXHuggingFace +import HuggingFace +import Tokenizers let model = try await #huggingFaceLoadModelContainer( configuration: LLMRegistry.gemma3_1B_qat_4bit @@ -202,14 +213,18 @@ Loading from a local directory: let container = try await loadModelContainer(directory: modelDirectory) // After (3.x) -let container = try await loadModelContainer(from: modelDirectory) +let container = try await loadModelContainer( + from: modelDirectory, + using: #huggingFaceTokenizerLoader() +) ``` Loading with a model factory: ```swift let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: modelConfiguration ) ``` @@ -217,13 +232,17 @@ let container = try await LLMModelFactory.shared.loadContainer( Loading an embedder: ```swift +import Foundation import MLXEmbedders +import MLXLMCommon import MLXHuggingFace +import HuggingFace +import Tokenizers -let container = try await EmbedderModelFactory.load( +let container = try await EmbedderModelFactory.shared.loadContainer( from: #hubDownloader(), using: #huggingFaceTokenizerLoader(), - configuration: .configuration(id: "sentence-transformers/all-MiniLM-L6-v2") + configuration: EmbedderRegistry.minilm_l6 ) ``` @@ -243,11 +262,11 @@ let text = tokenizer.decode(tokenIds: ids) ### Loading API -The `hub` parameter (previously `HubApi`) has been replaced with `from` (any `Downloader` or `URL` for a local directory). Functions that previously defaulted to `defaultHubApi` no longer have a default – callers must either pass a `Downloader` explicitly or use the convenience methods in `MLXLMHuggingFace` / `MLXEmbeddersHuggingFace`, which default to `HubClient.default`. +The `hub` parameter (previously `HubApi`) has been replaced with `from` (any `Downloader` or `URL` for a local directory). Functions that previously defaulted to `defaultHubApi` no longer have a default – callers must pass a `Downloader` explicitly (for example the `#hubDownloader()` macro from `MLXHuggingFace`) or use the `#huggingFaceLoadModelContainer` / `#huggingFaceLoadModel` convenience macros. -For most users who were using the default Hub client, adding `import MLXLMHuggingFace` or `import MLXEmbeddersHuggingFace` and using the convenience overloads is sufficient. +For most users who were using the default Hub client, adding `import MLXHuggingFace` (together with `import HuggingFace` and `import Tokenizers`) and using `#hubDownloader()` + `#huggingFaceTokenizerLoader()` — or the `#huggingFaceLoadModelContainer` macro — is sufficient. -Users who were passing a custom `HubApi` instance should create a `HubClient` instead and pass it as the `from` parameter. `HubClient` conforms to `Downloader` via `MLXLMHuggingFace`. +Users who were passing a custom `HubApi` instance should create a `HuggingFace.HubClient` instead and wrap it with `#hubDownloader(_:)` to pass as the `from` parameter. ### `ModelConfiguration` @@ -257,18 +276,54 @@ Users who were passing a custom `HubApi` instance should create a `HubClient` in ### Tokenizer loading -`loadTokenizer(configuration:hub:)` has been removed. Tokenizer loading now uses `AutoTokenizer.from(directory:)` from Swift Tokenizers directly. +`loadTokenizer(configuration:hub:)` has been removed. Tokenizer loading is now done by the `TokenizerLoader` passed to the load functions. `#huggingFaceTokenizerLoader()` uses `AutoTokenizer.from(modelFolder:)` from Swift Transformers. -`replacementTokenizers` (the `TokenizerReplacementRegistry`) has been removed. Use `AutoTokenizer.register(_:for:)` from Swift Tokenizers instead. +`replacementTokenizers` (the `TokenizerReplacementRegistry`) has been removed. To load a tokenizer class that `AutoTokenizer` does not support, pass your own `TokenizerLoader`. ### `defaultHubApi` -The `defaultHubApi` global has been removed. Hugging Face Hub access is now provided by `HubClient.default` from the `HuggingFace` module. +The `defaultHubApi` global has been removed. Hugging Face Hub access is now provided by the `#hubDownloader()` macro from `MLXHuggingFace`, which wraps a default `HuggingFace.HubClient`. ### Low-level APIs - `downloadModel(hub:configuration:progressHandler:)` → `Downloader.download(id:revision:matching:useLatest:progressHandler:)` -- `loadTokenizerConfig(configuration:hub:)` → `AutoTokenizer.from(directory:)` +- `loadTokenizerConfig(configuration:hub:)` → `TokenizerLoader.load(from:)` - `ModelFactory._load(hub:configuration:progressHandler:)` → `_load(configuration: ResolvedModelConfiguration)` - `ModelFactory._loadContainer`: removed (base `loadContainer` now builds the container from `_load`) +### `UserInput.Image`, `UserInput.Video` and `UserInput.Audio` + +These three media types were enums with these cases: + +- `UserInput.Image`: `ciImage`, `url` and `array`. +- `UserInput.Video`: `avAsset`, `url` and `frames`. +- `UserInput.Audio`: `url` and `array`. + +Each type is now a struct with a nested `Source` enum. `Source` has the old cases and their payloads. The struct also has a `source` property and an `init(source:)`. + +`UserInput.Image` also has an optional `label`. A vision message generator writes the label into the prompt as `[label]`, immediately before the image. + +Each old case is now a static function with the same name and argument labels. So the code that creates a media value still compiles: + +```swift +let image = UserInput.Image.url(imageURL) +let videos = urls.map(UserInput.Video.url) +let audio: UserInput.Audio = .array(samples) +``` + +A `switch`, `if case`, `guard case` or `for case` that matches a media value against a case no longer compiles. Match against the `source` of the media value instead: + +```swift +// Before +switch video { +case .url(let url): print(url) +default: break +} + +// After +switch video.source { +case .url(let url): print(url) +default: break +} +``` + diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index ccbc96b4be..c31c2e4a10 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -203,7 +203,7 @@ Beyond that, chose one of the 3 integration methods and add either the adapter p In your Package.swift add a reference to mlx-swift-lm, chosing either the `main` branch or something that tracks versions: ```swift -.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMajor(from: "3.31.3")), +.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.32.3")), ``` Beyond that, chose one of the 3 integration methods and add either the adapter packages OR the implementation packages if using macros/local implemenentation. See . diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 160d99d733..fc961f4455 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -1521,7 +1521,7 @@ private func runSynchronousGenerationLoop( // exits the program right away, those tasks will still be executing and will // hit assertions as the mlx scheduler is torn down. Synchronize with the stream // to make sure it is complete. - Stream().synchronize() + Stream.defaultStream.synchronize() return SynchronousGenerationLoopResult( generatedTokenIds: generatedTokenIds, @@ -2368,7 +2368,7 @@ private func generateLoopTask< // `while let token = iterator.next()` form) allowed one extra asyncEval to be // submitted post-cancellation, which faults if the app has backgrounded // (kIOGPUCommandBufferCallbackErrorBackgroundExecutionNotPermitted). The - // post-loop block below assigns `.cancelled`; Stream().synchronize() still + // post-loop block below assigns `.cancelled`; Stream.defaultStream.synchronize() still // settles any in-flight evaluation at the end of the task body. tokenLoop: while !Task.isCancelled { guard let token = autoreleasepool(invoking: { iterator.next() }) else { break } @@ -2463,7 +2463,7 @@ private func generateLoopTask< _ = continuation.yield(handler.infoEvent(info)) // Synchronize with the stream to ensure tasks are completed - Stream().synchronize() + Stream.defaultStream.synchronize() // Finalize the stream continuation.finish() diff --git a/Libraries/MLXLMCommon/KVCacheConfiguration.swift b/Libraries/MLXLMCommon/KVCacheConfiguration.swift index 8428df619f..513dea534a 100644 --- a/Libraries/MLXLMCommon/KVCacheConfiguration.swift +++ b/Libraries/MLXLMCommon/KVCacheConfiguration.swift @@ -425,6 +425,9 @@ public struct KVCacheLayerStatus: Sendable, Hashable { public let state: State public let resolvedStrategy: KVCacheStrategyIdentifier? public let reason: Reason? + /// Bytes allocated for this layer's arrays, including space reserved for + /// tokens not yet written. + public let memoryBytes: Int package init( path: [Int], @@ -432,7 +435,8 @@ public struct KVCacheLayerStatus: Sendable, Hashable { capacitySource: CapacitySource?, state: State, resolvedStrategy: KVCacheStrategyIdentifier?, - reason: Reason? + reason: Reason?, + memoryBytes: Int ) { self.path = path self.kind = kind @@ -440,6 +444,7 @@ public struct KVCacheLayerStatus: Sendable, Hashable { self.state = state self.resolvedStrategy = resolvedStrategy self.reason = reason + self.memoryBytes = memoryBytes } } diff --git a/Libraries/MLXLMCommon/KVCacheRuntime.swift b/Libraries/MLXLMCommon/KVCacheRuntime.swift index b546fbcfcc..d5296709a3 100644 --- a/Libraries/MLXLMCommon/KVCacheRuntime.swift +++ b/Libraries/MLXLMCommon/KVCacheRuntime.swift @@ -194,6 +194,7 @@ extension KVCacheLeaf { ) -> KVCacheLayerStatus { let requested = configuration.strategy.identifier let layerKind = CacheLayerKind(cache: cache) + let memoryBytes = cache.innerState().reduce(0) { $0 + $1.nbytes } let capacitySource: KVCacheLayerStatus.CapacitySource? = switch self.kind { case .recurrent: @@ -215,7 +216,8 @@ extension KVCacheLeaf { capacitySource: capacitySource, state: state, resolvedStrategy: resolvedStrategy, - reason: reason) + reason: reason, + memoryBytes: memoryBytes) } switch self.kind { diff --git a/Libraries/MLXLMCommon/LanguageModel.swift b/Libraries/MLXLMCommon/LanguageModel.swift index d22f354774..6d5055c9cd 100644 --- a/Libraries/MLXLMCommon/LanguageModel.swift +++ b/Libraries/MLXLMCommon/LanguageModel.swift @@ -6,15 +6,21 @@ import MLXNN /// Abstract form of a model that processes language. public protocol BaseLanguageModel: Module { + /// Normalize tensor names, values, and layer settings before loading the checkpoint. + /// The default implementation calls ``sanitize(weights:metadata:)``. + func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint + /// Optionally preprocess the weights and modify / remove values as needed. - func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] + /// Errors propagate to the checkpoint loader. + func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] /// Optionally preprocess the weights with access to safetensor metadata. /// /// The default implementation forwards to ``sanitize(weights:)``. /// Models can override this to inspect metadata (e.g. check `metadata["format"] == "mlx"`) /// and skip or customize sanitization accordingly. - func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: MLXArray] + func sanitize(weights: [String: MLXArray], metadata: [String: String]) throws -> [String: + MLXArray] } /// Weight files a model needs that no naming convention or `model.safetensors.index.json` @@ -46,14 +52,21 @@ public protocol ModelConversionMetadataProvider { } extension BaseLanguageModel { + public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + var checkpoint = checkpoint + checkpoint.weights = try sanitize( + weights: checkpoint.weights, metadata: checkpoint.metadata) + return checkpoint + } + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { weights } - public func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: + public func sanitize(weights: [String: MLXArray], metadata: [String: String]) throws -> [String: MLXArray] { - sanitize(weights: weights) + try sanitize(weights: weights) } } diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 6de6a7b652..d36db04be9 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -129,18 +129,21 @@ private final class ConcurrentLoadState: @unchecked Sendable { if firstError == nil { firstError = error } } - /// Weights merged in file order (a later file overwrites a duplicate name, matching the - /// serial loader) and the first file's metadata. - func result() throws -> (weights: [String: MLXArray], metadata: [String: String]) { + /// Preserve file order and tensor metadata, including later-file-wins duplicates. + func result() throws -> ModelCheckpoint { lock.lock() defer { lock.unlock() } if let firstError { throw firstError } var weights = [String: MLXArray]() - for fileWeights in perFile { + var weightMetadata = [String: [String: String]]() + for (index, fileWeights) in perFile.enumerated() { weights.merge(fileWeights) { _, new in new } + for name in fileWeights.keys { + weightMetadata[name] = perFileMetadata[index] + } } let metadata = perFileMetadata.first { !$0.isEmpty } ?? [:] - return (weights, metadata) + return ModelCheckpoint(weights: weights, metadata: metadata, weightMetadata: weightMetadata) } } @@ -154,6 +157,11 @@ private final class ConcurrentLoadState: @unchecked Sendable { func loadWeightArrays(urls: [URL]) throws -> ( weights: [String: MLXArray], metadata: [String: String] ) { + let checkpoint = try loadModelCheckpoint(urls: urls) + return (checkpoint.weights, checkpoint.metadata) +} + +func loadModelCheckpoint(urls: [URL]) throws -> ModelCheckpoint { struct WorkItem { let file: Int let url: URL @@ -356,7 +364,7 @@ private func topLevelSafetensorURLs(in modelDirectory: URL) -> [URL] { /// /// This is typically called via ``GenericModelFactory/load(from:using:configuration:useLatest:progressHandler:)``. /// This function loads model weight `safetensor` files in the given `modelDirectory`, -/// calls ``BaseLanguageModel/sanitize(weights:metadata:)`` to allow per-model preprocessing, +/// calls ``BaseLanguageModel/prepareCheckpoint(_:)`` to allow per-model preprocessing, /// applies optional quantization, and /// updates the model with the weights. Derived inference-only state is prepared after the /// checkpoint update and before the model is evaluated and returned to callers. @@ -371,28 +379,23 @@ public func loadWeights( perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil, weightFileSelection: WeightFileSelection = .automatic ) throws { - // load the weights and collect metadata from the first safetensor file - var weights = [String: MLXArray]() - var metadata = [String: String]() let additionalFiles = (model as? any AdditionalWeightFilesProviding)?.additionalWeightFiles let weightURLs = try safetensorWeightURLs( in: modelDirectory, selection: weightFileSelection, additionalFiles: additionalFiles ?? []) - (weights, metadata) = try loadWeightArrays(urls: weightURLs) - - // per-model cleanup (models can inspect metadata to customize behavior) - weights = model.sanitize(weights: weights, metadata: metadata) + var checkpoint = try loadModelCheckpoint(urls: weightURLs) + checkpoint.perLayerQuantization = + perLayerQuantization + ?? quantization.map { .init(quantization: $0, perLayerQuantization: [:]) } + checkpoint = try model.prepareCheckpoint(checkpoint) + let weights = checkpoint.weights // quantize if needed - if quantization != nil || perLayerQuantization != nil { + if let perLayerQuantization = checkpoint.perLayerQuantization { quantize(model: model) { path, module in if weights["\(path).scales"] != nil { - if let perLayerQuantization { - return perLayerQuantization.quantization(layer: path)?.asTuple - } else { - return quantization?.asTuple - } + return perLayerQuantization.quantization(layer: path)?.asTuple } else { return nil } diff --git a/Libraries/MLXLMCommon/ModelCheckpoint.swift b/Libraries/MLXLMCommon/ModelCheckpoint.swift new file mode 100644 index 0000000000..2a2ee812d2 --- /dev/null +++ b/Libraries/MLXLMCommon/ModelCheckpoint.swift @@ -0,0 +1,76 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// Checkpoint tensors and the metadata and quantization settings that describe them. +/// +/// Models can normalize a checkpoint in ``BaseLanguageModel/prepareCheckpoint(_:)`` before +/// quantization and strict parameter validation. Name mappings apply to tensors and layer +/// settings together, so a renamed layer keeps its declared precision. +public struct ModelCheckpoint { + public var weights: [String: MLXArray] + public var perLayerQuantization: BaseConfiguration.PerLayerQuantization? + + /// The first nonempty file metadata, for compatibility with existing sanitizers. + public let metadata: [String: String] + private var weightMetadata: [String: [String: String]] + + public init( + weights: [String: MLXArray], metadata: [String: String] = [:], + weightMetadata: [String: [String: String]] = [:], + perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil + ) { + self.weights = weights + self.metadata = metadata + self.weightMetadata = weightMetadata + self.perLayerQuantization = perLayerQuantization + } + + /// Metadata from the file that supplied this tensor, including an empty metadata block. + public func metadata(forWeight name: String) -> [String: String] { + weightMetadata[name] ?? metadata + } + + /// Rename or exclude complete module paths, including their quantization settings. + /// A `nil` name excludes the tensor or layer. Aliases must not overwrite each other. + public func mapNames(_ transform: (String) -> String?) throws -> Self { + var result = self + result.weights = [:] + result.weightMetadata = [:] + var sources = [String: String]() + for name in weights.keys.sorted() { + guard let mapped = transform(name) else { continue } + if let previous = sources.updateValue(name, forKey: mapped) { + throw MappingError.collision(previous, name, destination: mapped) + } + result.weights[mapped] = weights[name] + result.weightMetadata[mapped] = metadata(forWeight: name) + } + if let perLayerQuantization { + var settings = [String: BaseConfiguration.QuantizationOption]() + sources = [:] + for name in perLayerQuantization.perLayerQuantization.keys.sorted() { + guard let mapped = transform(name) else { continue } + if let previous = sources.updateValue(name, forKey: mapped) { + throw MappingError.collision(previous, name, destination: mapped) + } + settings[mapped] = perLayerQuantization.perLayerQuantization[name] + } + result.perLayerQuantization = .init( + quantization: perLayerQuantization.quantization, perLayerQuantization: settings) + } + return result + } + + public enum MappingError: LocalizedError { + case collision(String, String, destination: String) + + public var errorDescription: String? { + switch self { + case .collision(let first, let second, let destination): + "Checkpoint names '\(first)' and '\(second)' both map to '\(destination)'." + } + } + } +} diff --git a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift index bee9a7ac8b..1c1c46f1c2 100644 --- a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift +++ b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift @@ -707,9 +707,15 @@ public func loadParoQuantModel( // derivation — stays live code on every load. let preSanitizeWeights = weights - // 7. Model-specific sanitization - weights = model.sanitize(weights: weights) - markPhase("sanitize") + // 7. Model-specific checkpoint preparation + let checkpoint = try model.prepareCheckpoint( + .init( + weights: weights, + perLayerQuantization: .init( + quantization: .init(groupSize: paroConfig.groupSize, bits: paroConfig.bits), + perLayerQuantization: [:]))) + weights = checkpoint.weights + markPhase("prepareCheckpoint") // 8a. Swap SwitchGLU → RotateSwitchGLU where shared rotation keys exist. // Must precede the dense `.theta` scan in patchRotationLayers (the @@ -733,7 +739,7 @@ public func loadParoQuantModel( guard isCheckpointQuantizedLayer(path: path, weights: weights) else { return nil } - return (paroConfig.groupSize, paroConfig.bits, .affine) + return checkpoint.perLayerQuantization?.quantization(layer: path)?.asTuple } markPhase("quantize") @@ -765,7 +771,7 @@ public func loadParoQuantModel( guard isParoQuantIOLayer(path: path, module: module) else { return nil } - return (paroConfig.groupSize, paroConfig.bits, .affine) + return checkpoint.perLayerQuantization?.quantization(layer: path)?.asTuple } markPhase("quantizeIO") diff --git a/Libraries/MLXLMCommon/Qwen35Checkpoint.swift b/Libraries/MLXLMCommon/Qwen35Checkpoint.swift new file mode 100644 index 0000000000..9c5cff2165 --- /dev/null +++ b/Libraries/MLXLMCommon/Qwen35Checkpoint.swift @@ -0,0 +1,245 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// The serialized MTP component is independent of its runtime `mtp` wrapper. +package struct Qwen35CheckpointPolicy: Sendable { + package enum Layout: Sendable { + case embedded + case standalone + } + + package let layout: Layout + package let preconvertedNorms: Bool + + package init(layout: Layout, preconvertedNorms: Bool) { + self.layout = layout + self.preconvertedNorms = preconvertedNorms + } + + package static let normMetadataKey = "mlx_swift_lm.qwen_mtp.norm_convention" + private static let mtpComponent = CheckpointComponent( + name: "Qwen MTP", namespaces: ["mtp", "language_model.mtp"], destination: "mtp", + excludedNamespaces: [ + "model", "language_model.model", "language_model.lm_head", "lm_head", + "vision_tower", "visual", + ]) + private static let normSuffixes = [ + "mtp.norm.weight", "mtp.pre_fc_norm_embedding.weight", "mtp.pre_fc_norm_hidden.weight", + ".input_layernorm.weight", ".post_attention_layernorm.weight", + ".q_norm.weight", ".k_norm.weight", + ] + + package static func targetWeights(_ weights: [String: MLXArray]) -> [String: MLXArray] { + let mapping = CheckpointNameMapping(mtpComponent.namespaces.map { .excludePrefix($0) }) + return weights.filter { name, _ in mapping.mapName(name) != nil } + } + + package enum TargetLayout { + case text + case wrappedText + case vision + } + + package static func prepareTarget( + _ checkpoint: ModelCheckpoint, layout: TargetLayout, tiedWordEmbeddings: Bool + ) throws -> ModelCheckpoint { + var rules = [CheckpointNameMapping.Rule]() + if tiedWordEmbeddings { rules.append(.excludeModule("lm_head")) } + if layout == .vision { + rules.append(.replacePrefix("model.visual", with: "vision_tower")) + } else { + rules += [.excludePrefix("model.visual"), .excludePrefix("vision_tower")] + } + rules.append(.replacePrefix("model.language_model", with: "model")) + if layout == .text { + rules.append(.replacePrefix("language_model", with: "")) + } else { + rules += [ + .replacePrefix("model", with: "language_model.model"), + .replacePrefix("lm_head", with: "language_model.lm_head"), + ] + } + let selected = try mtpComponent.excluding(from: checkpoint) + return try selected.mapNames(using: .init(rules)) + } + + package func prepare( + _ checkpoint: ModelCheckpoint, mtpNumHiddenLayers: Int, numExperts: Int + ) throws -> ModelCheckpoint { + let selection = try Self.mtpComponent.select( + from: checkpoint, standalone: layout == .standalone) + var prepared = selection.checkpoint + + var conventions = Set() + for name in prepared.weights.keys.sorted() where Self.isNorm(name) { + let convention = try normConvention( + metadata: prepared.metadata(forWeight: name), source: selection.source) + conventions.insert(convention) + if convention == .offset, let value = prepared.weights[name], value.ndim == 1 { + prepared.weights[name] = value + MLXArray(1, dtype: value.dtype) + } + } + guard conventions.count <= 1 else { throw LoadingError.conflictingNormConventions } + try prepareExperts( + &prepared, layers: max(mtpNumHiddenLayers, 1), numExperts: numExperts) + return prepared + } + + private enum NormConvention: String { + case offset + case scale + } + + private func normConvention(metadata: [String: String], source: CheckpointComponent.Source) + throws -> NormConvention + { + if let declared = metadata[Self.normMetadataKey] { + guard let convention = NormConvention(rawValue: declared) else { + throw LoadingError.unsupportedNormConvention(declared) + } + return convention + } + if preconvertedNorms || source != .embedded(namespace: "mtp") + || metadata["format"]?.lowercased() == "mlx" + { + return .scale + } + return .offset + } + + private static func isNorm(_ name: String) -> Bool { + normSuffixes.contains { name.hasSuffix($0) } + } + + private func prepareExperts( + _ checkpoint: inout ModelCheckpoint, layers: Int, numExperts: Int + ) throws { + for layer in 0 ..< layers { + let prefix = "mtp.layers.\(layer).mlp" + for projection in ["gate_proj", "up_proj", "down_proj"] { + let source = "\(prefix).experts" + let destination = "\(prefix).switch_mlp.\(projection)" + let modules = (0 ..< numExperts).map { "\(source).\($0).\(projection)" } + guard modules.contains(where: { checkpoint.weights["\($0).weight"] != nil }) else { + continue + } + try mergeQuantization(&checkpoint, modules: modules, destination: destination) + for parameter in ["weight", "scales", "biases"] { + let names = modules.map { "\($0).\(parameter)" } + guard names.contains(where: { checkpoint.weights[$0] != nil }) else { continue } + let arrays = try names.map { name in + guard let array = checkpoint.weights[name] else { + throw LoadingError.incompleteExperts(name) + } + return array + } + guard arrays.allSatisfy({ $0.shape == arrays[0].shape }) else { + throw LoadingError.incompleteExperts(source) + } + let name = "\(destination).\(parameter)" + guard checkpoint.weights[name] == nil else { + throw LoadingError.ambiguousLayout + } + checkpoint.weights[name] = stacked(arrays) + for name in names { checkpoint.weights.removeValue(forKey: name) } + } + for module in modules { + checkpoint.perLayerQuantization?.perLayerQuantization.removeValue( + forKey: module) + } + } + + let fused = "\(prefix).experts.gate_up_proj" + if let value = checkpoint.weights[fused] { + guard value.ndim >= 2, value.dim(-2) % 2 == 0 else { + throw LoadingError.incompleteExperts(fused) + } + let destinations = ["gate_proj", "up_proj"].map { "\(prefix).switch_mlp.\($0)" } + for destination in destinations { + try mergeQuantization(&checkpoint, modules: [fused], destination: destination) + } + for parameter in ["weight", "scales", "biases"] { + let source = parameter == "weight" ? fused : "\(fused)_\(parameter)" + guard let array = checkpoint.weights.removeValue(forKey: source) else { + continue + } + guard array.ndim >= 2, array.dim(-2) == value.dim(-2) else { + throw LoadingError.incompleteExperts(source) + } + let mid = array.dim(-2) / 2 + for (index, destination) in destinations.enumerated() { + let name = "\(destination).\(parameter)" + guard checkpoint.weights[name] == nil else { + throw LoadingError.ambiguousLayout + } + checkpoint.weights[name] = + index == 0 + ? array[.ellipsis, .. [String: MLXArray] { - var sanitized = weights.filter { key, _ in key.hasPrefix("mtp.") } - - for layer in 0 ..< max(mtpNumHiddenLayers, 1) { - let prefix = "mtp.layers.\(layer).mlp" - if numExperts > 0, - sanitized["\(prefix).experts.0.up_proj.weight"] != nil - { - for projection in ["gate_proj", "up_proj", "down_proj"] { - let toJoin = (0 ..< numExperts).map { expert in - sanitized.removeValue( - forKey: "\(prefix).experts.\(expert).\(projection).weight")! - } - sanitized["\(prefix).switch_mlp.\(projection).weight"] = MLX.stacked(toJoin) - } - } - - let gateUpKey = "\(prefix).experts.gate_up_proj" - if let gateUp = sanitized.removeValue(forKey: gateUpKey) { - let mid = gateUp.dim(-2) / 2 - sanitized["\(prefix).switch_mlp.gate_proj.weight"] = - gateUp[.ellipsis, .. MLXArray +} + private struct CausalLMReranker { let tokenizer: any Tokenizer let inputProcessor: any RerankerInputProcessor @@ -1053,6 +1059,13 @@ private struct CausalLMReranker { count: maxLength - document.input.tokenIds.count) } let tokens = MLXArray(inputIDs).reshaped(batch.count, maxLength) + if let model = model as? any CausalRerankerModel { + let logits = model.lastTokenLogits( + tokens, sequenceLengths: batch.map(\.input.tokenIds.count)) + return batch.indices.map { row in + probability(logits: logits[row], tokens: classifierTokens) + } + } let logits = model(LMInput.Text(tokens: tokens), cache: nil, state: nil).logits let scores = batch.enumerated().map { row, document in probability( diff --git a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift index 42a52763ac..7162418267 100644 --- a/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift +++ b/Libraries/MLXLMCommon/Tool/Parsers/GemmaFunctionParser.swift @@ -55,7 +55,7 @@ public struct GemmaFunctionParser: ToolCallParser, Sendable { // value is never truncated and its remainder never becomes a stray key. for field in scanner.splitTopLevel(body, separator: ",") { guard let colon = scanner.firstTopLevelIndex(of: ":", in: field) else { continue } - let key = String(field[.. String { + guard key.count >= 2 * marker.count, key.hasPrefix(marker), key.hasSuffix(marker) + else { return String(key) } + return String(key.dropFirst(marker.count).dropLast(marker.count)) + } + + /// Parses a brace-form literal, then retries with nested marker strings quoted as JSON. + /// The original text goes first: FunctionGemma's `` can sit inside a JSON-quoted + /// string, as in `{a:"hi"}`, which the rewrite would break. + private func parseStructured(_ literal: String, marker: String) -> (any Sendable)? { + if let value = structuredValues.parse(literal) { return value } + guard literal.contains(marker) else { return nil } + return structuredValues.parse(Self.quotingMarkedStrings(literal, marker: marker)) + } + + /// Rewrites each `marker…marker` span as a JSON string literal. + /// An unterminated marker leaves the rest of the text unchanged. + private static func quotingMarkedStrings(_ literal: String, marker: String) -> String { + var out = "" + var rest = literal[...] + while let open = rest.range(of: marker) { + out += rest[.. String { + var out = "\"" + for scalar in text.unicodeScalars { + switch scalar { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\n": out += "\\n" + case "\r": out += "\\r" + case "\t": out += "\\t" + case "\u{08}": out += "\\b" + case "\u{0C}": out += "\\f" + case _ where scalar.value < 0x20: + let hex = String(scalar.value, radix: 16, uppercase: true) + out += (scalar.value < 0x10 ? "\\u000" : "\\u00") + hex + default: + out.unicodeScalars.append(scalar) + } + } + return out + "\"" + } + /// Whether a declared schema type is one the dialect writes in brace form. private static func isStructured(_ type: String) -> Bool { let type = type.lowercased() diff --git a/Libraries/MLXLMCommon/TurboQuantKVCache.swift b/Libraries/MLXLMCommon/TurboQuantKVCache.swift index 4234953cba..dbb7ce2220 100644 --- a/Libraries/MLXLMCommon/TurboQuantKVCache.swift +++ b/Libraries/MLXLMCommon/TurboQuantKVCache.swift @@ -1452,24 +1452,18 @@ public class TurboQuantKVCache: BaseKVCache { /// Does NOT include codec overhead (rotation matrices, codebooks) which is shared across layers. /// In rawKeyMode: rawKeys is always present (FP16 keys), no keyPackedMSE/keyNorms. public var memoryBytes: Int { - var total = 0 - // Raw FP16 buffers (always present in rawKeyMode for keys, or during prefill) - if let rk = rawKeys { total += rk.shape.reduce(1, *) * rk.dtype.bytesPerElement } - if let rv = rawValues { total += rv.shape.reduce(1, *) * rv.dtype.bytesPerElement } - // Compressed storage (K only present when NOT rawKeyMode) - if let kw = affKeyW { total += kw.shape.reduce(1, *) * kw.dtype.bytesPerElement } - if let ks = affKeyScales { total += ks.shape.reduce(1, *) * ks.dtype.bytesPerElement } - if let kb = affKeyBiases { total += kb.shape.reduce(1, *) * kb.dtype.bytesPerElement } - if let kp = keyPackedMSE { total += kp.shape.reduce(1, *) * kp.dtype.bytesPerElement } - if let kn = keyNorms { total += kn.shape.reduce(1, *) * kn.dtype.bytesPerElement } - if let vp = valPackedMSE { total += vp.shape.reduce(1, *) * vp.dtype.bytesPerElement } - if let vn = valNorms { total += vn.shape.reduce(1, *) * vn.dtype.bytesPerElement } - if let kcs = keyCalibScale { total += kcs.shape.reduce(1, *) * kcs.dtype.bytesPerElement } - return total + innerState().reduce(0) { $0 + $1.nbytes } } // MARK: - State / Trim + override public func innerState() -> [MLXArray] { + [ + rawKeys, rawValues, affKeyW, affKeyScales, affKeyBiases, + keyPackedMSE, keyNorms, valPackedMSE, valNorms, keyCalibScale, + ].compactMap { $0 } + } + override public var state: [MLXArray] { get { if isCompressed { diff --git a/Libraries/MLXLMCommon/TurboQuantKernels.swift b/Libraries/MLXLMCommon/TurboQuantKernels.swift index d455f470a5..bf1e963a6e 100644 --- a/Libraries/MLXLMCommon/TurboQuantKernels.swift +++ b/Libraries/MLXLMCommon/TurboQuantKernels.swift @@ -286,12 +286,14 @@ enum TurboQuantMetalKernels { if (pos_in_block < half_block) { a = shared_buf[block_id * block_size + pos_in_block]; b = shared_buf[block_id * block_size + pos_in_block + half_block]; - shared_buf[d] = a + b; } else { a = shared_buf[block_id * block_size + pos_in_block - half_block]; b = shared_buf[block_id * block_size + pos_in_block]; - shared_buf[d] = a - b; } + float next = (pos_in_block < half_block) ? (a + b) : (a - b); + // All groups must finish reading this stage before any overwrite. + threadgroup_barrier(mem_flags::mem_threadgroup); + shared_buf[d] = next; threadgroup_barrier(mem_flags::mem_threadgroup); } wht_val = shared_buf[d]; diff --git a/Libraries/MLXLMCommon/UserInput+Audio.swift b/Libraries/MLXLMCommon/UserInput+Audio.swift index 28a30c5a69..0110d17e47 100644 --- a/Libraries/MLXLMCommon/UserInput+Audio.swift +++ b/Libraries/MLXLMCommon/UserInput+Audio.swift @@ -22,7 +22,7 @@ extension UserInput.Audio { public func asMLXArray(processing: UserInput.AudioProcessing = .init()) async throws -> MLXArray { - switch self { + switch source { case .url(let url): #if canImport(AVFoundation) let asset = AVURLAsset(url: url) diff --git a/Libraries/MLXLMCommon/UserInput.swift b/Libraries/MLXLMCommon/UserInput.swift index afaeca40dd..f56151e308 100644 --- a/Libraries/MLXLMCommon/UserInput.swift +++ b/Libraries/MLXLMCommon/UserInput.swift @@ -76,13 +76,36 @@ public struct UserInput { } /// Representation of a video resource. - public enum Video { + public struct Video { + + public enum Source { + #if canImport(AVFoundation) + case avAsset(AVAsset) + #endif + case url(URL) + /// Useful for decoded frames held in memory + case frames([VideoFrame]) + } + + public var source: Source + + public init(source: Source) { + self.source = source + } + #if canImport(AVFoundation) - case avAsset(AVAsset) + public static func avAsset(_ asset: AVAsset) -> Self { + Self(source: .avAsset(asset)) + } #endif - case url(URL) - /// Useful for decoded frames held in memory - case frames([VideoFrame]) + + public static func url(_ url: URL) -> Self { + Self(source: .url(url)) + } + + public static func frames(_ frames: [VideoFrame]) -> Self { + Self(source: .frames(frames)) + } #if canImport(AVFoundation) @available( @@ -90,7 +113,7 @@ public struct UserInput { message: "Use MediaProcessing.asProcessedSequence() with the Video directly" ) public func asAVAsset() -> AVAsset { - switch self { + switch source { case .avAsset(let asset): return asset case .url(let url): @@ -105,16 +128,75 @@ public struct UserInput { } /// Representation of an image resource. - public enum Image { + public struct Image { + + public enum Source { + #if canImport(CoreImage) + case ciImage(CIImage) + #endif + case url(URL) + case array(MLXArray) + } + + public var source: Source + + /// Text that a vision message generator writes into the prompt as `[label]`, + /// immediately before this image. The generator leaves out and logs a label that + /// contains `<`, `>`, `|`, `[` or `]`. A vision processor also leaves out a label + /// whose `[label]` form contains a special token, such as `IMG` on Mistral3. + public var label: String? + + /// The characters that delimit image placeholders, such as `<|image_pad|>` and `[IMG]`. + package static let markerCharacters: Set = ["<", ">", "|", "[", "]"] + + package var labelMarkerCharacter: Character? { + label?.first(where: Self.markerCharacters.contains) + } + + package static func promptText(forLabel label: String) -> String { + "[\(label)]" + } + + public init(source: Source, label: String? = nil) { + self.source = source + self.label = label + } + #if canImport(CoreImage) - case ciImage(CIImage) + public static func ciImage(_ image: CIImage, label: String? = nil) -> Self { + Self(source: .ciImage(image), label: label) + } + + /// Makes `images.map(UserInput.Image.ciImage)` compile, because a function value + /// cannot use the default `label`. + public static func ciImage(_ image: CIImage) -> Self { + Self(source: .ciImage(image)) + } #endif - case url(URL) - case array(MLXArray) + + public static func url(_ url: URL, label: String? = nil) -> Self { + Self(source: .url(url), label: label) + } + + /// Makes `urls.map(UserInput.Image.url)` compile, because a function value cannot + /// use the default `label`. + public static func url(_ url: URL) -> Self { + Self(source: .url(url)) + } + + public static func array(_ array: MLXArray, label: String? = nil) -> Self { + Self(source: .array(array), label: label) + } + + /// Makes `arrays.map(UserInput.Image.array)` compile, because a function value + /// cannot use the default `label`. + public static func array(_ array: MLXArray) -> Self { + Self(source: .array(array)) + } #if canImport(CoreImage) public func asCIImage() throws -> CIImage { - switch self { + switch source { case .ciImage(let image): return image @@ -173,9 +255,26 @@ public struct UserInput { } /// Representation of an audio resource. - public enum Audio { - case url(URL) - case array(MLXArray) + public struct Audio { + + public enum Source { + case url(URL) + case array(MLXArray) + } + + public var source: Source + + public init(source: Source) { + self.source = source + } + + public static func url(_ url: URL) -> Self { + Self(source: .url(url)) + } + + public static func array(_ array: MLXArray) -> Self { + Self(source: .array(array)) + } // See also UserInput+Audio } @@ -532,6 +631,7 @@ public protocol UserInputProcessor: Sendable { public struct MessageGeneratorUserInputProcessor: UserInputProcessor { private let processor: any UserInputProcessor private let messageGenerator: any MessageGenerator + private let tokenizer: (any Tokenizer)? public init( processor: any UserInputProcessor, @@ -539,10 +639,21 @@ public struct MessageGeneratorUserInputProcessor: UserInputProcessor { ) { self.processor = processor self.messageGenerator = messageGenerator + self.tokenizer = nil + } + + package init( + processor: any UserInputProcessor, + messageGenerator: any MessageGenerator, + tokenizer: any Tokenizer + ) { + self.processor = processor + self.messageGenerator = messageGenerator + self.tokenizer = tokenizer } public func prepare(input: UserInput) async throws -> LMInput { - var input = input + var input = tokenizer.map { input.removingSpecialTokenLabels(using: $0) } ?? input input.prompt = .messages(messageGenerator.generate(from: input)) return try await processor.prepare(input: input) } @@ -576,3 +687,36 @@ public struct StandInUserInputProcessor: UserInputProcessor { throw UserInputError.notImplemented } } + +extension Tokenizer { + + /// The special tokens that `[label]` encodes to, or `nil` if it encodes to none. + /// An empty array still means that `[label]` contains a special token. + package func specialTokenNames(inImageLabel label: String) -> [String]? { + // Special tokens that `encode` adds, such as BOS, would otherwise flag every label. + let ids = encode( + text: UserInput.Image.promptText(forLabel: label), addSpecialTokens: false) + guard containsSpecialToken(ids) else { return nil } + return specialTokenNames(inIDs: ids) + } + + /// The `Tokenizer` protocol cannot list special tokens, so this function compares a + /// decode with and without `skipSpecialTokens`. An added token without the special + /// flag passes, so callers must refuse the marker characters too. + private func containsSpecialToken(_ ids: [Int]) -> Bool { + decode(tokenIds: ids, skipSpecialTokens: false) + != decode(tokenIds: ids, skipSpecialTokens: true) + } + + /// Each name comes from `convertIdToToken`, because decoding one id can change the + /// token's text. + private func specialTokenNames(inIDs ids: [Int]) -> [String] { + var names: [String] = [] + var seen = Set() + for id in ids where containsSpecialToken([id]) { + guard seen.insert(id).inserted else { continue } + names.append(convertIdToToken(id) ?? "token \(id)") + } + return names + } +} diff --git a/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift index bcb74083c1..bc0cedf55a 100644 --- a/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift +++ b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift @@ -154,7 +154,12 @@ public class VarianceNormalizedKVCache: BaseKVCache, KVCacheAttentionProtocol, } public override func innerState() -> [MLXArray] { - state + (tileSlabs.map(\.records) + pendingTiles).flatMap { + [ + $0.keyWeight, $0.keyScales, $0.keyBiases, $0.keyColumnScales, + $0.valueWeight, $0.valueScales, $0.valueBiases, $0.valueColumnScales, + ] + } + [tailKeys, tailValues].compactMap { $0 } } private func rotate(_ x: MLXArray) -> MLXArray { diff --git a/Libraries/MLXRerankers/Documentation.docc/Documentation.md b/Libraries/MLXRerankers/Documentation.docc/Documentation.md index 92e85cef24..9a620e0339 100644 --- a/Libraries/MLXRerankers/Documentation.docc/Documentation.md +++ b/Libraries/MLXRerankers/Documentation.docc/Documentation.md @@ -129,6 +129,9 @@ Jina reranker v3 accepts at most 64 documents in one listwise request. Pairwise Qwen rerankers use token-budgeted micro-batches and check task cancellation between input encoding and model batches. +Qwen3 projects only each row's final valid hidden state when scoring a batch, avoiding +vocabulary logits for the other input tokens. Singleton requests retain cached prefill. + ## Model Compatibility Single-logit encoder rerankers use a sigmoid-normalized relevance score. Multi-label encoder checkpoints diff --git a/Libraries/MLXVLM/MediaProcessing.swift b/Libraries/MLXVLM/MediaProcessing.swift index 9b27a0adff..546855e741 100644 --- a/Libraries/MLXVLM/MediaProcessing.swift +++ b/Libraries/MLXVLM/MediaProcessing.swift @@ -404,7 +404,7 @@ public enum MediaProcessing { maxFrames: Int = Int.max, frameProcessing: (VideoFrame) throws -> VideoFrame = { $0 } ) async throws -> ProcessedFrames { - switch video { + switch video.source { case .avAsset(let asset): try await Self.validateAsset(asset) return try await _asProcessedSequence( diff --git a/Libraries/MLXVLM/Models/FastVLM.swift b/Libraries/MLXVLM/Models/FastVLM.swift index 772943b778..308cda0dba 100644 --- a/Libraries/MLXVLM/Models/FastVLM.swift +++ b/Libraries/MLXVLM/Models/FastVLM.swift @@ -983,7 +983,8 @@ public struct FastVLMProcessor: UserInputProcessor { } public func prepare(input: MLXLMCommon.UserInput) async throws -> MLXLMCommon.LMInput { - let messages = FastVLMMessageGenerator().generate(from: input) + let messages = FastVLMMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) if input.images.isEmpty { // No image scenario @@ -1183,11 +1184,7 @@ public struct FastVLMMessageGenerator: MessageGenerator { public func generate(message: Chat.Message) -> MLXLMCommon.Message { var dictionary: MLXLMCommon.Message = [ "role": message.role.rawValue, - "content": [] - + message.images.map { _ in - ["type": "image"] - } - + [["type": "text", "text": message.content]], + "content": contentParts(for: message, layout: .imagesThenText), ] addToolMetadata(to: &dictionary, for: message) return dictionary diff --git a/Libraries/MLXVLM/Models/Gemma3.swift b/Libraries/MLXVLM/Models/Gemma3.swift index 2637b5c8a9..d2f8d1d780 100644 --- a/Libraries/MLXVLM/Models/Gemma3.swift +++ b/Libraries/MLXVLM/Models/Gemma3.swift @@ -1080,7 +1080,8 @@ public struct Gemma3Processor: UserInputProcessor { public func prepare(input: UserInput) async throws -> LMInput { // Use structured content message generator for Gemma3's chat template - let messages = Qwen2VLMessageGenerator().generate(from: input) + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index b219a2c4bd..29e32310ba 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -2686,15 +2686,7 @@ public struct Gemma4MessageGenerator: MessageGenerator { } else { dictionary = [ "role": message.role.rawValue, - "content": message.images.map { _ in - ["type": "image"] - } - + message.videos.map { _ in - ["type": "video"] - } - + [ - ["type": "text", "text": message.content] - ], + "content": contentParts(for: message, layout: .imagesThenVideosThenText), ] } addToolMetadata(to: &dictionary, for: message) @@ -2770,7 +2762,8 @@ public struct Gemma4Processor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Gemma4MessageGenerator().generate(from: input) + let messages = Gemma4MessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, @@ -3329,7 +3322,8 @@ public struct Gemma4UnifiedProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Gemma4MessageGenerator().generate(from: input) + let messages = Gemma4MessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, diff --git a/Libraries/MLXVLM/Models/GlmOcr.swift b/Libraries/MLXVLM/Models/GlmOcr.swift index 7cd8a4a20e..8adbf2ba56 100644 --- a/Libraries/MLXVLM/Models/GlmOcr.swift +++ b/Libraries/MLXVLM/Models/GlmOcr.swift @@ -836,7 +836,8 @@ public struct GlmOcrProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = GlmOcrMessageGenerator().generate(from: input) + let messages = GlmOcrMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, additionalContext: input.additionalContext) @@ -1368,12 +1369,7 @@ public struct GlmOcrMessageGenerator: MessageGenerator { public func generate(message: Chat.Message) -> MLXLMCommon.Message { var dictionary: MLXLMCommon.Message = [ "role": message.role.rawValue, - "content": [ - ["type": "text", "text": message.content] - ] - + message.images.map { _ in - ["type": "image"] - }, + "content": contentParts(for: message, layout: .textThenImages), ] addToolMetadata(to: &dictionary, for: message) return dictionary diff --git a/Libraries/MLXVLM/Models/LFM2VL.swift b/Libraries/MLXVLM/Models/LFM2VL.swift index f7804fef16..13e6be0386 100644 --- a/Libraries/MLXVLM/Models/LFM2VL.swift +++ b/Libraries/MLXVLM/Models/LFM2VL.swift @@ -745,7 +745,8 @@ public struct LFM2VLProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Qwen2VLMessageGenerator().generate(from: input) + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, @@ -882,7 +883,7 @@ public class LFM2VL: Module, VLMModel, KVCacheDimensionProvider { pixelValues: MLXArray?, spatialShapes: MLXArray?, pixelAttentionMask: MLXArray? - ) -> MLXArray { + ) throws -> MLXArray { // Ensure inputIds has batch dimension var batchedInputIds = inputIds if inputIds.ndim == 1 { @@ -940,7 +941,7 @@ public class LFM2VL: Module, VLMModel, KVCacheDimensionProvider { let concatenatedImageFeatures = concatenated(imageFeatures, axis: 0) // Merge image features with text embeddings - return mergeInputIdsWithImageFeatures( + return try mergeInputIdsWithImageFeatures( imageFeatures: concatenatedImageFeatures, inputsEmbeds: inputsEmbeds, inputIds: inputIds, @@ -953,7 +954,7 @@ public class LFM2VL: Module, VLMModel, KVCacheDimensionProvider { inputsEmbeds: MLXArray, inputIds: MLXArray, imageTokenIndex: Int - ) -> MLXArray { + ) throws -> MLXArray { // Find image token positions var imageIndices = [Int]() for (i, v) in inputIds.flattened().asArray(Int.self).enumerated() { @@ -964,7 +965,7 @@ public class LFM2VL: Module, VLMModel, KVCacheDimensionProvider { let nImageFeatures = imageFeatures.dim(0) if imageIndices.count != nImageFeatures { - fatalError( + throw VLMError.processing( "Image features and image tokens do not match: tokens: \(imageIndices.count), features \(nImageFeatures)" ) } @@ -1036,7 +1037,7 @@ public class LFM2VL: Module, VLMModel, KVCacheDimensionProvider { pixelAttentionMask = MLXArray.ones([1, numPatches]).asType(.int32) } - let inputEmbeddings = getInputEmbeddings( + let inputEmbeddings = try getInputEmbeddings( inputIds: input.text.tokens, pixelValues: pixelValues, spatialShapes: spatialShapes, diff --git a/Libraries/MLXVLM/Models/Mistral3.swift b/Libraries/MLXVLM/Models/Mistral3.swift index 8913fd449e..cc918558a6 100644 --- a/Libraries/MLXVLM/Models/Mistral3.swift +++ b/Libraries/MLXVLM/Models/Mistral3.swift @@ -614,7 +614,7 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider { inputIds: MLXArray?, pixelValues: MLXArray?, imageSizes: [(Int, Int)]? - ) -> MLXArray { + ) throws -> MLXArray { guard var pixelValues, let imageSizes else { guard let inputIds else { fatalError("Either inputIds or pixelValues must be provided") @@ -654,7 +654,7 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider { let imageFeatures = multiModalProjector(selectedFeatures, imageSizes: imageSizes) // Merge embeddings - return mergeInputIdsWithImageFeatures( + return try mergeInputIdsWithImageFeatures( imageTokenIndex: config.imageTokenIndex, imageFeatures: imageFeatures, inputsEmbeds: inputsEmbeds, @@ -667,7 +667,7 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider { imageFeatures: MLXArray, inputsEmbeds: MLXArray, inputIds: MLXArray - ) -> MLXArray { + ) throws -> MLXArray { let (_, numImagePatches, _) = ( imageFeatures.dim(0), imageFeatures.dim(1), @@ -682,7 +682,7 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider { // Validate that the number of image tokens matches the number of image patches guard imagePositions.count == numImagePatches else { - fatalError( + throw VLMError.processing( "Image token count (\(imagePositions.count)) does not match image patches (\(numImagePatches)). Ensure the processor adds exactly numImagePatches image tokens." ) } @@ -736,7 +736,7 @@ public class Mistral3VLM: Module, VLMModel, KVCacheDimensionProvider { imageSizes = nil } - let embeddings = getInputEmbeddings( + let embeddings = try getInputEmbeddings( inputIds: inputIds, pixelValues: pixelValues, imageSizes: imageSizes @@ -906,9 +906,7 @@ public struct Mistral3MessageGenerator: MessageGenerator { // For Mistral3 VLM, images come before text in the content var dictionary: Message = [ "role": message.role.rawValue, - "content": message.images.map { _ in - ["type": "image"] - } + [["type": "text", "text": message.content]], + "content": contentParts(for: message, layout: .imagesThenText), ] addToolMetadata(to: &dictionary, for: message) return dictionary @@ -1014,7 +1012,8 @@ public struct Mistral3VLMProcessor: UserInputProcessor { public func prepare(input: UserInput) async throws -> LMInput { // Generate structured messages using the message generator - let messages = Mistral3MessageGenerator().generate(from: input) + let messages = Mistral3MessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) if input.images.isEmpty { // No image - just apply chat template diff --git a/Libraries/MLXVLM/Models/MuseGlimmer.swift b/Libraries/MLXVLM/Models/MuseGlimmer.swift index 223a217bc7..26a9cf8824 100644 --- a/Libraries/MLXVLM/Models/MuseGlimmer.swift +++ b/Libraries/MLXVLM/Models/MuseGlimmer.swift @@ -1417,7 +1417,8 @@ public struct MuseGlimmerProcessor: UserInputProcessor { // model without corresponding features. guard input.videos.isEmpty else { throw VLMError.singleMediaTypeAllowed } - let messages = Qwen2VLMessageGenerator().generate(from: input) + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, additionalContext: input.additionalContext) diff --git a/Libraries/MLXVLM/Models/Qwen25VL.swift b/Libraries/MLXVLM/Models/Qwen25VL.swift index 685ef1e435..78a5fc2d2f 100644 --- a/Libraries/MLXVLM/Models/Qwen25VL.swift +++ b/Libraries/MLXVLM/Models/Qwen25VL.swift @@ -836,7 +836,8 @@ public struct Qwen25VLProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Qwen2VLMessageGenerator().generate(from: input) + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, diff --git a/Libraries/MLXVLM/Models/Qwen2VL.swift b/Libraries/MLXVLM/Models/Qwen2VL.swift index 3123c64b16..bffa329286 100644 --- a/Libraries/MLXVLM/Models/Qwen2VL.swift +++ b/Libraries/MLXVLM/Models/Qwen2VL.swift @@ -833,7 +833,8 @@ public struct Qwen2VLProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Qwen2VLMessageGenerator().generate(from: input) + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, @@ -1288,10 +1289,7 @@ public struct Qwen2VLMessageGenerator: MessageGenerator { // a deterministic ~9 px bbox offset vs the Python mlx-vlm reference. var dictionary: MLXLMCommon.Message = [ "role": message.role.rawValue, - "content": - message.images.map { _ in ["type": "image"] } - + message.videos.map { _ in ["type": "video"] } - + [["type": "text", "text": message.content]], + "content": contentParts(for: message, layout: .imagesThenVideosThenText), ] addToolMetadata(to: &dictionary, for: message) return dictionary diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index e3121303b1..b337154629 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -1405,16 +1405,26 @@ public class Qwen35: Module, VLMModel { return result } - public func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: + public func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + var checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + checkpoint, layout: .vision, + tiedWordEmbeddings: config.textConfiguration.tieWordEmbeddings) + checkpoint.weights = try sanitize( + weights: checkpoint.weights, metadata: checkpoint.metadata) + return checkpoint + } + + public func sanitize(weights: [String: MLXArray], metadata: [String: String]) throws -> [String: MLXArray] { if metadata["format"]?.lowercased() == "mlx" { - return weights + // Converted checkpoints can keep the MTP head; the drafter loads it, not this model. + return Qwen35CheckpointPolicy.targetWeights(weights) } - return sanitize(weights: weights) + return try sanitize(weights: weights) } - public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { // Whether the checkpoint stores RMSNorm weights in the raw (un-shifted) // convention that needs the `+1` offset. Mirrors the MLXLLM Qwen35 gate // so the VLM and text paths agree: a pre-converted MLX checkpoint @@ -1431,11 +1441,10 @@ public class Qwen35: Module, VLMModel { // layout is the reliable signal on its own. let shouldShiftNormWeights = hasUnsanitizedConv1d - var weights = weights.filter { !$0.key.contains("mtp.") } - - weights = filterLMHeadWeights( - from: weights, + let checkpoint = try Qwen35CheckpointPolicy.prepareTarget( + .init(weights: weights), layout: .vision, tiedWordEmbeddings: config.textConfiguration.tieWordEmbeddings) + let weights = checkpoint.weights var sanitized: [String: MLXArray] = [:] sanitized.reserveCapacity(weights.count) @@ -1449,25 +1458,8 @@ public class Qwen35: Module, VLMModel { ] for (key, originalValue) in weights { - var key = key var value = originalValue - if key.contains("model") { - if key.contains("model.language_model") { - key = key.replacingOccurrences( - of: "model.language_model", with: "language_model.model") - } else if key.contains("model.visual") { - key = key.replacingOccurrences(of: "model.visual", with: "vision_tower") - } else if key.hasPrefix("model.") { - // Unified Qwen 3.5 checkpoints (e.g. Qwen3.5-0.8B-MLX-4bit) ship - // language model tensors at bare `model.*` paths instead of - // `model.language_model.*`. Mirror the LLM-side fallback. - key = "language_model." + key - } - } else if key.contains("lm_head") { - key = key.replacingOccurrences(of: "lm_head", with: "language_model.lm_head") - } - if key.contains("conv1d.weight") && value.dim(-1) != 1 { value = value.movedAxis(source: 2, destination: 1) } diff --git a/Libraries/MLXVLM/Models/Qwen35MTP.swift b/Libraries/MLXVLM/Models/Qwen35MTP.swift index 5531c3527b..784fa0b35a 100644 --- a/Libraries/MLXVLM/Models/Qwen35MTP.swift +++ b/Libraries/MLXVLM/Models/Qwen35MTP.swift @@ -81,16 +81,27 @@ public final class Qwen35VLMNextNDraftModel: 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: Qwen35VLMNextNPredictor - public init( + public convenience init( _ configuration: Qwen35Configuration.TextConfiguration, preconvertedNorms: Bool = false + ) { + self.init( + configuration, + checkpointPolicy: .init( + layout: configuration.modelType == "qwen3_5_mtp" ? .standalone : .embedded, + preconvertedNorms: preconvertedNorms)) + } + + private init( + _ configuration: Qwen35Configuration.TextConfiguration, + checkpointPolicy: Qwen35CheckpointPolicy ) { self.configuration = configuration - self.preconvertedNorms = preconvertedNorms + self.checkpointPolicy = checkpointPolicy _mtp.wrappedValue = Qwen35VLMNextNPredictor(configuration) super.init() } @@ -101,7 +112,9 @@ public final class Qwen35VLMNextNDraftModel: Module, StatefulMTPDrafterModel { ) { self.init( configuration.textConfiguration, - preconvertedNorms: preconvertedNorms) + checkpointPolicy: .init( + layout: configuration.modelType == "qwen3_5_mtp" ? .standalone : .embedded, + preconvertedNorms: preconvertedNorms)) } public func makeState(parameters: GenerateParameters?) -> MTPDrafterState { @@ -258,14 +271,22 @@ public final class Qwen35VLMNextNDraftModel: 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 } + } func qwen35MTPPositionIds( @@ -291,3 +312,9 @@ func qwen35MTPPositionIds( } return tiled(base[.newAxis, 0..., 0...], repetitions: [3, 1, 1]) } + +extension Qwen35VLMNextNDraftModel: ModelConversionMetadataProvider { + public var modelConversionMetadata: [String: String] { + [Qwen35CheckpointPolicy.normMetadataKey: "scale"] + } +} diff --git a/Libraries/MLXVLM/Models/Qwen35MoE.swift b/Libraries/MLXVLM/Models/Qwen35MoE.swift index dd33fd0696..d5f8e65907 100644 --- a/Libraries/MLXVLM/Models/Qwen35MoE.swift +++ b/Libraries/MLXVLM/Models/Qwen35MoE.swift @@ -10,7 +10,7 @@ import MLX public final class Qwen35MoE: Qwen35 { - public override func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + public override func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { var remapped = [String: MLXArray]() remapped.reserveCapacity(weights.count) for (key, value) in weights { @@ -42,6 +42,6 @@ public final class Qwen35MoE: Qwen35 { } } - return super.sanitize(weights: remapped) + return try super.sanitize(weights: remapped) } } diff --git a/Libraries/MLXVLM/Models/Qwen3VL.swift b/Libraries/MLXVLM/Models/Qwen3VL.swift index 9a642db67f..7931c515fe 100644 --- a/Libraries/MLXVLM/Models/Qwen3VL.swift +++ b/Libraries/MLXVLM/Models/Qwen3VL.swift @@ -108,7 +108,8 @@ public struct Qwen3VLProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Qwen3VLMessageGenerator().generate(from: input) + let messages = Qwen3VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) var promptTokens = try tokenizer.applyChatTemplate( messages: messages, tools: input.tools, @@ -2032,17 +2033,9 @@ public struct Qwen3VLMessageGenerator: MessageGenerator { public init() {} public func generate(message: Chat.Message) -> MLXLMCommon.Message { - let imageContent = message.images.map { _ in - ["type": "image"] - } - let textContent = [["type": "text", "text": message.content]] - let videoContent = message.videos.map { _ in - ["type": "video"] - } - var dictionary: MLXLMCommon.Message = [ "role": message.role.rawValue, - "content": imageContent + videoContent + textContent, + "content": contentParts(for: message, layout: .imagesThenVideosThenText), ] addToolMetadata(to: &dictionary, for: message) return dictionary diff --git a/Libraries/MLXVLM/Models/SmolVLM2.swift b/Libraries/MLXVLM/Models/SmolVLM2.swift index bda45ac92d..c91f0692ad 100644 --- a/Libraries/MLXVLM/Models/SmolVLM2.swift +++ b/Libraries/MLXVLM/Models/SmolVLM2.swift @@ -227,7 +227,8 @@ public struct SmolVLMProcessor: UserInputProcessor { } public func prepare(input: UserInput) async throws -> LMInput { - let messages = Qwen2VLMessageGenerator().generate(from: input) // TODO: Create SmolVLM2MessageGenerator + let messages = Qwen2VLMessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: tokenizer)) // TODO: Create SmolVLM2MessageGenerator if input.images.isEmpty && input.videos.isEmpty { // No image scenario diff --git a/Libraries/MLXVLM/README.md b/Libraries/MLXVLM/README.md index 1dd8b961d2..0c3be00559 100644 --- a/Libraries/MLXVLM/README.md +++ b/Libraries/MLXVLM/README.md @@ -12,13 +12,16 @@ Using LLMs and VLMs from MLXLMCommon is as easy as: ```swift +import Foundation import MLXVLM import MLXLMCommon -import MLXLMHuggingFace -import MLXLMTokenizers +import MLXHuggingFace +import HuggingFace +import Tokenizers let model = try await loadModel( - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen2.5-VL-3B-Instruct-4bit" ) let session = ChatSession(model) diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 9874e24972..21ca40e032 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -478,7 +478,7 @@ public final class VLMModelFactory: GenericModelFactory { let processor: any UserInputProcessor if let messageGenerator = mutableConfiguration.messageGenerator { processor = MessageGeneratorUserInputProcessor( - processor: baseProcessor, messageGenerator: messageGenerator) + processor: baseProcessor, messageGenerator: messageGenerator, tokenizer: tokenizer) } else { processor = baseProcessor } diff --git a/Package.swift b/Package.swift index bf50534407..cc3f0572ae 100644 --- a/Package.swift +++ b/Package.swift @@ -61,7 +61,7 @@ let package = Package( .default(enabledTraits: ["FoundationModelsIntegration"]), ], dependencies: [ - .package(url: "https://github.com/ml-explore/mlx-swift", .upToNextMinor(from: "0.31.6")), + .package(url: "https://github.com/ml-explore/mlx-swift", .upToNextMinor(from: "0.32.3")), // 602.0.0 floor: swift.org publishes signed prebuilt swift-syntax artifacts only for // >= 602 tags on current toolchains; a 600.x/601.x resolution falls back to the full // source compile of swift-syntax. diff --git a/README.md b/README.md index 668349ea21..1851a0595b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ MLX Swift LM is a Swift package to build tools and applications with large langu > [!IMPORTANT] > We use `swift-format` to keep the code formatting consistent. CI has this pinned to `603.0.0` right now. +[View Current Release Planning](https://github.com/ml-explore/mlx-swift-lm/issues?q=is%3Aissue+is%3Aopen+label%3Arelease-planning) and read about [Contributing](#contributing). + Some key features include: - Model loading with integrations for a variety of tokenizer and model downloading packages. @@ -46,7 +48,7 @@ See documentation on [how to integrate mlx-swift-lm and downloaders/tokenizers]( Add the core package to your `Package.swift`: ```swift -.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMajor(from: "3.31.3")), +.package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.32.3")), ``` Then chose an [integration package for downloaders and tokenizers](https://swiftpackageindex.com/ml-explore/mlx-swift-lm/main/documentation/mlxlmcommon/using#Integration-Packages). @@ -64,7 +66,7 @@ See also [MLXLMCommon](Libraries/MLXLMCommon). The simplest way to get started i ```swift dependencies: [ - .package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMajor(from: "3.31.3")), + .package(url: "https://github.com/ml-explore/mlx-swift-lm", .upToNextMinor(from: "3.32.3")), .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"), .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"), ], @@ -143,3 +145,9 @@ if #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) { Here, we combine `MLXFoundationModels` with [`MLXGuidedGeneration`](Libraries/MLXGuidedGeneration/README.md) by requesting a `@Generable` type: the response is grammar-constrained to that type's schema. `MLXGuidedGeneration` is a standalone primitive that constrains any MLX model's output to a schema. Other capabilities include `.vision`, `.toolCalling`, and `.reasoning`. See [Libraries/MLXFoundationModels](Libraries/MLXFoundationModels/README.md) for the full capability set, custom weights and loaders, and more information about using MLXFoundationModels. + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for how to build, test, and submit changes. + +Smaller, focused PRs are easier and quicker to review. Sometimes larger PRs can't be helped. If you want to discuss, feel free to open an issue or ask questions in a PR. If responses are slow, feel free to @ `davidkoski` - there is a lot of activity and it probably just got past me. I will do my best to respond! diff --git a/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift b/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift index 160e0d4225..78a9fe394c 100644 --- a/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift +++ b/Tests/MLXFoundationModelsTests/AllowedToolOutputRouterTests.swift @@ -26,6 +26,21 @@ struct AllowedToolOutputRouterTests { return rejection.reason } + /// The text of `events`, or `nil` if any of them is not a response. + /// + /// The router flushes the text before a possible marker and only later decides whether the + /// marker was real so ordinary tag-like text can arrive as more than one response event. + /// Where a test is about text surviving intact rather than about where the stream was cut, + /// join the events and compare that + private func responseText(_ events: [AllowedToolOutputRouter.Event]) -> String? { + var text = "" + for event in events { + guard case .response(let chunk) = event else { return nil } + text += chunk + } + return text + } + @Test func plainTextRemainsAResponse() { var router = AllowedToolOutputRouter(format: .json, tools: tools) #expect(router.process("Hello") == [.response("Hello")]) @@ -271,10 +286,10 @@ struct AllowedToolOutputRouterTests { @Test func ordinaryTagLikeTextRemainsAResponse() { var jsonRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect( - jsonRouter.process("Use for layout") == [.response("Use
for layout")]) + responseText(jsonRouter.process("Use
for layout")) == "Use
for layout") var mistralRouter = AllowedToolOutputRouter(format: .mistral, tools: tools) - #expect(mistralRouter.process("[Today] is sunny") == [.response("[Today] is sunny")]) + #expect(responseText(mistralRouter.process("[Today] is sunny")) == "[Today] is sunny") } @Test func malformedProtocolSuppressesOnlyTheMarkerSpan() { @@ -366,8 +381,8 @@ struct AllowedToolOutputRouterTests { @Test func nearProtocolMarkersSuppressWithoutStrippingOrdinaryTags() { var ordinaryRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect( - ordinaryRouter.process("Use and labels") - == [.response("Use and labels")]) + responseText(ordinaryRouter.process("Use and labels")) + == "Use and labels") var partialRouter = AllowedToolOutputRouter(format: .json, tools: tools) #expect(partialRouter.process("before [Int] { + var ids: [Int] = [] + var rest = Substring(text) + while !rest.isEmpty { + if let added = allAdded.first(where: { rest.hasPrefix($0.text) }) { + ids.append(added.id) + rest = rest.dropFirst(added.text.count) + } else { + ids.append(Self.scalarBase + Int(rest.unicodeScalars.first!.value)) + rest = rest.dropFirst() + } + } + // Add a special BOS and EOS when asked, as a real tokenizer does. The tests then + // fail if the label check passes `addSpecialTokens: true`. + return addSpecialTokens ? [bosID] + ids + [eosID] : ids + } + + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.compactMap { id -> String? in + if let special = specials.first(where: { $0.id == id }) { + return skipSpecialTokens ? nil : special.text + } + if let added = nonSpecialAdded.first(where: { $0.id == id }) { + return added.text + } + if id == bosID || id == eosID { + return skipSpecialTokens ? nil : "" + } + guard let scalar = Unicode.Scalar(UInt32(id - Self.scalarBase)) else { return nil } + return String(Character(scalar)) + } + .joined() + } + + func convertTokenToId(_ token: String) -> Int? { + allAdded.first { $0.text == token }?.id + } + + func convertIdToToken(_ id: Int) -> String? { + allAdded.first { $0.id == id }?.text + } + + private var bosID: Int { 1 } + private var eosID: Int { 2 } + + var bosToken: String? { "" } + var eosToken: String? { "" } + var unknownToken: String? { nil } + + func applyChatTemplate( + messages: [[String: any Sendable]], + tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [] } +} + +private let qwenTokenizer = SpecialTokenStubTokenizer(specials: [ + ("<|vision_start|>", 151_652), + ("<|vision_end|>", 151_653), + ("<|image_pad|>", 151_655), + ("<|im_start|>", 151_644), +]) + +private let gemma4Tokenizer = SpecialTokenStubTokenizer(specials: [ + ("<|image>", 255_999), + ("<|image|>", 258_880), + ("", 258_882), +]) + +private let mistralTokenizer = SpecialTokenStubTokenizer(specials: [ + ("[IMG]", 10), + ("[IMG_BREAK]", 12), + ("[IMG_END]", 13), +]) + +/// In the GLM-OCR tokenizer, the image token `<|image|>` is not a special token. +private let glmOcrTokenizer = SpecialTokenStubTokenizer( + specials: [ + ("<|begin_of_image|>", 59_256), + ("<|end_of_image|>", 59_257), + ], + nonSpecialAdded: [("<|image|>", 59_280)]) + +@Suite("Attachment label validation") +struct AttachmentLabelValidatorTests { + + @available(iOS 27.0, macOS 27.0, visionOS 27.0, *) + private static func labeled(_ labels: String...) -> [TranscriptConverter.LabeledAttachment] { + let segments = labels.map { label in + Transcript.Segment.attachment( + Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(makeSolidCGImage())), + label: label)) + } + let prompt = Transcript.Prompt( + segments: [.text(Transcript.TextSegment(content: "Describe this"))] + segments, + responseFormat: nil) + return TranscriptConverter.labeledAttachments(in: [.prompt(prompt)]) + } + + @available(iOS 27.0, macOS 27.0, visionOS 27.0, *) + private static func validationError( + for labels: String..., with tokenizer: any MLXLMCommon.Tokenizer + ) -> LanguageModelError.UnsupportedTranscriptContent? { + let attachments = labels.map { label in + labeled(label)[0] + } + do { + try AttachmentLabelValidator.default.validate(attachments, with: tokenizer) + return nil + } catch let error as LanguageModelError { + guard case .unsupportedTranscriptContent(let content) = error else { + Issue.record("Expected unsupportedTranscriptContent, got \(error)") + return nil + } + return content + } catch { + Issue.record("Expected LanguageModelError, got \(error)") + return nil + } + } + + @Test("Ordinary labels are accepted") + func ordinaryLabelsPass() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let attachments = Self.labeled( + "Photo_A1B2C3", "receipt", "facture (2024-03-01)", "chart q3 (final)", + "a & an entity", "发票扫描件", "photo 📸 beach", "100% done", "a/b\\c") + try AttachmentLabelValidator.default.validate(attachments, with: qwenTokenizer) + try AttachmentLabelValidator.default.validate(attachments, with: gemma4Tokenizer) + try AttachmentLabelValidator.default.validate(attachments, with: glmOcrTokenizer) + try AttachmentLabelValidator.default.validate(attachments, with: mistralTokenizer) + } + + @Test("A marker character in a label is refused on every model") + func markerCharactersAreRefused() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + for label in ["chart [q3] (final)", "a tag", "<|", "|>", "]", "half<"] { + let error = Self.validationError(for: label, with: qwenTokenizer) + let description = try #require( + error?.debugDescription, "expected \(label) to be refused") + #expect(description.contains("\"\(label)\"")) + } + } + + @Test("No labels and an empty label are accepted") + func emptyInputsPass() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + try AttachmentLabelValidator.default.validate([], with: qwenTokenizer) + try AttachmentLabelValidator.default.validate(Self.labeled(""), with: qwenTokenizer) + } + + @Test("A label carrying an image placeholder is rejected, naming label and token") + func imagePlaceholderLabelIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError(for: "<|image_pad|>", with: qwenTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("<|image_pad|>")) + #expect(description.contains("special token")) + } + + @Test("A special token embedded in otherwise ordinary text is rejected") + func embeddedSpecialTokenIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError( + for: "receipt <|image_pad|> tail", with: qwenTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("\"receipt <|image_pad|> tail\"")) + #expect(description.contains("`<|image_pad|>`")) + } + + @Test("Rejection names the prompt entry the label came from") + func rejectionNamesTheOffendingEntry() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + // Build the entry once. Each `Transcript.Prompt` gets a new id, so two builds of + // the same prompt are not equal. + let attachments = Self.labeled("<|image_pad|>") + do { + try AttachmentLabelValidator.default.validate(attachments, with: qwenTokenizer) + Issue.record("Expected the label to be rejected") + } catch let error as LanguageModelError { + guard case .unsupportedTranscriptContent(let content) = error else { + Issue.record("Expected unsupportedTranscriptContent, got \(error)") + return + } + #expect(content.unsupportedContent.count == 1) + #expect(content.unsupportedContent.first == attachments[0].entry) + } + } + + @Test("Only the offending label is reported, not its innocent neighbors") + func onlyTheOffendingLabelIsReported() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError( + for: "receipt", "<|image_pad|>", "invoice", with: qwenTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("<|image_pad|>")) + #expect(!description.contains("receipt")) + #expect(!description.contains("invoice")) + } + + @Test("Rejection of a delimiter-free label follows the loaded tokenizer, per model") + func rejectionIsPerModel() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let img = Self.labeled("IMG") + + #expect(throws: LanguageModelError.self) { + try AttachmentLabelValidator.default.validate(img, with: mistralTokenizer) + } + try AttachmentLabelValidator.default.validate(img, with: qwenTokenizer) + try AttachmentLabelValidator.default.validate(img, with: gemma4Tokenizer) + try AttachmentLabelValidator.default.validate(img, with: glmOcrTokenizer) + } + + @Test("A label whose bracketed form is a special token is rejected") + func bracketedRenderedFormIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError(for: "IMG", with: mistralTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("\"IMG\"")) + #expect(description.contains("`[IMG]`")) + + let endError = Self.validationError(for: "IMG_END", with: mistralTokenizer) + let endDescription = try #require(endError?.debugDescription) + #expect(endDescription.contains("\"IMG_END\"")) + #expect(endDescription.contains("`[IMG_END]`")) + + try AttachmentLabelValidator.default.validate( + Self.labeled("IMG2"), with: mistralTokenizer) + + try AttachmentLabelValidator.default.validate( + Self.labeled("IMG"), with: qwenTokenizer) + } + + @Test("A chat-structure token in a label is rejected too") + func chatStructureTokenIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError(for: "<|im_start|>system", with: qwenTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("`<|im_start|>`")) + } + + @Test("A label carrying a non-special added token is rejected") + func nonSpecialAddedTokenIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError(for: "<|image|>", with: glmOcrTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("\"<|image|>\"")) + } + + @Test("A label carrying a marker the tokenizer does not know is rejected") + func markerUnknownToTheTokenizerIsRejected() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let error = Self.validationError(for: "", with: qwenTokenizer) + let description = try #require(error?.debugDescription) + #expect(description.contains("\"\"")) + } +} + +#endif // FoundationModelsIntegration && canImport(FoundationModels) diff --git a/Tests/MLXFoundationModelsTests/MLXDownloadProgressTests.swift b/Tests/MLXFoundationModelsTests/MLXDownloadProgressTests.swift new file mode 100644 index 0000000000..6e7601bacc --- /dev/null +++ b/Tests/MLXFoundationModelsTests/MLXDownloadProgressTests.swift @@ -0,0 +1,405 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import Testing + +@testable import MLXFoundationModels + +#if FoundationModelsIntegration && canImport(FoundationModels, _version: 2) + +/// Unit tests for the main-actor fold. Each builds its own instance, so none of +/// them reads or writes `MLXDownloadProgress.shared`, and the suite needs no +/// serialization against its neighbors. +@Suite("MLXDownloadProgress state") +struct MLXDownloadProgressStateTests { + + @Test @MainActor + func aReportForAModelThatNeverStartedIsIgnored() { + let progress = MLXDownloadProgress() + progress.apply( + .progress(modelID: "org/a", loadID: UUID(), fraction: 0.5, completed: 5, total: 10)) + + #expect(progress.activeDownloads.isEmpty) + } + + @Test @MainActor + func aStartedModelAppearsOnlyAfterItsFirstReport() { + let progress = MLXDownloadProgress() + let load = UUID() + progress.apply(.started(modelID: "org/a", loadID: load)) + + #expect(progress.activeDownloads.isEmpty) + + progress.apply( + .progress(modelID: "org/a", loadID: load, fraction: 0.5, completed: 5, total: 10)) + + #expect(progress.activeDownloads.map(\.modelID) == ["org/a"]) + #expect(progress.download(forModelID: "org/a")?.completedBytes == 5) + #expect(progress.download(forModelID: "org/a")?.totalBytes == 10) + } + + @Test @MainActor + func aModelAlreadyOnDiskNeverAppears() { + let progress = MLXDownloadProgress() + let load = UUID() + progress.apply(.started(modelID: "org/a", loadID: load)) + progress.apply( + .progress(modelID: "org/a", loadID: load, fraction: 1, completed: 10, total: 10)) + + #expect(progress.activeDownloads.isEmpty) + } + + @Test @MainActor + func twoModelsReportIndependentlyAndTheAggregatesSumThem() { + let progress = MLXDownloadProgress() + let loadA = UUID() + let loadB = UUID() + progress.apply(.started(modelID: "org/a", loadID: loadA)) + progress.apply( + .progress(modelID: "org/a", loadID: loadA, fraction: 0.5, completed: 5, total: 10)) + progress.apply(.started(modelID: "org/b", loadID: loadB)) + progress.apply( + .progress(modelID: "org/b", loadID: loadB, fraction: 0.25, completed: 30, total: 120)) + + #expect(progress.activeDownloads.map(\.modelID) == ["org/a", "org/b"]) + #expect(progress.download(forModelID: "org/a")?.fractionCompleted == 0.5) + #expect(progress.download(forModelID: "org/b")?.fractionCompleted == 0.25) + #expect(progress.completedBytes == 35) + #expect(progress.totalBytes == 130) + #expect(progress.fractionCompleted == 35.0 / 130.0) + } + + @Test @MainActor + func endingOneModelLeavesTheOtherDownloading() { + let progress = MLXDownloadProgress() + let loadA = UUID() + let loadB = UUID() + progress.apply(.started(modelID: "org/a", loadID: loadA)) + progress.apply( + .progress(modelID: "org/a", loadID: loadA, fraction: 0.5, completed: 5, total: 10)) + progress.apply(.started(modelID: "org/b", loadID: loadB)) + progress.apply( + .progress(modelID: "org/b", loadID: loadB, fraction: 0.25, completed: 30, total: 120)) + progress.apply(.ended(modelID: "org/a", loadID: loadA)) + + #expect(progress.activeDownloads.map(\.modelID) == ["org/b"]) + #expect(progress.download(forModelID: "org/a") == nil) + #expect(progress.completedBytes == 30) + } + + @Test @MainActor + func aReportThatArrivesAfterTheEndIsIgnored() { + let progress = MLXDownloadProgress() + let load = UUID() + progress.apply(.started(modelID: "org/a", loadID: load)) + progress.apply( + .progress(modelID: "org/a", loadID: load, fraction: 0.5, completed: 5, total: 10)) + progress.apply(.ended(modelID: "org/a", loadID: load)) + progress.apply( + .progress(modelID: "org/a", loadID: load, fraction: 0.75, completed: 7, total: 10)) + + #expect(progress.activeDownloads.isEmpty) + } + + @Test @MainActor + func aCancelledLoadDoesNotEndTheLoadThatReplacedIt() { + let progress = MLXDownloadProgress() + let cancelled = UUID() + let replacement = UUID() + progress.apply(.started(modelID: "org/a", loadID: cancelled)) + progress.apply( + .progress(modelID: "org/a", loadID: cancelled, fraction: 0.4, completed: 4, total: 10)) + // An eviction cancels the first load and forgets it at once, so the + // replacement starts while the first is still unwinding and reports its + // end afterwards. + progress.apply(.started(modelID: "org/a", loadID: replacement)) + progress.apply(.ended(modelID: "org/a", loadID: cancelled)) + progress.apply( + .progress( + modelID: "org/a", loadID: replacement, fraction: 0.1, completed: 1, total: 10)) + + #expect(progress.download(forModelID: "org/a")?.fractionCompleted == 0.1) + + progress.apply(.ended(modelID: "org/a", loadID: replacement)) + + #expect(progress.activeDownloads.isEmpty) + } + + @Test @MainActor + func aReportFromACancelledLoadCannotMoveTheReplacementBackward() { + let progress = MLXDownloadProgress() + let cancelled = UUID() + let replacement = UUID() + progress.apply(.started(modelID: "org/a", loadID: cancelled)) + progress.apply( + .progress(modelID: "org/a", loadID: cancelled, fraction: 0.4, completed: 4, total: 10)) + progress.apply(.started(modelID: "org/a", loadID: replacement)) + progress.apply( + .progress( + modelID: "org/a", loadID: replacement, fraction: 0.1, completed: 1, total: 10)) + let replacementStart = progress.download(forModelID: "org/a")?.startedAt + // The cancelled load's last report, arriving after its replacement began. + progress.apply( + .progress(modelID: "org/a", loadID: cancelled, fraction: 0.4, completed: 4, total: 10)) + + let download = progress.download(forModelID: "org/a") + #expect(download?.fractionCompleted == 0.1) + #expect(download?.completedBytes == 1) + #expect(download?.startedAt == replacementStart) + // The cancelled load's byte count never enters the replacement's samples, + // so no rate is computed across two loads. + #expect(download?.throughputBytesPerSecond == nil) + } + + @Test @MainActor + func aReplacementLoadPublishesNothingUntilItReports() { + let progress = MLXDownloadProgress() + let cancelled = UUID() + let replacement = UUID() + progress.apply(.started(modelID: "org/a", loadID: cancelled)) + progress.apply( + .progress(modelID: "org/a", loadID: cancelled, fraction: 0.4, completed: 4, total: 10)) + progress.apply(.started(modelID: "org/a", loadID: replacement)) + + #expect(progress.activeDownloads.isEmpty) + #expect(progress.download(forModelID: "org/a") == nil) + } + + @Test @MainActor + func nothingDownloadingReportsEmptyAggregates() { + let progress = MLXDownloadProgress() + + #expect(progress.activeDownloads.isEmpty) + #expect(progress.fractionCompleted == 0) + #expect(progress.completedBytes == 0) + #expect(progress.totalBytes == 0) + #expect(progress.startedAt == nil) + #expect(progress.throughputBytesPerSecond == nil) + } +} + +/// Waits until the shared progress state satisfies `condition`. +/// +/// A producer only hands its update to the inbox, so a test cannot read the state +/// on the line after a load returns. Each turn waits for the next change to what +/// `condition` reads, and never sleeps. A condition that never holds hangs here, +/// which the caller's time limit turns into a failure. +/// +/// Runs on the main actor and does not suspend between testing the condition and +/// installing the tracking, so a change cannot land in that gap and leave this +/// waiting for a change that already happened. +@MainActor +private func waitForSharedProgress(toSatisfy condition: @MainActor () -> Bool) async { + while !condition() { + await withCheckedContinuation { continuation in + withObservationTracking { + _ = condition() + } onChange: { + continuation.resume() + } + } + } +} + +/// Satisfies `LanguageModel`'s requirements and nothing more. A test that only +/// loads a container never generates a token, so these bodies never run. Do not +/// treat this as a model. It has no parameters, and `callAsFunction` returns a +/// fixed zero array whose dimensions mean nothing. +private final class StubLanguageModel: Module, LanguageModel, KVCacheDimensionProvider { + var kvHeads: [Int] { [] } + + func prepare( + _ input: LMInput, cache: [KVCache], state _: LMOutput.State?, prefill _: PrefillParameters + ) throws -> PrepareResult { + .tokens(input.text) + } + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + MLXArray.zeros([1, 1, 1]) + } +} + +/// Satisfies `UserInputProcessor`'s one requirement. A test that only loads a +/// container prepares no input, so this body never runs. +private struct StubInputProcessor: UserInputProcessor { + func prepare(input: UserInput) throws -> LMInput { + LMInput(tokens: MLXArray([0])) + } +} + +/// Holds a loader open, so a test observes the progress a load reported before +/// that load ends. +private actor ProgressLoadGate { + private var reportedAlready = false + private var reportedContinuation: CheckedContinuation? + private var releasedAlready = false + private var releaseContinuation: CheckedContinuation? + + func signalReported() { + reportedAlready = true + reportedContinuation?.resume() + reportedContinuation = nil + } + + func waitUntilReported() async { + if reportedAlready { return } + await withCheckedContinuation { reportedContinuation = $0 } + } + + func waitForRelease() async { + if releasedAlready { return } + await withCheckedContinuation { releaseContinuation = $0 } + } + + func release() { + releasedAlready = true + releaseContinuation?.resume() + releaseContinuation = nil + } +} + +/// Thrown when a parked loader resumes without being cancelled. Only the +/// cancellation handler releases it, so this error means the test's own gate +/// misbehaved rather than the cache. +private struct ParkedLoaderResumedWithoutCancellation: Error {} + +/// Nested under the serialized `FoundationModelsCacheTests` parent, declared in +/// ModelCacheEvictionTests.swift, because these tests drive a real +/// `MLXLanguageModel` load and read the process-global +/// `MLXDownloadProgress.shared`. +extension FoundationModelsCacheTests { + + @Suite("MLXDownloadProgress load lifecycle") + struct DownloadProgressLifecycle { + + struct LoadFailure: Error {} + + @Test( + "a failed load clears the progress state for its model", + .timeLimit(.minutes(1))) + func failedLoadClearsProgress() async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let id = "org/throwing-loader-\(UUID().uuidString)" + let gate = ProgressLoadGate() + let model = MLXLanguageModel( + configuration: ModelConfiguration(id: id), + capabilities: [], + weightsLocation: { _ in URL(fileURLWithPath: "/tmp") }, + load: { _, progressHandler in + let fakeProgress = Progress(totalUnitCount: 10) + fakeProgress.completedUnitCount = 5 + progressHandler(fakeProgress) + await gate.signalReported() + await gate.waitForRelease() + throw LoadFailure() + }) + + let loadTask = Task { try await model.loadContainer() } + await gate.waitUntilReported() + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) != nil + } + + await gate.release() + await #expect(throws: LoadFailure.self) { + try await loadTask.value + } + + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) == nil + } + } + + @Test( + "a cancelled load clears the progress state for its model", + .timeLimit(.minutes(1))) + func cancelledLoadClearsProgress() async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let id = "org/cancelled-loader-\(UUID().uuidString)" + let gate = ProgressLoadGate() + let model = MLXLanguageModel( + configuration: ModelConfiguration(id: id), + capabilities: [], + weightsLocation: { _ in URL(fileURLWithPath: "/tmp") }, + load: { _, progressHandler in + let fakeProgress = Progress(totalUnitCount: 10) + fakeProgress.completedUnitCount = 5 + progressHandler(fakeProgress) + await withTaskCancellationHandler { + await gate.waitForRelease() + } onCancel: { + // A cancellation handler cannot await, so hop onto the + // gate to release the parked loader. + Task { await gate.release() } + } + try Task.checkCancellation() + throw ParkedLoaderResumedWithoutCancellation() + }) + + let loadTask = Task { try await model.loadContainer() } + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) != nil + } + + await model.evict() + await #expect(throws: CancellationError.self) { + try await loadTask.value + } + + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) == nil + } + } + + @Test( + "a successful load clears the progress state for its model", + .timeLimit(.minutes(1))) + func successfulLoadClearsProgress() async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let id = "org/succeeding-loader-\(UUID().uuidString)" + let gate = ProgressLoadGate() + let model = MLXLanguageModel( + configuration: ModelConfiguration(id: id), + capabilities: [], + weightsLocation: { _ in URL(fileURLWithPath: "/tmp") }, + load: { configuration, progressHandler in + let fakeProgress = Progress(totalUnitCount: 10) + fakeProgress.completedUnitCount = 5 + progressHandler(fakeProgress) + await gate.signalReported() + await gate.waitForRelease() + return ModelContainer( + context: ModelContext( + configuration: configuration, + model: StubLanguageModel(), + processor: StubInputProcessor(), + tokenizer: ByteTokenizer())) + }) + + let loadTask = Task { try await model.loadContainer() } + await gate.waitUntilReported() + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) != nil + } + + await gate.release() + _ = try await loadTask.value + + await waitForSharedProgress { + MLXDownloadProgress.shared.download(forModelID: id) == nil + } + + // A successful load caches the container under `id`. Drop it so it + // does not outlive this test in the process-global cache. + await model.evict() + } + } +} + +#endif // FoundationModelsIntegration && canImport(FoundationModels, _version: 2) diff --git a/Tests/MLXFoundationModelsTests/ModelCacheEvictionTests.swift b/Tests/MLXFoundationModelsTests/ModelCacheEvictionTests.swift index 9474f1a4d2..d9e32ca665 100644 --- a/Tests/MLXFoundationModelsTests/ModelCacheEvictionTests.swift +++ b/Tests/MLXFoundationModelsTests/ModelCacheEvictionTests.swift @@ -165,6 +165,54 @@ extension FoundationModelsCacheTests { let lastError = await MLXLanguageModel.lastLoadErrorInCache(modelID: id) #expect(lastError == nil, "a superseded load must not re-populate cache state") } + + @Test( + "evict() cancels the model's registered load task", + .timeLimit(.minutes(1))) + func evictCancelsRegisteredLoad() async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let probe = CancellationProbe() + let model = MLXLanguageModel( + configuration: ModelConfiguration(id: "org/cancel-evict-\(UUID().uuidString)"), + capabilities: [], + weightsLocation: { _ in URL(fileURLWithPath: "/no/such/path") }, + load: makeCancellationProbingLoader(probe: probe)) + + let loadTask = Task { try await model.preload() } + await probe.waitUntilParked() + + await model.evict() + + await #expect(throws: CancellationError.self) { + try await loadTask.value + } + #expect(await probe.wasCancelled) + } + + @Test( + "evictAll() cancels every registered load task", + .timeLimit(.minutes(1))) + func evictAllCancelsRegisteredLoads() async throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let probe = CancellationProbe() + let model = MLXLanguageModel( + configuration: ModelConfiguration(id: "org/cancel-evictall-\(UUID().uuidString)"), + capabilities: [], + weightsLocation: { _ in URL(fileURLWithPath: "/no/such/path") }, + load: makeCancellationProbingLoader(probe: probe)) + + let loadTask = Task { try await model.preload() } + await probe.waitUntilParked() + + await MLXLanguageModel.evictAll() + + await #expect(throws: CancellationError.self) { + try await loadTask.value + } + #expect(await probe.wasCancelled) + } } } @@ -173,6 +221,62 @@ extension FoundationModelsCacheTests { // Hoisted to file scope so the eviction tests above share one definition. Kept // file-`private` so they don't collide with AvailabilityTests.swift's own stubs. +/// Builds a container loader that parks until the cache cancels its load task. +/// The loader never produces a container: the test awaits its failure, so the +/// probe reads back without any timing assumption. +@available(iOS 27.0, macOS 27.0, visionOS 27.0, *) +private func makeCancellationProbingLoader( + probe: CancellationProbe +) -> MLXLanguageModel.ContainerLoader { + { _, _ in + await withTaskCancellationHandler { + await probe.parkUntilCancelled() + } onCancel: { + // A cancellation handler cannot await, so hop onto the probe actor to + // record the cancellation and resume the parked continuation. + Task { await probe.recordCancellation() } + } + try Task.checkCancellation() + throw ParkedLoaderResumedWithoutCancellation() + } +} + +/// Records the cancellation of a registered load task, and parks the loader until +/// that cancellation arrives. +private actor CancellationProbe { + private(set) var wasCancelled = false + private var isParked = false + private var parkContinuation: CheckedContinuation? + private var parkedWaiter: CheckedContinuation? + + /// Suspends the loader until ``recordCancellation()`` runs. + func parkUntilCancelled() async { + if wasCancelled { return } + isParked = true + parkedWaiter?.resume() + parkedWaiter = nil + await withCheckedContinuation { parkContinuation = $0 } + } + + /// Suspends until the loader parks, so a test evicts only after the cache has + /// registered the load task. + func waitUntilParked() async { + if isParked { return } + await withCheckedContinuation { parkedWaiter = $0 } + } + + func recordCancellation() { + wasCancelled = true + parkContinuation?.resume() + parkContinuation = nil + } +} + +/// Thrown if the parked loader resumes without a cancellation. Only +/// `CancellationProbe.recordCancellation()` resumes it, so this error means the +/// probe misbehaved rather than the cache. +private struct ParkedLoaderResumedWithoutCancellation: Error {} + /// Coordinates the in-flight window: the downloader signals when a load has entered /// (so the load task is registered), then parks until the test releases it. private actor LoadGate { diff --git a/Tests/MLXFoundationModelsTests/ToolCallingConversionsTests.swift b/Tests/MLXFoundationModelsTests/ToolCallingConversionsTests.swift new file mode 100644 index 0000000000..3bc6f7c41d --- /dev/null +++ b/Tests/MLXFoundationModelsTests/ToolCallingConversionsTests.swift @@ -0,0 +1,85 @@ +// Copyright © 2026 Apple Inc. + +#if FoundationModelsIntegration && canImport(FoundationModels, _version: 2) + +import Testing +import Foundation +import FoundationModels +@testable import MLXFoundationModels + +@available(iOS 27.0, macOS 27.0, visionOS 27.0, *) +@Generable +private struct Seat { + @Guide(description: "Seat row.") + var row: Int +} + +@available(iOS 27.0, macOS 27.0, visionOS 27.0, *) +@Generable +private struct ReserveSeatsArguments { + @Guide(description: "Flight number.") + var flight: String + // Keep the count at 1. A boxed `1` also passes `as? Bool`, so a conversion + // that casts with `as? Bool` turns `minItems` and `maxItems` into `true`. + @Guide(description: "Seats to reserve.", .count(1)) + var seats: [Seat] +} + +@Suite +struct ToolCallingConversionsTests { + + @Test + func schemaBooleansAreSwiftBools() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let parameters = try parametersSchema(of: makeReserveSeatsToolSpec()) + + let rootValue = try #require(parameters["additionalProperties"]) + #expect(isSwiftBool(rootValue)) + #expect(rootValue as? Bool == false) + + let definitions = try #require(parameters["$defs"] as? [String: Any]) + let seat = try #require(definitions["Seat"] as? [String: Any]) + let nestedValue = try #require(seat["additionalProperties"]) + #expect(isSwiftBool(nestedValue)) + #expect(nestedValue as? Bool == false) + } + + @Test + func schemaNumbersStayNumbers() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + let parameters = try parametersSchema(of: makeReserveSeatsToolSpec()) + + let properties = try #require(parameters["properties"] as? [String: Any]) + let seats = try #require(properties["seats"] as? [String: Any]) + for key in ["minItems", "maxItems"] { + let bound = try #require(seats[key]) + #expect(!isSwiftBool(bound), "\(key) must stay a number") + #expect(bound as? Int == 1) + } + } + + // MARK: - Helpers + + @available(iOS 27.0, macOS 27.0, visionOS 27.0, *) + private func makeReserveSeatsToolSpec() throws -> [String: any Sendable] { + try ToolCallingConversions.makeToolSpec( + from: Transcript.ToolDefinition( + name: "reserve_seats", + description: "Reserve seats on a flight", + parameters: ReserveSeatsArguments.generationSchema + ) + ) + } + + private func parametersSchema(of toolSpec: [String: any Sendable]) throws -> [String: Any] { + let function = try #require(toolSpec["function"] as? [String: Any]) + return try #require(function["parameters"] as? [String: Any]) + } + + private func isSwiftBool(_ value: Any) -> Bool { + // Keep the `type(of:)` check. A boxed boolean and a boxed `0` or `1` also pass `as? Bool`. + type(of: value) == Bool.self + } +} + +#endif // FoundationModelsIntegration && canImport(FoundationModels) diff --git a/Tests/MLXFoundationModelsTests/TranscriptConverterTests.swift b/Tests/MLXFoundationModelsTests/TranscriptConverterTests.swift index 35a394320f..fa599f9bea 100644 --- a/Tests/MLXFoundationModelsTests/TranscriptConverterTests.swift +++ b/Tests/MLXFoundationModelsTests/TranscriptConverterTests.swift @@ -3,6 +3,7 @@ import CoreGraphics import Foundation import FoundationModels +import ImageIO import MLXLMCommon import Testing @@ -32,7 +33,7 @@ struct TranscriptConverterTests { ) let entries: [Transcript.Entry] = [.instructions(instructions)] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) let message = messages.first! @@ -52,7 +53,7 @@ struct TranscriptConverterTests { ) let entries: [Transcript.Entry] = [.prompt(prompt)] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) let message = messages.first! @@ -72,7 +73,7 @@ struct TranscriptConverterTests { ) let entries: [Transcript.Entry] = [.response(response)] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) let message = messages.first! @@ -93,7 +94,7 @@ struct TranscriptConverterTests { ) let entries: [Transcript.Entry] = [.prompt(prompt)] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) let message = messages.first! @@ -128,7 +129,7 @@ struct TranscriptConverterTests { )), ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 4) #expect(messages[0].role == .system) @@ -142,7 +143,7 @@ struct TranscriptConverterTests { guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } let entries: [Transcript.Entry] = [] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.isEmpty) } @@ -162,7 +163,7 @@ struct TranscriptConverterTests { )) ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) } @@ -178,7 +179,7 @@ struct TranscriptConverterTests { .toolCalls(Transcript.ToolCalls(id: "tc_1", [toolCall])) ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) #expect(messages[0].role == .assistant) @@ -205,7 +206,7 @@ struct TranscriptConverterTests { segments: [.text(Transcript.TextSegment(content: "18C and sunny"))]) let entries: [Transcript.Entry] = [.toolOutput(output)] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) #expect(messages[0].role == .tool) @@ -244,7 +245,7 @@ struct TranscriptConverterTests { content: testCase.content)) ]) - let messages = TranscriptConverter.mlxMessages(for: [.toolOutput(output)]) + let messages = try TranscriptConverter.mlxMessages(for: [.toolOutput(output)]) #expect(messages.count == 1) let message = try #require(messages.first) @@ -274,7 +275,7 @@ struct TranscriptConverterTests { .text(Transcript.TextSegment(content: "Use this current reading.")), ]) - let messages = TranscriptConverter.mlxMessages(for: [.toolOutput(output)]) + let messages = try TranscriptConverter.mlxMessages(for: [.toolOutput(output)]) let message = try #require(messages.first) #expect( @@ -310,7 +311,7 @@ struct TranscriptConverterTests { .toolOutput(output), ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.map(\.role) == [.user, .assistant, .tool]) @@ -353,7 +354,7 @@ struct TranscriptConverterTests { .toolOutput(outputB), ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) // Both rounds replay in order: each assistant tool-call message is // immediately followed by its correlated tool result, so a third-round @@ -397,7 +398,7 @@ struct TranscriptConverterTests { )), ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 2) #expect(messages[0].role == .user) @@ -426,7 +427,7 @@ struct TranscriptConverterTests { )), ] - let messages = TranscriptConverter.mlxMessages(for: entries) + let messages = try TranscriptConverter.mlxMessages(for: entries) #expect(messages.count == 1) #expect(messages[0].role == .user) @@ -448,12 +449,13 @@ struct TranscriptConverterTests { responseFormat: nil ) - let messages = TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) #expect(messages.count == 1) #expect(messages[0].role == .user) #expect(messages[0].content == "Describe this") #expect(messages[0].images.count == 1) + #expect(messages[0].images.first?.label == "photo") } @Test @@ -468,16 +470,17 @@ struct TranscriptConverterTests { responseFormat: nil ) - let messages = TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) #expect(messages.count == 1) #expect(messages[0].role == .user) #expect(messages[0].content == "") #expect(messages[0].images.count == 1) + #expect(messages[0].images.first?.label == "photo") } @Test - func testInstructionsImageAttachmentBecomesSystemMessageImage() throws { + func testInstructionsImageAttachmentIsDropped() throws { guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } let attachment = Transcript.AttachmentSegment( @@ -491,12 +494,27 @@ struct TranscriptConverterTests { toolDefinitions: [] ) - let messages = TranscriptConverter.mlxMessages(for: [.instructions(instructions)]) + let messages = try TranscriptConverter.mlxMessages(for: [.instructions(instructions)]) #expect(messages.count == 1) #expect(messages[0].role == .system) #expect(messages[0].content == "Use this reference:") - #expect(messages[0].images.count == 1) + #expect(messages[0].images.isEmpty) + } + + @Test + func testInstructionsWithOnlyAnImageProducesNoMessage() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let attachment = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(makeSolidCGImage())), + label: "reference") + let instructions = Transcript.Instructions( + segments: [.attachment(attachment)], toolDefinitions: []) + + let messages = try TranscriptConverter.mlxMessages(for: [.instructions(instructions)]) + + #expect(messages.isEmpty) } @Test @@ -514,7 +532,7 @@ struct TranscriptConverterTests { responseFormat: nil ) - let messages = TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) #expect(messages.count == 1) #expect(messages[0].images.count == 1) @@ -525,7 +543,7 @@ struct TranscriptConverterTests { Issue.record("Expected one image input") return } - guard case .ciImage = image else { + guard case .ciImage = image.source else { Issue.record("URL-backed attachment should yield .ciImage, not .url") return } @@ -551,13 +569,13 @@ struct TranscriptConverterTests { responseFormat: nil ) - let messages = TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) #expect(messages.count == 1) #expect(messages[0].images.count == 2) // Segment order is preserved: the 2x2 image precedes the 4x4 image. let widths = messages[0].images.compactMap { image -> CGFloat? in - guard case .ciImage(let ciImage) = image else { return nil } + guard case .ciImage(let ciImage) = image.source else { return nil } return ciImage.extent.width } #expect(widths == [2, 4]) @@ -580,11 +598,133 @@ struct TranscriptConverterTests { responseFormat: nil ) - let messages = TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) #expect(messages.count == 1) - #expect(messages[0].content == "line one\nline two") + #expect( + messages[0].content == """ + line one + line two + """) #expect(messages[0].images.count == 1) + #expect(messages[0].images.first?.label == "photo") + } + + @Test + func testLabelsRideOnTheImagesTheyName() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let first = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(makeSolidCGImage())), + label: "Photo_A1B2C3") + let second = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(makeSolidCGImage())), + label: "Photo_D4E5F6") + let prompt = Transcript.Prompt( + segments: [ + .text(Transcript.TextSegment(content: "Compare these two images:")), + .attachment(first), + .attachment(second), + ], + responseFormat: nil + ) + + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + + #expect(messages.count == 1) + #expect(messages[0].content == "Compare these two images:") + #expect(messages[0].images.map(\.label) == ["Photo_A1B2C3", "Photo_D4E5F6"]) + } + + @Test + func testUnlabeledAttachmentLeavesTheImageUnnamed() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let attachment = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(makeSolidCGImage())), + label: nil) + let prompt = Transcript.Prompt( + segments: [ + .text(Transcript.TextSegment(content: "Describe this")), + .attachment(attachment), + ], + responseFormat: nil + ) + + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + + #expect(messages[0].content == "Describe this") + #expect(messages[0].images.count == 1) + #expect(messages[0].images.first?.label == nil) + } + + @Test + func testOrientationIsAppliedToTheImageHandedToTheModel() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let wide = makeSolidCGImage(width: 8, height: 2) + let attachment = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(wide, orientation: .right)), + label: "rotated") + let prompt = Transcript.Prompt( + segments: [.attachment(attachment)], responseFormat: nil) + + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + + guard case .ciImage(let image) = messages[0].images.first?.source else { + Issue.record("Expected one CIImage input") + return + } + #expect(image.extent.width == 2) + #expect(image.extent.height == 8) + } + + @Test + func testNaturalOrientationLeavesTheImageUnchanged() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + let wide = makeSolidCGImage(width: 8, height: 2) + let attachment = Transcript.AttachmentSegment( + content: .image(Transcript.ImageAttachment(wide, orientation: nil)), + label: "natural") + let prompt = Transcript.Prompt( + segments: [.attachment(attachment)], responseFormat: nil) + + let messages = try TranscriptConverter.mlxMessages(for: [.prompt(prompt)]) + + guard case .ciImage(let image) = messages[0].images.first?.source else { + Issue.record("Expected one CIImage input") + return + } + #expect(image.extent.width == 8) + #expect(image.extent.height == 2) + } + + @Test + func testAttachmentLabelsAreCollectedInFirstSeenOrderWithoutDuplicates() throws { + guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } + + func promptEntry(_ labels: [String?]) -> Transcript.Entry { + .prompt( + Transcript.Prompt( + segments: labels.map { label in + .attachment( + Transcript.AttachmentSegment( + content: .image( + Transcript.ImageAttachment(makeSolidCGImage())), + label: label)) + }, + responseFormat: nil)) + } + + let entries = [ + promptEntry(["Photo_A1B2C3", nil]), + promptEntry(["Photo_D4E5F6", "Photo_A1B2C3"]), + ] + + #expect( + TranscriptConverter.labeledAttachments(in: entries).map(\.label) + == ["Photo_A1B2C3", "Photo_D4E5F6"]) } } diff --git a/Tests/MLXFoundationModelsTests/VisionCapabilityGateTests.swift b/Tests/MLXFoundationModelsTests/VisionCapabilityGateTests.swift index e1f2833662..faa0f0af8b 100644 --- a/Tests/MLXFoundationModelsTests/VisionCapabilityGateTests.swift +++ b/Tests/MLXFoundationModelsTests/VisionCapabilityGateTests.swift @@ -57,12 +57,14 @@ struct VisionCapabilityGateTests { } } - @Test("Image in instructions without .vision throws unsupportedCapability(.vision)") - func instructionsImageWithoutVisionThrows() async throws { + /// The stub model has no weights, so a failed weight load shows that the gate let + /// the request through. + @Test("Instructions-only image does not trip the vision gate") + func instructionsOnlyImageDoesNotTripTheGate() async throws { guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } let model = makeStubModel( - "vision/not-declared", + "vision/instructions-only-image", capabilities: []) let executor = try makeMLXExecutor(for: model) @@ -77,29 +79,28 @@ struct VisionCapabilityGateTests { toolDefinitions: [] ) let prompt = Transcript.Prompt( - segments: [.text(Transcript.TextSegment(content: "What is this?"))], + segments: [.text(Transcript.TextSegment(content: "Hello"))], responseFormat: nil ) let request = makeExecutorRequest( - transcript: Transcript(entries: [ - .instructions(instructions), .prompt(prompt), - ])) + transcript: Transcript(entries: [.instructions(instructions), .prompt(prompt)])) let channel = LanguageModelExecutorGenerationChannel() do { try await executor.respond( to: request, model: model, streamingInto: channel) - Issue.record("Expected unsupportedCapability(.vision), but respond returned") - return + Issue.record("Expected the weight load to fail, but respond returned") } catch let error as LanguageModelError { - guard case .unsupportedCapability(let unsupported) = error else { - Issue.record("Expected unsupportedCapability, got \(error)") + Issue.record( + "Expected the missing weights to fail the request, got a rejection instead: \(error)" + ) + } catch let error as ModelFactoryError { + guard case .configurationFileError(let file, let modelName, _) = error else { + Issue.record("Expected the missing config.json to fail the load, got \(error)") return } - #expect(unsupported.capability == .vision) - } catch { - Issue.record( - "Expected LanguageModelError.unsupportedCapability(.vision), got: \(error)") + #expect(file == "config.json") + #expect(modelName == "vision/instructions-only-image") } } } diff --git a/Tests/MLXLMTests/CacheConfigurationTests.swift b/Tests/MLXLMTests/CacheConfigurationTests.swift index dcbd880155..2705e33d59 100644 --- a/Tests/MLXLMTests/CacheConfigurationTests.swift +++ b/Tests/MLXLMTests/CacheConfigurationTests.swift @@ -123,6 +123,29 @@ private func legacyStatus(cache: [KVCache], maxKVSize: Int) throws -> KVCacheSta #expect(status.layers[4].path == [3, 1]) } +@Test func cacheStatusReportsAllocatedMemory() { + func attention() -> KVCacheSimple { + let cache = KVCacheSimple() + let tokens = MLXArray.zeros([1, 2, 3, 8]) + _ = cache.update(keys: tokens, values: tokens) + return cache + } + let recurrent = MambaCache() + recurrent[0] = MLXArray.zeros([1, 3, 16]) + recurrent[1] = MLXArray.zeros([1, 2, 4, 8]) + + let status = KVCacheStatus( + cache: [attention(), KVCacheSimple(), CacheList(recurrent, attention())]) + + // Three tokens reserve a whole step of rows for keys and for values. + let attentionBytes = 2 * (2 * KVCacheSimple().step * 8) * 4 + let recurrentBytes = (3 * 16 + 2 * 4 * 8) * 4 + #expect( + status.layers.map(\.memoryBytes) + == [attentionBytes, 0, recurrentBytes, attentionBytes]) + #expect(status.memoryBytes == 2 * attentionBytes + recurrentBytes) +} + // MARK: - Default LanguageModel path @Test func defaultLanguageModelHonorsMaxKVSize() throws { diff --git a/Tests/MLXLMTests/CancellationTests.swift b/Tests/MLXLMTests/CancellationTests.swift index 8d37250424..d711b6cecc 100644 --- a/Tests/MLXLMTests/CancellationTests.swift +++ b/Tests/MLXLMTests/CancellationTests.swift @@ -23,7 +23,7 @@ final class CancellationTests: XCTestCase { } // Stream-consumer break cancels the task via onTermination. The generation task - // must still settle (run Stream().synchronize()) before task.value returns. + // must still settle (run Stream.defaultStream.synchronize()) before task.value returns. func testGenerateTaskSettlesAfterStreamCancellation() async throws { let model = makeTinyModel() let tokenizer = TestTokenizer() @@ -44,7 +44,7 @@ final class CancellationTests: XCTestCase { // continuation.onTermination → task.cancel(). for await _ in stream { break } - // Must complete without hanging. Failure here means Stream().synchronize() + // Must complete without hanging. Failure here means Stream.defaultStream.synchronize() // was not reached or the task body was not allowed to run to completion. await task.value } diff --git a/Tests/MLXLMTests/CheckpointComponentTests.swift b/Tests/MLXLMTests/CheckpointComponentTests.swift new file mode 100644 index 0000000000..0f5af749d5 --- /dev/null +++ b/Tests/MLXLMTests/CheckpointComponentTests.swift @@ -0,0 +1,114 @@ +// Copyright © 2026 Apple Inc. + +import MLX +import Testing + +@testable import MLXLMCommon + +struct CheckpointComponentTests { + private let component = CheckpointComponent( + name: "predictor", namespaces: ["head", "wrapper.head"], destination: "predictor", + excludedNamespaces: ["backbone", "wrapper"]) + + @Test(arguments: ["head", "wrapper.head"]) + func selectionKeepsComponentProvenanceAndPrecision(namespace: String) throws { + let checkpoint = ModelCheckpoint( + weights: [ + "\(namespace).fc.weight": MLXArray(1), "backbone.fc.weight": MLXArray(2), + "wrapper.backbone.weight": MLXArray(3), "unknown.weight": MLXArray(4), + ], + metadata: ["format": "mlx"], + weightMetadata: ["\(namespace).fc.weight": ["component_format": "native"]], + perLayerQuantization: .init( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: [ + "\(namespace).fc": .quantize(.init(groupSize: 32, bits: 8)), + "backbone.fc": .skip, + ])) + let selected = try component.select(from: checkpoint) + #expect(selected.source == .embedded(namespace: namespace)) + #expect(Set(selected.checkpoint.weights.keys) == ["predictor.fc.weight", "unknown.weight"]) + #expect( + selected.checkpoint.metadata(forWeight: "predictor.fc.weight")["component_format"] + == "native") + #expect( + selected.checkpoint.perLayerQuantization?.quantization(layer: "predictor.fc")?.bits == 8 + ) + #expect( + selected.checkpoint.perLayerQuantization?.quantization(layer: "predictor.other")?.bits + == 4) + #expect( + selected.checkpoint.perLayerQuantization?.perLayerQuantization["backbone.fc"] == nil) + } + + @Test + func standaloneRequiresAnExplicitDeclaration() throws { + let checkpoint = ModelCheckpoint(weights: ["fc.weight": MLXArray(1)]) + #expect(throws: CheckpointComponent.SelectionError.self) { + try component.select(from: checkpoint) + } + let selected = try component.select(from: checkpoint, standalone: true) + #expect(selected.source == .standalone) + #expect(selected.checkpoint.weights["predictor.fc.weight"] != nil) + #expect(throws: CheckpointComponent.SelectionError.self) { + try component.select(from: .init(weights: [:]), standalone: true) + } + } + + @Test + func competingNamespacesAndDestinationAliasesAreRejected() { + #expect(throws: CheckpointComponent.SelectionError.self) { + try component.select( + from: .init(weights: [ + "head.fc.weight": MLXArray(1), "wrapper.head.fc.weight": MLXArray(2), + ])) + } + #expect(throws: ModelCheckpoint.MappingError.self) { + try component.select( + from: .init(weights: [ + "head.fc.weight": MLXArray(1), "predictor.fc.weight": MLXArray(2), + ])) + } + } + + @Test + func excludingAComponentPreservesSimilarlyNamedModules() throws { + let checkpoint = ModelCheckpoint( + weights: [ + "head.fc.weight": MLXArray(1), "headless.weight": MLXArray(2), + "backbone.head.weight": MLXArray(3), "wrapper.head.fc.weight": MLXArray(4), + ], + perLayerQuantization: .init(perLayerQuantization: ["head": .skip, "headless": .skip])) + let selected = try component.excluding(from: checkpoint) + #expect(Set(selected.weights.keys) == ["headless.weight", "backbone.head.weight"]) + #expect(selected.perLayerQuantization?.perLayerQuantization["head"] == nil) + guard case .skip? = selected.perLayerQuantization?.perLayerQuantization["headless"] else { + Issue.record("The unrelated module's precision declaration was removed") + return + } + } + + @Test + func orderedMappingsUseModuleBoundariesForTensorsAndSettings() throws { + let checkpoint = ModelCheckpoint( + weights: [ + "outer.text.fc.weight": MLXArray(1), "outer.text.lm_head.scales": MLXArray(2), + "outer.text.lm_head_extra.weight": MLXArray(3), "outer.texture.weight": MLXArray(4), + ], + perLayerQuantization: .init(perLayerQuantization: [ + "outer.text.fc": .quantize(.init(groupSize: 32, bits: 8)), + "outer.text.lm_head": .skip, + ])) + let mapped = try checkpoint.mapNames( + using: .init([ + .replacePrefix("outer", with: ""), .replacePrefix("text", with: "language_model"), + .excludeModule("lm_head"), + ])) + #expect( + Set(mapped.weights.keys) == [ + "language_model.fc.weight", "language_model.lm_head_extra.weight", "texture.weight", + ]) + #expect(mapped.perLayerQuantization?.quantization(layer: "language_model.fc")?.bits == 8) + #expect(mapped.perLayerQuantization?.perLayerQuantization["language_model.lm_head"] == nil) + } +} diff --git a/Tests/MLXLMTests/ContinuationAssertions.swift b/Tests/MLXLMTests/ContinuationAssertions.swift index f012412fd8..8351c7f75a 100644 --- a/Tests/MLXLMTests/ContinuationAssertions.swift +++ b/Tests/MLXLMTests/ContinuationAssertions.swift @@ -114,7 +114,7 @@ struct ContinuationAssertions { let (logitsW, _) = try prefill(model, t2, cache: cacheW, state: s1) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsW, logitsF), max(noiseFloor * 10, 1e-3), + maxAbsDiff(logitsW, logitsF), max(noiseFloor * 10, MatmulPrecision.splitTolerance), "warm continuation diverged from full prefill (noise floor \(noiseFloor))", file: file, line: line) } @@ -139,7 +139,7 @@ struct ContinuationAssertions { let (logitsW, _) = try prefill(model, t2, cache: cacheW, state: s1) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsW, logitsF), 1e-3, + maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance, "state-threaded warm continuation diverged from full prefill", file: file, line: line) } @@ -196,11 +196,11 @@ struct ContinuationAssertions { let diff = maxAbsDiff(logitsW, logitsF) if expectsIsolation { XCTAssertLessThanOrEqual( - diff, 1e-3, + diff, MatmulPrecision.splitTolerance, "split-suffix prefill diverged from full prefill", file: file, line: line) } else { XCTAssertGreaterThan( - diff, 1e-3, + diff, MatmulPrecision.splitTolerance, "cross-image vision attention should have changed the logits", file: file, line: line) } @@ -230,7 +230,7 @@ struct ContinuationAssertions { let (logitsW, _) = try prefill(model, t3, cache: cacheW, state: s2) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsW, logitsF), 1e-3, + maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance, "post-image resume state positioned the following turn wrong", file: file, line: line) } @@ -250,7 +250,7 @@ struct ContinuationAssertions { let (logitsC, _) = try prefill(model, prompt, cache: cacheC, stepSize: 8) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsC, logitsS), 1e-3, + maxAbsDiff(logitsC, logitsS), MatmulPrecision.splitTolerance, "windowed prefill diverged from single-shot", file: file, line: line) } } @@ -280,7 +280,7 @@ struct ContinuationAssertions { model, prompt, image: image, cache: cacheC, stepSize: stepSize) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsC, logitsS), 1e-3, + maxAbsDiff(logitsC, logitsS), MatmulPrecision.splitTolerance, "windowed image prefill diverged from single-shot at stepSize \(stepSize)", file: file, line: line) } diff --git a/Tests/MLXLMTests/Gemma3nCheckpointTests.swift b/Tests/MLXLMTests/Gemma3nCheckpointTests.swift new file mode 100644 index 0000000000..dfb5c1c227 --- /dev/null +++ b/Tests/MLXLMTests/Gemma3nCheckpointTests.swift @@ -0,0 +1,84 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN +import Testing + +@testable import MLXLLM +@testable import MLXLMCommon + +struct Gemma3nCheckpointTests { + @Test + func wrapperRenamePreservesMixedPrecisionDuringStrictLoading() throws { + let config = try configuration() + let source = Gemma3nTextModel(config: config) + quantize(model: source) { path, _ in + if path.hasSuffix("self_attn.q_proj") { return (32, 8, .affine) } + if path.hasSuffix("self_attn.k_proj") { return (32, 4, .affine) } + return nil + } + let weights = Dictionary( + uniqueKeysWithValues: source.parameters().flattened().map { + ("model." + $0.0, $0.1) + }) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try save(arrays: weights, url: directory.appendingPathComponent("model.safetensors")) + let loaded = Gemma3nTextModel(config: config) + let settings = BaseConfiguration.PerLayerQuantization( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: Dictionary( + uniqueKeysWithValues: (0 ..< 2).map { + ( + "model.language_model.layers.\($0).self_attn.q_proj", + .quantize(.init(groupSize: 32, bits: 8)) + ) + })) + try loadWeights(modelDirectory: directory, model: loaded, perLayerQuantization: settings) + for layer in loaded.languageModel.layers { + #expect((layer.selfAttn.qProj as? QuantizedLinear)?.bits == 8) + #expect((layer.selfAttn.kProj as? QuantizedLinear)?.bits == 4) + } + let expected = Dictionary(uniqueKeysWithValues: source.parameters().flattened()) + for (name, value) in loaded.parameters().flattened() { + #expect(arrayEqual(value, try #require(expected[name])).item(Bool.self)) + } + } + + @Test + func wrapperAliasesFailBeforeUpdatingTheModel() throws { + let model = Gemma3nTextModel(config: try configuration()) + let weights = [ + "model.language_model.norm.weight": MLXArray(1), + "language_model.norm.weight": MLXArray(2), + ] + #expect(throws: ModelCheckpoint.MappingError.self) { + try model.prepareCheckpoint(.init(weights: weights)) + } + let baseModel: any BaseLanguageModel = model + #expect(throws: ModelCheckpoint.MappingError.self) { + try baseModel.sanitize(weights: weights) + } + #expect(throws: ModelCheckpoint.MappingError.self) { + try baseModel.sanitize(weights: weights, metadata: [:]) + } + } + + private func configuration() throws -> Gemma3nTextConfiguration { + let data = try JSONEncoder().encode(Gemma3nTextConfiguration()) + var values = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + values.merge([ + "hidden_size": 64, "num_hidden_layers": 2, "intermediate_size": [64, 64], + "num_attention_heads": 2, "head_dim": 32, "vocab_size": 16, + "num_key_value_heads": 2, "vocab_size_per_layer_input": 16, + "hidden_size_per_layer_input": 32, "altup_num_inputs": 2, "laurel_rank": 8, + "layer_types": ["sliding_attention", "full_attention"], + "activation_sparsity_pattern": [0, 0], + ]) { _, new in new } + return try JSONDecoder().decode( + Gemma3nTextConfiguration.self, from: JSONSerialization.data(withJSONObject: values)) + } +} diff --git a/Tests/MLXLMTests/GlmOcrContinuationTests.swift b/Tests/MLXLMTests/GlmOcrContinuationTests.swift index 6ca1c11956..c4fc922ac8 100644 --- a/Tests/MLXLMTests/GlmOcrContinuationTests.swift +++ b/Tests/MLXLMTests/GlmOcrContinuationTests.swift @@ -227,7 +227,8 @@ final class GlmOcrContinuationTests: XCTestCase { let decodeW = model(LMInput.Text(tokens: next), cache: cacheW, state: s2) XCTAssertLessThanOrEqual( - maxAbsDiff(decodeW.logits[0..., -1, 0...], decodeF.logits[0..., -1, 0...]), 1e-3, + maxAbsDiff(decodeW.logits[0..., -1, 0...], decodeF.logits[0..., -1, 0...]), + MatmulPrecision.splitTolerance, "decode after a warm continuation ignored the carried anchor") } } diff --git a/Tests/MLXLMTests/KVCacheTests.swift b/Tests/MLXLMTests/KVCacheTests.swift index 5d4c303787..5c27a09a69 100644 --- a/Tests/MLXLMTests/KVCacheTests.swift +++ b/Tests/MLXLMTests/KVCacheTests.swift @@ -149,2345 +149,2393 @@ private final class ProtocolDefaultTrimmabilityCache: KVCache { func innerState() -> [MLXArray] { [] } } -// MARK: - Predictive trimmability +@Suite(.serialized) struct KVCacheTests { + // MARK: - Predictive trimmability -@Test func testRotatingKVCachePredictsStrictTrimBoundary() { - let cache = RotatingKVCache(maxSize: 8) - cache.offset = 3 + @Test func testRotatingKVCachePredictsStrictTrimBoundary() { + let cache = RotatingKVCache(maxSize: 8) + cache.offset = 3 - #expect(cache.isTrimmable(after: 4)) - #expect(!cache.isTrimmable(after: 5)) -} + #expect(cache.isTrimmable(after: 4)) + #expect(!cache.isTrimmable(after: 5)) + } -@Test func testRotatingKVCacheIsNotTrimmableAtOrPastWindow() { - // `isTrimmable` is the *exact rewind* predicate. Past the window a trim is - // merely consistent (the window loses its oldest rows), so this must stay - // false to keep the staged-round and prompt-cache-reuse machinery exact. - let cache = RotatingKVCache(maxSize: 8) + @Test func testRotatingKVCacheIsNotTrimmableAtOrPastWindow() { + // `isTrimmable` is the *exact rewind* predicate. Past the window a trim is + // merely consistent (the window loses its oldest rows), so this must stay + // false to keep the staged-round and prompt-cache-reuse machinery exact. + let cache = RotatingKVCache(maxSize: 8) - cache.offset = 8 - #expect(!cache.isTrimmable) - #expect(!cache.isTrimmable(after: 0)) + cache.offset = 8 + #expect(!cache.isTrimmable) + #expect(!cache.isTrimmable(after: 0)) - cache.offset = 9 - #expect(!cache.isTrimmable) - #expect(!cache.isTrimmable(after: 0)) -} + cache.offset = 9 + #expect(!cache.isTrimmable) + #expect(!cache.isTrimmable(after: 0)) + } -@Test func testRotatingPredictiveTrimOverrideDispatchesThroughKVCache() { - let rotating = RotatingKVCache(maxSize: 8) - rotating.offset = 3 - let cache: any KVCache = rotating + @Test func testRotatingPredictiveTrimOverrideDispatchesThroughKVCache() { + let rotating = RotatingKVCache(maxSize: 8) + rotating.offset = 3 + let cache: any KVCache = rotating - #expect(cache.isTrimmable(after: 4)) - #expect(!cache.isTrimmable(after: 5)) -} + #expect(cache.isTrimmable(after: 4)) + #expect(!cache.isTrimmable(after: 5)) + } -@Test func testUnboundedCacheRemainsTrimmableAfterPositiveLookAhead() { - let cache: any KVCache = KVCacheSimple() + @Test func testUnboundedCacheRemainsTrimmableAfterPositiveLookAhead() { + let cache: any KVCache = KVCacheSimple() - #expect(cache.isTrimmable(after: 1_000)) -} + #expect(cache.isTrimmable(after: 1_000)) + } -@Test func testCacheListDelegatesPredictiveTrimmabilityToChildren() { - let rotating = RotatingKVCache(maxSize: 8) - rotating.offset = 3 - let cache: any KVCache = CacheList(KVCacheSimple(), rotating) + @Test func testCacheListDelegatesPredictiveTrimmabilityToChildren() { + let rotating = RotatingKVCache(maxSize: 8) + rotating.offset = 3 + let cache: any KVCache = CacheList(KVCacheSimple(), rotating) - #expect(cache.isTrimmable(after: 4)) - #expect(!cache.isTrimmable(after: 5)) -} + #expect(cache.isTrimmable(after: 4)) + #expect(!cache.isTrimmable(after: 5)) + } -@Test func testDirectKVCacheConformerUsesPredictiveTrimDefault() { - let cache: any KVCache = ProtocolDefaultTrimmabilityCache() + @Test func testDirectKVCacheConformerUsesPredictiveTrimDefault() { + let cache: any KVCache = ProtocolDefaultTrimmabilityCache() - #expect(cache.isTrimmable(after: 1_000)) -} + #expect(cache.isTrimmable(after: 1_000)) + } -// MARK: - Original parameterized test (updated with value assertions) - -@Test( - .serialized, - arguments: cacheCreators) -func testCacheSerialization(creator: (() -> any KVCache)) async throws { - let cache = (0 ..< 10).map { _ in creator() } - let keys = MLXArray.ones([1, 8, 32, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 32, 64], dtype: .bfloat16) - for item in cache { - switch item { - case let arrays as ArraysCache: - arrays[0] = keys - arrays[1] = values - case let quantized as QuantizedKVCache: - _ = quantized.updateQuantized(keys: keys, values: values) - default: - _ = item.update(keys: keys, values: values) + // MARK: - Original parameterized test (updated with value assertions) + + @Test( + .serialized, + arguments: cacheCreators) + func testCacheSerialization(creator: (() -> any KVCache)) async throws { + let cache = (0 ..< 10).map { _ in creator() } + let keys = MLXArray.ones([1, 8, 32, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 32, 64], dtype: .bfloat16) + for item in cache { + switch item { + case let arrays as ArraysCache: + arrays[0] = keys + arrays[1] = values + case let quantized as QuantizedKVCache: + _ = quantized.updateQuantized(keys: keys, values: values) + default: + _ = item.update(keys: keys, values: values) + } } - } - let url = tempURL() + let url = tempURL() - try savePromptCache(url: url, cache: cache, metadata: [:]) - let (loadedCache, _) = try loadPromptCache(url: url) + try savePromptCache(url: url, cache: cache, metadata: [:]) + let (loadedCache, _) = try loadPromptCache(url: url) - #expect(cache.count == loadedCache.count) - for (lhs, rhs) in zip(cache, loadedCache) { - #expect(type(of: lhs) == type(of: rhs)) - #expect(lhs.metaState == rhs.metaState) - assertArraysClose(lhs.state, rhs.state) + #expect(cache.count == loadedCache.count) + for (lhs, rhs) in zip(cache, loadedCache) { + #expect(type(of: lhs) == type(of: rhs)) + #expect(lhs.metaState == rhs.metaState) + assertArraysClose(lhs.state, rhs.state) + } } -} -@Test func testPromptCacheStateRoundTrip() throws { - let cache = KVCacheSimple() - let keys = MLXArray.ones([1, 2, 4, 8], dtype: .bfloat16) - let values = MLXArray.zeros([1, 2, 4, 8], dtype: .bfloat16) - _ = cache.update(keys: keys, values: values) + @Test func testPromptCacheStateRoundTrip() throws { + let cache = KVCacheSimple() + let keys = MLXArray.ones([1, 2, 4, 8], dtype: .bfloat16) + let values = MLXArray.zeros([1, 2, 4, 8], dtype: .bfloat16) + _ = cache.update(keys: keys, values: values) - let ropeDeltasKey = LMOutput.Key("test.ropeDeltas") - let positionsKey = LMOutput.Key("test.positionIds") - let ropeDeltas = MLXArray([Int32(3), 5, 7]).reshaped([1, 3]) - let positions = MLXArray([Int32(11), 13, 17, 19]).reshaped([2, 2]) - var state = LMOutput.State() - state[ropeDeltasKey] = ropeDeltas - state[positionsKey] = positions + let ropeDeltasKey = LMOutput.Key("test.ropeDeltas") + let positionsKey = LMOutput.Key("test.positionIds") + let ropeDeltas = MLXArray([Int32(3), 5, 7]).reshaped([1, 3]) + let positions = MLXArray([Int32(11), 13, 17, 19]).reshaped([2, 2]) + var state = LMOutput.State() + state[ropeDeltasKey] = ropeDeltas + state[positionsKey] = positions - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache( - url: url, cache: [cache], metadata: ["source": "test"], state: state) - - let snapshot = try loadPromptCacheSnapshot(url: url) - let restoredRopeDeltas = try #require(snapshot.state?[ropeDeltasKey]) - let restoredPositions = try #require(snapshot.state?[positionsKey]) - - #expect(snapshot.metadata == ["source": "test"]) - #expect(restoredRopeDeltas.dtype == ropeDeltas.dtype) - #expect(restoredRopeDeltas.shape == ropeDeltas.shape) - #expect(allClose(restoredRopeDeltas, ropeDeltas, rtol: 0, atol: 0).item(Bool.self)) - #expect(restoredPositions.dtype == positions.dtype) - #expect(restoredPositions.shape == positions.shape) - #expect(allClose(restoredPositions, positions, rtol: 0, atol: 0).item(Bool.self)) - - let (storedArrays, storedMetadata) = try loadArraysAndMetadata(url: url) - #expect(storedArrays["__mlx_lm_state_tensor_0"] != nil) - #expect(storedArrays["__mlx_lm_state_tensor_1"] != nil) - #expect( - storedArrays.keys.allSatisfy { - Int($0.split(separator: ".")[0]) != nil - || $0.hasPrefix("__mlx_lm_state_tensor_") - }) - #expect(storedMetadata["1.__mlx_lm_state_0_key"] == "test.positionIds") - #expect(storedMetadata["1.__mlx_lm_state_1_key"] == "test.ropeDeltas") - #expect(storedMetadata["2.0"] == "__mlx_lm_state_v1__:KVCache") - #expect(throws: KVCacheError.self) { - try loadPromptCache(url: url) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache( + url: url, cache: [cache], metadata: ["source": "test"], state: state) + + let snapshot = try loadPromptCacheSnapshot(url: url) + let restoredRopeDeltas = try #require(snapshot.state?[ropeDeltasKey]) + let restoredPositions = try #require(snapshot.state?[positionsKey]) + + #expect(snapshot.metadata == ["source": "test"]) + #expect(restoredRopeDeltas.dtype == ropeDeltas.dtype) + #expect(restoredRopeDeltas.shape == ropeDeltas.shape) + #expect(allClose(restoredRopeDeltas, ropeDeltas, rtol: 0, atol: 0).item(Bool.self)) + #expect(restoredPositions.dtype == positions.dtype) + #expect(restoredPositions.shape == positions.shape) + #expect(allClose(restoredPositions, positions, rtol: 0, atol: 0).item(Bool.self)) + + let (storedArrays, storedMetadata) = try loadArraysAndMetadata(url: url) + #expect(storedArrays["__mlx_lm_state_tensor_0"] != nil) + #expect(storedArrays["__mlx_lm_state_tensor_1"] != nil) + #expect( + storedArrays.keys.allSatisfy { + Int($0.split(separator: ".")[0]) != nil + || $0.hasPrefix("__mlx_lm_state_tensor_") + }) + #expect(storedMetadata["1.__mlx_lm_state_0_key"] == "test.positionIds") + #expect(storedMetadata["1.__mlx_lm_state_1_key"] == "test.ropeDeltas") + #expect(storedMetadata["2.0"] == "__mlx_lm_state_v1__:KVCache") + #expect(throws: KVCacheError.self) { + try loadPromptCache(url: url) + } } -} - -@Test func testLegacyPromptCacheLoadsWithNilState() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - - try savePromptCache(url: url, cache: [cache]) - let snapshot = try loadPromptCacheSnapshot(url: url) - let (legacyCache, legacyMetadata) = try loadPromptCache(url: url) - let (arrays, metadata) = try loadArraysAndMetadata(url: url) - - #expect(snapshot.cache.count == 1) - #expect(snapshot.state == nil) - #expect(legacyCache.count == 1) - #expect(legacyMetadata.isEmpty) - #expect(arrays.keys.allSatisfy { Int($0.split(separator: ".")[0]) != nil }) - #expect(!metadata.keys.contains { $0.contains("__mlx_lm_state_") }) - #expect(metadata["2.0"] == "KVCache") -} - -@Test func testEmptyPromptCacheStateUsesTheLegacyFormat() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let legacyURL = tempURL() - let emptyStateURL = tempURL() - defer { - try? FileManager.default.removeItem(at: legacyURL) - try? FileManager.default.removeItem(at: emptyStateURL) - } - - try savePromptCache(url: legacyURL, cache: [cache]) - try savePromptCache(url: emptyStateURL, cache: [cache], state: LMOutput.State()) - let snapshot = try loadPromptCacheSnapshot(url: emptyStateURL) - let (legacyCache, _) = try loadPromptCache(url: emptyStateURL) - let (legacyArrays, legacyMetadata) = try loadArraysAndMetadata(url: legacyURL) - let (emptyStateArrays, emptyStateMetadata) = try loadArraysAndMetadata(url: emptyStateURL) - - #expect(snapshot.state == nil) - #expect(legacyCache.count == 1) - #expect(Set(emptyStateArrays.keys) == Set(legacyArrays.keys)) - #expect(emptyStateMetadata == legacyMetadata) -} -@Test func testPromptCacheStateRejectsReservedUserMetadata() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } + @Test func testLegacyPromptCacheLoadsWithNilState() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(throws: KVCacheError.self) { - try savePromptCache( - url: url, cache: [cache], - metadata: ["__mlx_lm_state_version": "caller-owned"]) + try savePromptCache(url: url, cache: [cache]) + let snapshot = try loadPromptCacheSnapshot(url: url) + let (legacyCache, legacyMetadata) = try loadPromptCache(url: url) + let (arrays, metadata) = try loadArraysAndMetadata(url: url) + + #expect(snapshot.cache.count == 1) + #expect(snapshot.state == nil) + #expect(legacyCache.count == 1) + #expect(legacyMetadata.isEmpty) + #expect(arrays.keys.allSatisfy { Int($0.split(separator: ".")[0]) != nil }) + #expect(!metadata.keys.contains { $0.contains("__mlx_lm_state_") }) + #expect(metadata["2.0"] == "KVCache") } -} -@Test func testPromptCacheStateRejectsUnsupportedValues() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let unsupportedKey = LMOutput.Key("test.unsupported") - var state = LMOutput.State() - state[unsupportedKey] = true - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } + @Test func testEmptyPromptCacheStateUsesTheLegacyFormat() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let legacyURL = tempURL() + let emptyStateURL = tempURL() + defer { + try? FileManager.default.removeItem(at: legacyURL) + try? FileManager.default.removeItem(at: emptyStateURL) + } - #expect(throws: LMOutput.State.SerializationError.self) { - try savePromptCache(url: url, cache: [cache], state: state) + try savePromptCache(url: legacyURL, cache: [cache]) + try savePromptCache(url: emptyStateURL, cache: [cache], state: LMOutput.State()) + let snapshot = try loadPromptCacheSnapshot(url: emptyStateURL) + let (legacyCache, _) = try loadPromptCache(url: emptyStateURL) + let (legacyArrays, legacyMetadata) = try loadArraysAndMetadata(url: legacyURL) + let (emptyStateArrays, emptyStateMetadata) = try loadArraysAndMetadata(url: emptyStateURL) + + #expect(snapshot.state == nil) + #expect(legacyCache.count == 1) + #expect(Set(emptyStateArrays.keys) == Set(legacyArrays.keys)) + #expect(emptyStateMetadata == legacyMetadata) } - #expect(!FileManager.default.fileExists(atPath: url.path)) -} - -@Test func testPromptCacheStateRejectsMalformedEntries() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let key = LMOutput.Key("test.state") - var state = LMOutput.State() - state[key] = MLXArray([Int32(1)]) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [cache], state: state) - let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) - var malformedMetadata = savedMetadata - malformedMetadata["1.__mlx_lm_state_count"] = "2" - try save(arrays: arrays, metadata: malformedMetadata, url: url) + @Test func testPromptCacheStateRejectsReservedUserMetadata() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) + #expect(throws: KVCacheError.self) { + try savePromptCache( + url: url, cache: [cache], + metadata: ["__mlx_lm_state_version": "caller-owned"]) + } } -} -@Test func testPromptCacheStateRejectsUnknownVersions() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let key = LMOutput.Key("test.state") - var state = LMOutput.State() - state[key] = MLXArray([Int32(1)]) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - - try savePromptCache(url: url, cache: [cache], state: state) - let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) - var malformedMetadata = savedMetadata - malformedMetadata["1.__mlx_lm_state_version"] = "999" - try save(arrays: arrays, metadata: malformedMetadata, url: url) + @Test func testPromptCacheStateRejectsUnsupportedValues() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let unsupportedKey = LMOutput.Key("test.unsupported") + var state = LMOutput.State() + state[unsupportedKey] = true + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) + #expect(throws: LMOutput.State.SerializationError.self) { + try savePromptCache(url: url, cache: [cache], state: state) + } + #expect(!FileManager.default.fileExists(atPath: url.path)) } -} - -@Test func testPromptCacheStateRejectsDuplicateKeys() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let firstKey = LMOutput.Key("test.first") - let secondKey = LMOutput.Key("test.second") - var state = LMOutput.State() - state[firstKey] = MLXArray([Int32(1)]) - state[secondKey] = MLXArray([Int32(2)]) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [cache], state: state) - let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) - var malformedMetadata = savedMetadata - malformedMetadata["1.__mlx_lm_state_1_key"] = "test.first" - try save(arrays: arrays, metadata: malformedMetadata, url: url) + @Test func testPromptCacheStateRejectsMalformedEntries() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let key = LMOutput.Key("test.state") + var state = LMOutput.State() + state[key] = MLXArray([Int32(1)]) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) - } -} + try savePromptCache(url: url, cache: [cache], state: state) + let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) -@Test func testPromptCacheStateRejectsUnexpectedTensors() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let key = LMOutput.Key("test.state") - var state = LMOutput.State() - state[key] = MLXArray([Int32(1)]) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } + // eval before overwriting file -- otherwise the lazy read picks + // up the corruption + eval(arrays) - try savePromptCache(url: url, cache: [cache], state: state) - let (storedArrays, metadata) = try loadArraysAndMetadata(url: url) - var malformedArrays = storedArrays - malformedArrays["__mlx_lm_state_tensor_99"] = MLXArray([Int32(99)]) - try save(arrays: malformedArrays, metadata: metadata, url: url) + var malformedMetadata = savedMetadata + malformedMetadata["1.__mlx_lm_state_count"] = "2" + try save(arrays: arrays, metadata: malformedMetadata, url: url) - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } } -} -@Test func testPromptCacheStateRequiresCompatibilityMarker() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let key = LMOutput.Key("test.state") - var state = LMOutput.State() - state[key] = MLXArray([Int32(1)]) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } + @Test func testPromptCacheStateRejectsUnknownVersions() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let key = LMOutput.Key("test.state") + var state = LMOutput.State() + state[key] = MLXArray([Int32(1)]) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [cache], state: state) - let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) - var malformedMetadata = storedMetadata - malformedMetadata["2.0"] = "KVCache" - try save(arrays: arrays, metadata: malformedMetadata, url: url) + try savePromptCache(url: url, cache: [cache], state: state) + let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays) + var malformedMetadata = savedMetadata + malformedMetadata["1.__mlx_lm_state_version"] = "999" + try save(arrays: arrays, metadata: malformedMetadata, url: url) - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } } -} -@Test func testPromptCacheCompatibilityMarkerRequiresState() throws { - let cache = KVCacheSimple() - _ = cache.update( - keys: MLXArray.ones([1, 1, 1, 4]), - values: MLXArray.zeros([1, 1, 1, 4])) - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } + @Test func testPromptCacheStateRejectsDuplicateKeys() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let firstKey = LMOutput.Key("test.first") + let secondKey = LMOutput.Key("test.second") + var state = LMOutput.State() + state[firstKey] = MLXArray([Int32(1)]) + state[secondKey] = MLXArray([Int32(2)]) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [cache]) - let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) - var malformedMetadata = storedMetadata - malformedMetadata["2.0"] = "__mlx_lm_state_v1__:KVCache" - try save(arrays: arrays, metadata: malformedMetadata, url: url) + try savePromptCache(url: url, cache: [cache], state: state) + let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays) + var malformedMetadata = savedMetadata + malformedMetadata["1.__mlx_lm_state_1_key"] = "test.first" + try save(arrays: arrays, metadata: malformedMetadata, url: url) - #expect(throws: KVCacheError.self) { - try loadPromptCacheSnapshot(url: url) + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } } -} -@Test func testQuantizedKVCacheRestoresNonDefaultQuantizationMetadata() throws { - let cache = QuantizedKVCache(groupSize: 64, bits: 4) - let keys = MLXArray.ones([1, 1, 4, 32], dtype: .bfloat16) - let values = MLXArray.ones([1, 1, 4, 32], dtype: .bfloat16) - _ = cache.updateQuantized(keys: keys, values: values) + @Test func testPromptCacheStateRejectsUnexpectedTensors() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let key = LMOutput.Key("test.state") + var state = LMOutput.State() + state[key] = MLXArray([Int32(1)]) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(cache.groupSize == 32) - #expect(cache.bits == 4) + try savePromptCache(url: url, cache: [cache], state: state) + let (storedArrays, metadata) = try loadArraysAndMetadata(url: url) + eval(storedArrays) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + var malformedArrays = storedArrays + malformedArrays["__mlx_lm_state_tensor_99"] = MLXArray([Int32(99)]) + try save(arrays: malformedArrays, metadata: metadata, url: url) - let restored = try #require(loaded[0] as? QuantizedKVCache) - #expect(restored.groupSize == 32) - #expect(restored.bits == 4) - #expect(restored.metaState == cache.metaState) + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } + } - let moreKeys = MLXArray.zeros([1, 1, 1, 32], dtype: .bfloat16) - let moreValues = MLXArray.zeros([1, 1, 1, 32], dtype: .bfloat16) - _ = restored.updateQuantized(keys: moreKeys, values: moreValues) + @Test func testPromptCacheStateRequiresCompatibilityMarker() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let key = LMOutput.Key("test.state") + var state = LMOutput.State() + state[key] = MLXArray([Int32(1)]) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(restored.groupSize == 32) - #expect(restored.bits == 4) -} + try savePromptCache(url: url, cache: [cache], state: state) + let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays) + var malformedMetadata = storedMetadata + malformedMetadata["2.0"] = "KVCache" + try save(arrays: arrays, metadata: malformedMetadata, url: url) -@Test func testQuantizedKVCacheMetaStateRestoresQuantizationMetadataWithoutState() { - let cache = QuantizedKVCache() + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } + } - cache.metaState = ["256", "11", "32", "4"] + @Test func testPromptCacheCompatibilityMarkerRequiresState() throws { + let cache = KVCacheSimple() + _ = cache.update( + keys: MLXArray.ones([1, 1, 1, 4]), + values: MLXArray.zeros([1, 1, 1, 4])) + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - #expect(cache.offset == 11) - #expect(cache.groupSize == 32) - #expect(cache.bits == 4) - #expect(cache.metaState == ["256", "11", "32", "4"]) -} + try savePromptCache(url: url, cache: [cache]) + let (arrays, storedMetadata) = try loadArraysAndMetadata(url: url) + eval(arrays) -@Test func testQuantizedKVCacheCopyPreservesRestoredQuantizationMetadata() throws { - let cache = QuantizedKVCache() - cache.metaState = ["256", "5", "32", "4"] + var malformedMetadata = storedMetadata + malformedMetadata["2.0"] = "__mlx_lm_state_v1__:KVCache" + try save(arrays: arrays, metadata: malformedMetadata, url: url) - let copied = try #require(cache.copy() as? QuantizedKVCache) + #expect(throws: KVCacheError.self) { + try loadPromptCacheSnapshot(url: url) + } + } - #expect(copied.offset == 5) - #expect(copied.groupSize == 32) - #expect(copied.bits == 4) - #expect(copied.metaState == cache.metaState) -} + @Test func testQuantizedKVCacheRestoresNonDefaultQuantizationMetadata() throws { + let cache = QuantizedKVCache(groupSize: 64, bits: 4) + let keys = MLXArray.ones([1, 1, 4, 32], dtype: .bfloat16) + let values = MLXArray.ones([1, 1, 4, 32], dtype: .bfloat16) + _ = cache.updateQuantized(keys: keys, values: values) -@Test func testEmptyKVCacheSimpleToQuantizedPreservesRequestedQuantizationMetadata() throws { - let cache = KVCacheSimple() - cache.offset = 7 + #expect(cache.groupSize == 32) + #expect(cache.bits == 4) - let quantized = try cache.toQuantized(groupSize: 128, bits: 4) + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) - #expect(quantized.offset == 7) - #expect(quantized.groupSize == 128) - #expect(quantized.bits == 4) - #expect(quantized.metaState == ["256", "7", "128", "4"]) -} + let restored = try #require(loaded[0] as? QuantizedKVCache) + #expect(restored.groupSize == 32) + #expect(restored.bits == 4) + #expect(restored.metaState == cache.metaState) -@Test func testDirectKVCacheQuantizationFailuresAreRecoverable() throws { - let incompatible = KVCacheSimple() - incompatible.state = [ - MLXArray.zeros([1, 2, 4, 5], dtype: .float32, stream: .cpu), - MLXArray.zeros([1, 2, 4, 5], dtype: .float32, stream: .cpu), - ] + let moreKeys = MLXArray.zeros([1, 1, 1, 32], dtype: .bfloat16) + let moreValues = MLXArray.zeros([1, 1, 1, 32], dtype: .bfloat16) + _ = restored.updateQuantized(keys: moreKeys, values: moreValues) - #expect(throws: KVCacheError.self) { - _ = try incompatible.toQuantized(groupSize: 64, bits: 4) + #expect(restored.groupSize == 32) + #expect(restored.bits == 4) } - #expect(throws: KVCacheError.self) { - _ = try RotatingKVCache(maxSize: 32).toQuantized() - } -} -@Test func testPromptCacheRestorationRejectsIncompleteState() throws { - try expectPromptCacheLoadToFail([ - .init(className: "KVCacheSimple", arrayCount: 1, metadata: [""]), - .init( - className: "RotatingKVCache", arrayCount: 1, - metadata: ["0", "32", "256", "0", "0", "modelNative"]), - .init( - className: "QuantizedKVCache", arrayCount: 3, - metadata: ["256", "0", "64", "4"]), - .init( - className: "VarianceNormalizedKVCache", arrayCount: 7, - metadata: ["32", "32", "4", "4", "2", "1", "0"]), - .init(className: "ChunkedKVCache", arrayCount: 1, metadata: ["None", "0"]), - ]) -} + @Test func testQuantizedKVCacheMetaStateRestoresQuantizationMetadataWithoutState() { + let cache = QuantizedKVCache() -@Test func testPromptCacheRestorationRejectsInvalidMetadata() throws { - try expectPromptCacheLoadToFail([ - .init(className: "KVCacheSimple", arrayCount: 0, metadata: ["unexpected"]), - .init( - className: "RotatingKVCache", arrayCount: 0, - metadata: ["0", "32", "invalid", "0", "0", "modelNative"]), - .init( - className: "RotatingKVCache", arrayCount: 0, - metadata: ["0", "32", "256", "0", "0", "invalid-origin"]), - .init( - className: "QuantizedKVCache", arrayCount: 0, - metadata: ["256", "invalid", "64", "4"]), - .init( - className: "VarianceNormalizedKVCache", arrayCount: 0, - metadata: ["24", "0", "4", "4", "2", "0", "0"]), - .init( - className: "VarianceNormalizedKVCache", arrayCount: 8, - metadata: ["32", "31", "4", "4", "2", "1", "0"]), - .init(className: "ChunkedKVCache", arrayCount: 0, metadata: ["invalid", "0"]), - ]) -} + cache.metaState = ["256", "11", "32", "4"] -@Test func testPromptCacheRestorationRejectsInvalidStateRank() throws { - try expectPromptCacheLoadToFail([ - .init( - className: "KVCacheSimple", arrayCount: 2, metadata: [""], - arrayShape: [1, 1]), - .init( - className: "VarianceNormalizedKVCache", arrayCount: 8, - metadata: ["32", "32", "4", "4", "2", "1", "0"], - arrayShape: [1, 1]), - ]) -} + #expect(cache.offset == 11) + #expect(cache.groupSize == 32) + #expect(cache.bits == 4) + #expect(cache.metaState == ["256", "11", "32", "4"]) + } -@Test func testPromptCacheRestorationAcceptsLegacyRotatingMetadata() throws { - let fixture = SerializedCacheFixture( - className: "RotatingKVCache", - arrayCount: 2, - metadata: ["0", "32", "256", "1", "1"]) - let url = try writePromptCacheFixture(fixture) - defer { try? FileManager.default.removeItem(at: url) } - - let (restored, _) = try loadPromptCache(url: url) - let rotating = try #require(restored.first as? RotatingKVCache) - - #expect(rotating.capacityOrigin == .modelNative) - // Legacy metadata has no wrapped flag; the restored cache derives it (an - // unwrapped layout here) and re-serializes with the flag appended. - #expect(rotating.metaState == ["0", "32", "256", "1", "1", "modelNative", "false"]) -} + @Test func testQuantizedKVCacheCopyPreservesRestoredQuantizationMetadata() throws { + let cache = QuantizedKVCache() + cache.metaState = ["256", "5", "32", "4"] -@Test func testPromptCacheRoundTripPreservesEmptyCaches() throws { - let populated = KVCacheSimple() - populated.state = [ - MLXArray.ones([1, 1, 1, 32], stream: .cpu), - MLXArray.ones([1, 1, 1, 32], stream: .cpu), - ] - let caches: [KVCache] = [ - KVCacheSimple(), - populated, - RotatingKVCache(maxSize: 32), - QuantizedKVCache(), - ChunkedKVCache(chunkSize: 16), - ] - let url = tempURL() - defer { try? FileManager.default.removeItem(at: url) } - - try savePromptCache(url: url, cache: caches) - let (restored, _) = try loadPromptCache(url: url) - - #expect(restored.count == caches.count) - #expect(restored[0] is KVCacheSimple) - #expect(restored[0].state.isEmpty) - #expect(restored[1].state.count == 2) - #expect(restored[2] is RotatingKVCache) - #expect(restored[2].state.isEmpty) - #expect(restored[3] is QuantizedKVCache) - #expect(restored[3].state.isEmpty) - #expect(restored[4] is ChunkedKVCache) - #expect(restored[4].state.isEmpty) -} + let copied = try #require(cache.copy() as? QuantizedKVCache) -// MARK: - ArraysCache sparse slot round-trip + #expect(copied.offset == 5) + #expect(copied.groupSize == 32) + #expect(copied.bits == 4) + #expect(copied.metaState == cache.metaState) + } -@Test func testArraysCacheSparseSlots() throws { - let cache = ArraysCache(size: 3) - let a = MLXArray.ones([2, 4], dtype: .float32) * 3.0 - let b = MLXArray.ones([2, 4], dtype: .float32) * 7.0 - cache[0] = a - // slot 1 stays nil - cache[2] = b + @Test func testEmptyKVCacheSimpleToQuantizedPreservesRequestedQuantizationMetadata() throws { + let cache = KVCacheSimple() + cache.offset = 7 - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) - - #expect(loaded.count == 1) - let restored = try #require(loaded[0] as? ArraysCache) - #expect(restored.slotCount == 3) - #expect(restored[0] != nil) - #expect(restored[1] == nil) - #expect(restored[2] != nil) - #expect(allClose(restored[0]!, a).item(Bool.self)) - #expect(allClose(restored[2]!, b).item(Bool.self)) -} + let quantized = try cache.toQuantized(groupSize: 128, bits: 4) -// MARK: - ArraysCache leftPadding round-trip + #expect(quantized.offset == 7) + #expect(quantized.groupSize == 128) + #expect(quantized.bits == 4) + #expect(quantized.metaState == ["256", "7", "128", "4"]) + } -@Test func testArraysCacheLeftPadding() throws { - let cache = ArraysCache(size: 2, leftPadding: [0, 5]) - let a = MLXArray.ones([2, 4], dtype: .float32) - let b = MLXArray.ones([2, 4], dtype: .float32) * 2.0 - cache[0] = a - cache[1] = b + @Test func testDirectKVCacheQuantizationFailuresAreRecoverable() throws { + let incompatible = KVCacheSimple() + incompatible.state = [ + MLXArray.zeros([1, 2, 4, 5], dtype: .float32, stream: .cpu), + MLXArray.zeros([1, 2, 4, 5], dtype: .float32, stream: .cpu), + ] - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + #expect(throws: KVCacheError.self) { + _ = try incompatible.toQuantized(groupSize: 64, bits: 4) + } + #expect(throws: KVCacheError.self) { + _ = try RotatingKVCache(maxSize: 32).toQuantized() + } + } - let restored = try #require(loaded[0] as? ArraysCache) - #expect(restored.leftPaddingValues == [0, 5]) - assertArraysClose(restored.state, cache.state) -} + @Test func testPromptCacheRestorationRejectsIncompleteState() throws { + try expectPromptCacheLoadToFail([ + .init(className: "KVCacheSimple", arrayCount: 1, metadata: [""]), + .init( + className: "RotatingKVCache", arrayCount: 1, + metadata: ["0", "32", "256", "0", "0", "modelNative"]), + .init( + className: "QuantizedKVCache", arrayCount: 3, + metadata: ["256", "0", "64", "4"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 7, + metadata: ["32", "32", "4", "4", "2", "1", "0"]), + .init(className: "ChunkedKVCache", arrayCount: 1, metadata: ["None", "0"]), + ]) + } -@Test func testArraysCacheMaskUsesLeftPaddingAfterStateUpdate() throws { - let cache = ArraysCache(size: 2, leftPadding: [1, 3]) - cache[0] = MLXArray.ones([2, 4], dtype: .float32) + @Test func testPromptCacheRestorationRejectsInvalidMetadata() throws { + try expectPromptCacheLoadToFail([ + .init(className: "KVCacheSimple", arrayCount: 0, metadata: ["unexpected"]), + .init( + className: "RotatingKVCache", arrayCount: 0, + metadata: ["0", "32", "invalid", "0", "0", "modelNative"]), + .init( + className: "RotatingKVCache", arrayCount: 0, + metadata: ["0", "32", "256", "0", "0", "invalid-origin"]), + .init( + className: "QuantizedKVCache", arrayCount: 0, + metadata: ["256", "invalid", "64", "4"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 0, + metadata: ["24", "0", "4", "4", "2", "0", "0"]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 8, + metadata: ["32", "31", "4", "4", "2", "1", "0"]), + .init(className: "ChunkedKVCache", arrayCount: 0, metadata: ["invalid", "0"]), + ]) + } - let mask = try #require(cache.makeMask(N: 4)) - #expect( - mask.asArray(Bool.self) == [ - false, true, true, true, - false, false, false, true, + @Test func testPromptCacheRestorationRejectsInvalidStateRank() throws { + try expectPromptCacheLoadToFail([ + .init( + className: "KVCacheSimple", arrayCount: 2, metadata: [""], + arrayShape: [1, 1]), + .init( + className: "VarianceNormalizedKVCache", arrayCount: 8, + metadata: ["32", "32", "4", "4", "2", "1", "0"], + arrayShape: [1, 1]), ]) -} + } -@Test func testArraysCacheAdvanceUpdatesSequenceMetadataOnly() throws { - let cache = ArraysCache(size: 2, leftPadding: [3, 5]) - cache.offset = 7 - cache.prepare(lengths: [4, 6]) + @Test func testPromptCacheRestorationAcceptsLegacyRotatingMetadata() throws { + let fixture = SerializedCacheFixture( + className: "RotatingKVCache", + arrayCount: 2, + metadata: ["0", "32", "256", "1", "1"]) + let url = try writePromptCacheFixture(fixture) + defer { try? FileManager.default.removeItem(at: url) } - cache.advance(2) + let (restored, _) = try loadPromptCache(url: url) + let rotating = try #require(restored.first as? RotatingKVCache) - #expect(cache.offset == 7) - #expect(cache.leftPaddingValues == [1, 3]) - #expect(cache.lengthsValues == [2, 4]) -} + #expect(rotating.capacityOrigin == .modelNative) + // Legacy metadata has no wrapped flag; the restored cache derives it (an + // unwrapped layout here) and re-serializes with the flag appended. + #expect(rotating.metaState == ["0", "32", "256", "1", "1", "modelNative", "false"]) + } -@Test func testArraysCacheMaskUsesLengthsWhenLeftPaddingIsAbsent() throws { - let cache = ArraysCache(size: 2) - cache.prepare(lengths: [1, 3]) + @Test func testPromptCacheRoundTripPreservesEmptyCaches() throws { + let populated = KVCacheSimple() + populated.state = [ + MLXArray.ones([1, 1, 1, 32], stream: .cpu), + MLXArray.ones([1, 1, 1, 32], stream: .cpu), + ] + let caches: [KVCache] = [ + KVCacheSimple(), + populated, + RotatingKVCache(maxSize: 32), + QuantizedKVCache(), + ChunkedKVCache(chunkSize: 16), + ] + let url = tempURL() + defer { try? FileManager.default.removeItem(at: url) } - let mask = try #require(cache.makeMask(N: 4)) - #expect( - mask.asArray(Bool.self) == [ - true, false, false, false, - true, true, true, false, - ]) -} + try savePromptCache(url: url, cache: caches) + let (restored, _) = try loadPromptCache(url: url) + + #expect(restored.count == caches.count) + #expect(restored[0] is KVCacheSimple) + #expect(restored[0].state.isEmpty) + #expect(restored[1].state.count == 2) + #expect(restored[2] is RotatingKVCache) + #expect(restored[2].state.isEmpty) + #expect(restored[3] is QuantizedKVCache) + #expect(restored[3].state.isEmpty) + #expect(restored[4] is ChunkedKVCache) + #expect(restored[4].state.isEmpty) + } -@Test func testTextSequenceLengthsComeFromAttentionMask() throws { - let tokens = MLXArray(0 ..< 8).reshaped(2, 4) - let mask = MLXArray([1, 1, 0, 0, 1, 1, 1, 0]).reshaped(2, 4) - let text = LMInput.Text(tokens: tokens, mask: mask) + // MARK: - ArraysCache sparse slot round-trip - #expect(text.sequenceLengths == [2, 3]) -} + @Test func testArraysCacheSparseSlots() throws { + let cache = ArraysCache(size: 3) + let a = MLXArray.ones([2, 4], dtype: .float32) * 3.0 + let b = MLXArray.ones([2, 4], dtype: .float32) * 7.0 + cache[0] = a + // slot 1 stays nil + cache[2] = b + + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) -@Test func testTextSequenceLengthsInferUniformBatches() throws { - let text = LMInput.Text(tokens: MLXArray(0 ..< 8).reshaped(2, 4)) + #expect(loaded.count == 1) + let restored = try #require(loaded[0] as? ArraysCache) + #expect(restored.slotCount == 3) + #expect(restored[0] != nil) + #expect(restored[1] == nil) + #expect(restored[2] != nil) + #expect(allClose(restored[0]!, a).item(Bool.self)) + #expect(allClose(restored[2]!, b).item(Bool.self)) + } - #expect(text.sequenceLengths == [4, 4]) -} + // MARK: - ArraysCache leftPadding round-trip -@Test func testCacheListForwardsPrepareAndFinalize() throws { - let arrays = ArraysCache(size: 2) - let cache = CacheList(arrays, KVCacheSimple()) + @Test func testArraysCacheLeftPadding() throws { + let cache = ArraysCache(size: 2, leftPadding: [0, 5]) + let a = MLXArray.ones([2, 4], dtype: .float32) + let b = MLXArray.ones([2, 4], dtype: .float32) * 2.0 + cache[0] = a + cache[1] = b - cache.prepare(lengths: [2, 4]) - #expect(arrays.lengthsValues == [2, 4]) + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) - cache.finalize() - #expect(arrays.lengthsValues == nil) -} + let restored = try #require(loaded[0] as? ArraysCache) + #expect(restored.leftPaddingValues == [0, 5]) + assertArraysClose(restored.state, cache.state) + } -@Test func testCacheListForwardsLifecycleThroughKVCacheProtocol() throws { - let lifecycle = LifecycleRecordingCache() - let cache = CacheList(KVCacheSimple(), lifecycle) + @Test func testArraysCacheMaskUsesLeftPaddingAfterStateUpdate() throws { + let cache = ArraysCache(size: 2, leftPadding: [1, 3]) + cache[0] = MLXArray.ones([2, 4], dtype: .float32) - cache.prepare(lengths: [2, 4]) - #expect(lifecycle.preparedLengths == [2, 4]) + let mask = try #require(cache.makeMask(N: 4)) + #expect( + mask.asArray(Bool.self) == [ + false, true, true, true, + false, false, false, true, + ]) + } - cache.finalize() - #expect(lifecycle.finalizeCallCount == 1) -} + @Test func testArraysCacheAdvanceUpdatesSequenceMetadataOnly() throws { + let cache = ArraysCache(size: 2, leftPadding: [3, 5]) + cache.offset = 7 + cache.prepare(lengths: [4, 6]) -@Test func testWithPreparedCacheScopesSequenceMetadata() throws { - let cache = ArraysCache(size: 2) + cache.advance(2) - withPreparedCache([cache], lengths: [2, 4]) { + #expect(cache.offset == 7) + #expect(cache.leftPaddingValues == [1, 3]) #expect(cache.lengthsValues == [2, 4]) } - #expect(cache.lengthsValues == nil) -} - -@Test func testArraysCacheLengthsRoundTrip() throws { - let cache = ArraysCache(size: 2) - cache.prepare(lengths: [4, 2]) - cache[0] = MLXArray.ones([2, 4], dtype: .float32) + @Test func testArraysCacheMaskUsesLengthsWhenLeftPaddingIsAbsent() throws { + let cache = ArraysCache(size: 2) + cache.prepare(lengths: [1, 3]) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + let mask = try #require(cache.makeMask(N: 4)) + #expect( + mask.asArray(Bool.self) == [ + true, false, false, false, + true, true, true, false, + ]) + } - let restored = try #require(loaded[0] as? ArraysCache) - #expect(restored.currentLengths?.asArray(Int.self) == [4, 2]) - #expect(restored.lengthsValues == [4, 2]) - assertArraysClose(restored.state, cache.state) -} + @Test func testTextSequenceLengthsComeFromAttentionMask() throws { + let tokens = MLXArray(0 ..< 8).reshaped(2, 4) + let mask = MLXArray([1, 1, 0, 0, 1, 1, 1, 0]).reshaped(2, 4) + let text = LMInput.Text(tokens: tokens, mask: mask) -@Test func testArraysCacheAdvanceUpdatesLengthsAndLeftPaddingMasks() throws { - let cache = ArraysCache(size: 2, leftPadding: [1, 3]) - cache.prepare(lengths: [4, 2]) - cache.advance(2) + #expect(text.sequenceLengths == [2, 3]) + } - #expect(cache.leftPaddingValues == [-1, 1]) - #expect(cache.currentLengths?.asArray(Int.self) == [2, 0]) + @Test func testTextSequenceLengthsInferUniformBatches() throws { + let text = LMInput.Text(tokens: MLXArray(0 ..< 8).reshaped(2, 4)) - let mask = try #require(cache.makeMask(N: 3)) - #expect(mask.asArray(Bool.self) == [true, true, true, false, true, true]) + #expect(text.sequenceLengths == [4, 4]) + } - let lengthOnly = ArraysCache(size: 1) - lengthOnly.prepare(lengths: [2, 0]) - let lengthMask = try #require(lengthOnly.makeMask(N: 3)) - #expect(lengthMask.asArray(Bool.self) == [true, true, false, false, false, false]) + @Test func testCacheListForwardsPrepareAndFinalize() throws { + let arrays = ArraysCache(size: 2) + let cache = CacheList(arrays, KVCacheSimple()) - cache.finalize() - #expect(cache.leftPaddingValues == nil) - #expect(cache.currentLengths == nil) -} + cache.prepare(lengths: [2, 4]) + #expect(arrays.lengthsValues == [2, 4]) -@Test func testArraysCacheFilterAndExtendPreserveBatchMetadata() throws { - let first = ArraysCache(size: 1, leftPadding: [0, 2]) - first.prepare(lengths: [5, 3]) - first[0] = MLXArray.ones([2, 2], dtype: .float32) + cache.finalize() + #expect(arrays.lengthsValues == nil) + } - first.filter(batchIndices: MLXArray([1])) - #expect(first.leftPaddingValues == [2]) - #expect(first.currentLengths?.asArray(Int.self) == [3]) - #expect(first[0]?.shape == [1, 2]) + @Test func testCacheListForwardsLifecycleThroughKVCacheProtocol() throws { + let lifecycle = LifecycleRecordingCache() + let cache = CacheList(KVCacheSimple(), lifecycle) - let second = ArraysCache(size: 1, leftPadding: [1, 4]) - second.prepare(lengths: [6, 2]) - second[0] = MLXArray.ones([2, 2], dtype: .float32) * 2 + cache.prepare(lengths: [2, 4]) + #expect(lifecycle.preparedLengths == [2, 4]) - first.extend(other: second) - #expect(first.leftPaddingValues == [2, 1, 4]) - #expect(first.currentLengths?.asArray(Int.self) == [3, 6, 2]) - #expect(first[0]?.shape == [3, 2]) -} + cache.finalize() + #expect(lifecycle.finalizeCallCount == 1) + } -@Test func testAttentionMaskUsesSharedCausalCachePath() throws { - let cache = KVCacheSimple() - let prefillInput = MLXArray.ones([1, 3, 8], dtype: .float32) - - let prefillMask = createAttentionMask(h: prefillInput, cache: cache) - if case .causal = prefillMask { - // Expected for multi-token prefill: Falcon H1 uses the shared symbolic causal mask path. - } else { - Issue.record("Expected symbolic causal attention mask for prefill") - } - - let tokenInput = MLXArray.ones([1, 1, 8], dtype: .float32) - let tokenMask = createAttentionMask(h: tokenInput, cache: cache) - if case .none = tokenMask { - // Expected for one-token decode: no materialized mask is needed. - } else { - Issue.record("Expected no attention mask for one-token decode") - } - - cache.offset = 2 - let forcedMask = createAttentionMask(h: prefillInput, cache: cache, returnArray: true) - guard case .array(let mask) = forcedMask else { - Issue.record("Expected forced attention mask array") - return - } - #expect(mask.shape == [3, 5]) - #expect( - mask.asArray(Bool.self) == [ - true, true, true, false, false, - true, true, true, true, false, - true, true, true, true, true, - ]) -} + @Test func testWithPreparedCacheScopesSequenceMetadata() throws { + let cache = ArraysCache(size: 2) -@Test func testSSMMaskUsesSharedMambaMetadataPath() throws { - let leftPadded = MambaCache(leftPadding: [1, 3]) - let input = MLXArray.ones([2, 4, 8], dtype: .float32) + withPreparedCache([cache], lengths: [2, 4]) { + #expect(cache.lengthsValues == [2, 4]) + } - let leftPaddingMask = try #require(createSSMMask(h: input, cache: leftPadded)) - #expect( - leftPaddingMask.asArray(Bool.self) == [ - false, true, true, true, - false, false, false, true, - ]) + #expect(cache.lengthsValues == nil) + } - let lengthMasked = MambaCache() - lengthMasked.prepare(lengths: [3, 1]) - let lengthsMask = try #require(createSSMMask(h: input, cache: lengthMasked)) - #expect( - lengthsMask.asArray(Bool.self) == [ - true, true, true, false, - true, false, false, false, - ]) -} + @Test func testArraysCacheLengthsRoundTrip() throws { + let cache = ArraysCache(size: 2) + cache.prepare(lengths: [4, 2]) + cache[0] = MLXArray.ones([2, 4], dtype: .float32) -@Test func testCacheListPrepareFinalizePropagatesThroughNestedHybridCaches() throws { - let mamba = MambaCache(leftPadding: [0, 2]) - let arrays = ArraysCache(size: 1) - let nested = CacheList(CacheList(mamba), arrays) + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) - nested.prepare(lengths: [4, 1]) + let restored = try #require(loaded[0] as? ArraysCache) + #expect(restored.currentLengths?.asArray(Int.self) == [4, 2]) + #expect(restored.lengthsValues == [4, 2]) + assertArraysClose(restored.state, cache.state) + } - #expect(mamba.currentLengths?.asArray(Int.self) == [4, 1]) - #expect(arrays.currentLengths?.asArray(Int.self) == [4, 1]) + @Test func testArraysCacheAdvanceUpdatesLengthsAndLeftPaddingMasks() throws { + let cache = ArraysCache(size: 2, leftPadding: [1, 3]) + cache.prepare(lengths: [4, 2]) + cache.advance(2) - nested.finalize() + #expect(cache.leftPaddingValues == [-1, 1]) + #expect(cache.currentLengths?.asArray(Int.self) == [2, 0]) - #expect(mamba.currentLengths == nil) - #expect(mamba.leftPaddingValues == nil) - #expect(arrays.currentLengths == nil) -} + let mask = try #require(cache.makeMask(N: 3)) + #expect(mask.asArray(Bool.self) == [true, true, true, false, true, true]) -@Test func testMambaCacheCopyPreservesBatchMaskMetadata() throws { - let cache = MambaCache(leftPadding: [2, 0]) - cache.prepare(lengths: [5, 3]) - cache[0] = MLXArray.ones([2, 3, 4], dtype: .float32) - cache[1] = MLXArray.ones([2, 1, 4, 4], dtype: .float32) + let lengthOnly = ArraysCache(size: 1) + lengthOnly.prepare(lengths: [2, 0]) + let lengthMask = try #require(lengthOnly.makeMask(N: 3)) + #expect(lengthMask.asArray(Bool.self) == [true, true, false, false, false, false]) - let copied = try #require(cache.copy() as? MambaCache) + cache.finalize() + #expect(cache.leftPaddingValues == nil) + #expect(cache.currentLengths == nil) + } - #expect(copied.leftPaddingValues == [2, 0]) - #expect(copied.currentLengths?.asArray(Int.self) == [5, 3]) - #expect(copied[0]?.shape == [2, 3, 4]) - #expect(copied[1]?.shape == [2, 1, 4, 4]) -} + @Test func testArraysCacheFilterAndExtendPreserveBatchMetadata() throws { + let first = ArraysCache(size: 1, leftPadding: [0, 2]) + first.prepare(lengths: [5, 3]) + first[0] = MLXArray.ones([2, 2], dtype: .float32) -@Test func testArraysCacheFilterKeepsSequenceMetadata() throws { - let cache = ArraysCache(size: 2, leftPadding: [1, 3]) - cache.prepare(lengths: [2, 4]) - cache[0] = MLXArray.ones([2, 4], dtype: .float32) + first.filter(batchIndices: MLXArray([1])) + #expect(first.leftPaddingValues == [2]) + #expect(first.currentLengths?.asArray(Int.self) == [3]) + #expect(first[0]?.shape == [1, 2]) - cache.filter(batchIndices: MLXArray([1])) + let second = ArraysCache(size: 1, leftPadding: [1, 4]) + second.prepare(lengths: [6, 2]) + second[0] = MLXArray.ones([2, 2], dtype: .float32) * 2 - #expect(cache.leftPaddingValues == [3]) - #expect(cache.lengthsValues == [4]) -} + first.extend(other: second) + #expect(first.leftPaddingValues == [2, 1, 4]) + #expect(first.currentLengths?.asArray(Int.self) == [3, 6, 2]) + #expect(first[0]?.shape == [3, 2]) + } -@Test func testArraysCacheExtendPadsMissingSlotsAndMetadata() throws { - let first = ArraysCache(size: 2, leftPadding: [1, 3]) - first.prepare(lengths: [2, 4]) - first[0] = MLXArray.ones([2, 4], dtype: .float32) + @Test func testAttentionMaskUsesSharedCausalCachePath() throws { + let cache = KVCacheSimple() + let prefillInput = MLXArray.ones([1, 3, 8], dtype: .float32) - let second = ArraysCache(size: 2) - second[1] = MLXArray.ones([1, 4], dtype: .float32) * 2 + let prefillMask = createAttentionMask(h: prefillInput, cache: cache) + if case .causal = prefillMask { + // Expected for multi-token prefill: Falcon H1 uses the shared symbolic causal mask path. + } else { + Issue.record("Expected symbolic causal attention mask for prefill") + } - first.extend(other: second) + let tokenInput = MLXArray.ones([1, 1, 8], dtype: .float32) + let tokenMask = createAttentionMask(h: tokenInput, cache: cache) + if case .none = tokenMask { + // Expected for one-token decode: no materialized mask is needed. + } else { + Issue.record("Expected no attention mask for one-token decode") + } - #expect(first[0]?.shape == [3, 4]) - #expect(first[1]?.shape == [3, 4]) - #expect(first.leftPaddingValues == [1, 3, 0]) - #expect(first.lengthsValues == [2, 4, 0]) -} + cache.offset = 2 + let forcedMask = createAttentionMask(h: prefillInput, cache: cache, returnArray: true) + guard case .array(let mask) = forcedMask else { + Issue.record("Expected forced attention mask array") + return + } + #expect(mask.shape == [3, 5]) + #expect( + mask.asArray(Bool.self) == [ + true, true, true, false, false, + true, true, true, true, false, + true, true, true, true, true, + ]) + } -@Test func testArraysCacheCopyPreservesSparseSlotsAndMetadata() throws { - let cache = ArraysCache(size: 3, leftPadding: [2]) - cache.prepare(lengths: [5]) - cache[2] = MLXArray.ones([1, 4], dtype: .float32) + @Test func testSSMMaskUsesSharedMambaMetadataPath() throws { + let leftPadded = MambaCache(leftPadding: [1, 3]) + let input = MLXArray.ones([2, 4, 8], dtype: .float32) - let copied = try #require(cache.copy() as? ArraysCache) + let leftPaddingMask = try #require(createSSMMask(h: input, cache: leftPadded)) + #expect( + leftPaddingMask.asArray(Bool.self) == [ + false, true, true, true, + false, false, false, true, + ]) + + let lengthMasked = MambaCache() + lengthMasked.prepare(lengths: [3, 1]) + let lengthsMask = try #require(createSSMMask(h: input, cache: lengthMasked)) + #expect( + lengthsMask.asArray(Bool.self) == [ + true, true, true, false, + true, false, false, false, + ]) + } - #expect(copied.slotCount == 3) - #expect(copied[0] == nil) - #expect(copied[1] == nil) - #expect(copied[2] != nil) - #expect(copied.leftPaddingValues == [2]) - #expect(copied.lengthsValues == [5]) -} + @Test func testCacheListPrepareFinalizePropagatesThroughNestedHybridCaches() throws { + let mamba = MambaCache(leftPadding: [0, 2]) + let arrays = ArraysCache(size: 1) + let nested = CacheList(CacheList(mamba), arrays) -// MARK: - MambaCache type preservation + nested.prepare(lengths: [4, 1]) -@Test func testMambaCacheRoundTrip() throws { - let cache = MambaCache() - let a = MLXArray.ones([2, 4], dtype: .float32) * 5.0 - let b = MLXArray.ones([2, 4], dtype: .float32) * 9.0 - cache[0] = a - cache[1] = b + #expect(mamba.currentLengths?.asArray(Int.self) == [4, 1]) + #expect(arrays.currentLengths?.asArray(Int.self) == [4, 1]) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + nested.finalize() - #expect(loaded.count == 1) - let restored = try #require(loaded[0] as? MambaCache) - #expect(restored.slotCount == 2) - assertArraysClose(restored.state, cache.state) -} + #expect(mamba.currentLengths == nil) + #expect(mamba.leftPaddingValues == nil) + #expect(arrays.currentLengths == nil) + } -// MARK: - CacheList with KV caches + @Test func testMambaCacheCopyPreservesBatchMaskMetadata() throws { + let cache = MambaCache(leftPadding: [2, 0]) + cache.prepare(lengths: [5, 3]) + cache[0] = MLXArray.ones([2, 3, 4], dtype: .float32) + cache[1] = MLXArray.ones([2, 1, 4, 4], dtype: .float32) -@Test func testCacheListKVCaches() throws { - let simple = KVCacheSimple() - let rotating = RotatingKVCache(maxSize: 32) + let copied = try #require(cache.copy() as? MambaCache) - let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - _ = simple.update(keys: keys, values: values) - _ = rotating.update(keys: keys * 2.0, values: values * 2.0) + #expect(copied.leftPaddingValues == [2, 0]) + #expect(copied.currentLengths?.asArray(Int.self) == [5, 3]) + #expect(copied[0]?.shape == [2, 3, 4]) + #expect(copied[1]?.shape == [2, 1, 4, 4]) + } - let cacheList = CacheList(simple, rotating) + @Test func testArraysCacheFilterKeepsSequenceMetadata() throws { + let cache = ArraysCache(size: 2, leftPadding: [1, 3]) + cache.prepare(lengths: [2, 4]) + cache[0] = MLXArray.ones([2, 4], dtype: .float32) - let url = tempURL() - try savePromptCache(url: url, cache: [cacheList], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + cache.filter(batchIndices: MLXArray([1])) - #expect(loaded.count == 1) - let restored = try #require(loaded[0] as? CacheList) - let child0 = try #require(restored[0] as? KVCacheSimple) - let child1 = try #require(restored[1] as? RotatingKVCache) + #expect(cache.leftPaddingValues == [3]) + #expect(cache.lengthsValues == [4]) + } - assertArraysClose(child0.state, simple.state, label: "child0") - assertArraysClose(child1.state, rotating.state, label: "child1") - #expect(child1.metaState == rotating.metaState) -} + @Test func testArraysCacheExtendPadsMissingSlotsAndMetadata() throws { + let first = ArraysCache(size: 2, leftPadding: [1, 3]) + first.prepare(lengths: [2, 4]) + first[0] = MLXArray.ones([2, 4], dtype: .float32) -// MARK: - CacheList with hybrid (MambaCache + KVCacheSimple) + let second = ArraysCache(size: 2) + second[1] = MLXArray.ones([1, 4], dtype: .float32) * 2 -@Test func testCacheListHybrid() throws { - let mamba = MambaCache() - mamba[0] = MLXArray.ones([2, 4], dtype: .float32) * 3.0 - mamba[1] = MLXArray.ones([2, 4], dtype: .float32) * 4.0 + first.extend(other: second) - let simple = KVCacheSimple() - let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - _ = simple.update(keys: keys, values: values) + #expect(first[0]?.shape == [3, 4]) + #expect(first[1]?.shape == [3, 4]) + #expect(first.leftPaddingValues == [1, 3, 0]) + #expect(first.lengthsValues == [2, 4, 0]) + } - let cacheList = CacheList(mamba, simple) + @Test func testArraysCacheCopyPreservesSparseSlotsAndMetadata() throws { + let cache = ArraysCache(size: 3, leftPadding: [2]) + cache.prepare(lengths: [5]) + cache[2] = MLXArray.ones([1, 4], dtype: .float32) - let url = tempURL() - try savePromptCache(url: url, cache: [cacheList], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + let copied = try #require(cache.copy() as? ArraysCache) - #expect(loaded.count == 1) - let restored = try #require(loaded[0] as? CacheList) - let restoredMamba = try #require(restored[0] as? MambaCache) - let restoredSimple = try #require(restored[1] as? KVCacheSimple) + #expect(copied.slotCount == 3) + #expect(copied[0] == nil) + #expect(copied[1] == nil) + #expect(copied[2] != nil) + #expect(copied.leftPaddingValues == [2]) + #expect(copied.lengthsValues == [5]) + } - assertArraysClose(restoredMamba.state, mamba.state, label: "mamba") - assertArraysClose(restoredSimple.state, simple.state, label: "simple") -} + // MARK: - MambaCache type preservation -// MARK: - Simple cache round-trip with value assertions + @Test func testMambaCacheRoundTrip() throws { + let cache = MambaCache() + let a = MLXArray.ones([2, 4], dtype: .float32) * 5.0 + let b = MLXArray.ones([2, 4], dtype: .float32) * 9.0 + cache[0] = a + cache[1] = b -@Test func testSimpleCacheRoundTrip() throws { - let cache = KVCacheSimple() - let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) - _ = cache.update(keys: keys, values: values) + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) - #expect(loaded.count == 1) - assertArraysClose(loaded[0].state, cache.state) -} + #expect(loaded.count == 1) + let restored = try #require(loaded[0] as? MambaCache) + #expect(restored.slotCount == 2) + assertArraysClose(restored.state, cache.state) + } -// MARK: - ArraysCache fully populated round-trip + // MARK: - CacheList with KV caches -@Test func testArraysCacheFullyPopulated() throws { - let cache = ArraysCache(size: 2) - cache[0] = MLXArray.ones([2, 4], dtype: .float32) - cache[1] = MLXArray.ones([2, 4], dtype: .float32) * 2.0 + @Test func testCacheListKVCaches() throws { + let simple = KVCacheSimple() + let rotating = RotatingKVCache(maxSize: 32) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: [:]) - let (loaded, _) = try loadPromptCache(url: url) + let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + _ = simple.update(keys: keys, values: values) + _ = rotating.update(keys: keys * 2.0, values: values * 2.0) - #expect(loaded.count == 1) - let restored = try #require(loaded[0] as? ArraysCache) - #expect(restored.slotCount == 2) - assertArraysClose(restored.state, cache.state) -} + let cacheList = CacheList(simple, rotating) -/// Verify that copy() produces an independent cache: same type, same state, -/// but mutating the copy does not affect the original. -@Test( - .serialized, - arguments: cacheCreators) -func testCacheCopyIsIndependent(creator: (() -> any KVCache)) async throws { - let original = creator() - - let keys = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) - - // populate the original - switch original { - case let arrays as ArraysCache: - arrays[0] = keys - arrays[1] = values - case let quantized as QuantizedKVCache: - _ = quantized.updateQuantized(keys: keys, values: values) - default: - _ = original.update(keys: keys, values: values) - } - - let originalOffset = original.offset - let originalState = original.state - eval(originalState) - let originalMeta = original.metaState - - // copy - let copied = original.copy() - - // same type - #expect(type(of: original) == type(of: copied)) - - // same offset and metadata - #expect(copied.offset == originalOffset) - #expect(copied.metaState == originalMeta) - - // same state values - let copiedState = copied.state - eval(copiedState) - #expect(copiedState.count == originalState.count) - for (origArr, copyArr) in zip(originalState, copiedState) { - #expect(origArr.shape == copyArr.shape) - #expect(allClose(origArr, copyArr).item(Bool.self)) - } - - // mutate the copy — push more tokens through it - let moreKeys = MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) - let moreValues = MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) - - switch copied { - case let arrays as ArraysCache: - // overwrite slot 0 with a different array - arrays[0] = moreKeys - case let quantized as QuantizedKVCache: - _ = quantized.updateQuantized(keys: moreKeys, values: moreValues) - default: - _ = copied.update(keys: moreKeys, values: moreValues) - } - - // original must be unchanged - #expect(original.offset == originalOffset) - #expect(original.metaState == originalMeta) - let currentState = original.state - eval(currentState) - #expect(currentState.count == originalState.count) - for (origArr, savedArr) in zip(currentState, originalState) { - #expect(origArr.shape == savedArr.shape) - #expect(allClose(origArr, savedArr).item(Bool.self)) - } -} + let url = tempURL() + try savePromptCache(url: url, cache: [cacheList], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) -/// copy() on an empty (unpopulated) cache must not crash. -@Test( - .serialized, - arguments: cacheCreators) -func testCacheCopyOnEmptyCache(creator: (() -> any KVCache)) async throws { - let empty = creator() - let copied = empty.copy() - - #expect(type(of: empty) == type(of: copied)) - #expect(copied.offset == 0) - #expect(copied.state.count == empty.state.count) -} + #expect(loaded.count == 1) + let restored = try #require(loaded[0] as? CacheList) + let child0 = try #require(restored[0] as? KVCacheSimple) + let child1 = try #require(restored[1] as? RotatingKVCache) -/// CacheList.copy() produces independent sub-caches. -@Test -func testCacheListCopyIsIndependent() async throws { - let sub1 = KVCacheSimple() - let sub2 = RotatingKVCache(maxSize: 32) - let composite = CacheList(sub1, sub2) - - let keys = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) - let values = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) - _ = sub1.update(keys: keys, values: values) - _ = sub2.update(keys: keys, values: values) - - // snapshot original state — eval to materialize before copy - let originalState = composite.state - eval(originalState) - let originalOffset0 = sub1.offset - let originalOffset1 = sub2.offset - - let copied = composite.copy() - - #expect(copied is CacheList) - let copiedState = copied.state - eval(copiedState) - #expect(copiedState.count == originalState.count) - for (orig, copy) in zip(originalState, copiedState) { - #expect(orig.shape == copy.shape) - #expect(allClose(orig, copy).item(Bool.self)) - } - - // mutate inside the copy - let copiedList = copied as! CacheList - _ = copiedList[0].update( - keys: MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16), - values: MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) - ) - - // originals unchanged - #expect(sub1.offset == originalOffset0) - #expect(sub2.offset == originalOffset1) - let currentState = composite.state - eval(currentState) - #expect(currentState.count == originalState.count) - for (orig, saved) in zip(currentState, originalState) { - #expect(orig.shape == saved.shape) - #expect(allClose(orig, saved).item(Bool.self)) + assertArraysClose(child0.state, simple.state, label: "child0") + assertArraysClose(child1.state, rotating.state, label: "child1") + #expect(child1.metaState == rotating.metaState) } -} -// MARK: - Quantized attention causal masking -// Regression for the finfo.min mistranslation (masked fill was Float.leastNormalMagnitude ≈ 0). + // MARK: - CacheList with hybrid (MambaCache + KVCacheSimple) -@Test -func testQuantizedAttentionCausalMaskMatchesFullPrecision() throws { - withRandomState(MLXRandom.RandomState(seed: 0)) { - let (B, nKVHeads, L, D) = (1, 2, 4, 64) - let scale = 1.0 / Float(D).squareRoot() + @Test func testCacheListHybrid() throws { + let mamba = MambaCache() + mamba[0] = MLXArray.ones([2, 4], dtype: .float32) * 3.0 + mamba[1] = MLXArray.ones([2, 4], dtype: .float32) * 4.0 - // nRepeats 1 = MHA, 2 = GQA (exercises the 5-D reshape + .causal path that silently corrupts). - for nRepeats in [1, 2] { - let nQHeads = nKVHeads * nRepeats - let q = MLXRandom.normal([B, nQHeads, L, D]) - let k = MLXRandom.normal([B, nKVHeads, L, D]) - let v = MLXRandom.normal([B, nKVHeads, L, D]) + let simple = KVCacheSimple() + let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + _ = simple.update(keys: keys, values: values) - // Reference: full-precision causal attention. - let reference = MLXFast.scaledDotProductAttention( - queries: q, keys: k, values: v, scale: scale, mask: .causal) + let cacheList = CacheList(mamba, simple) - // Path under test: quantized cache + .causal. - let cache = QuantizedKVCache(groupSize: 64, bits: 8) - let (qK, qV) = cache.updateQuantized(keys: k, values: v) - let out = quantizedScaledDotProductAttention( - queries: q, quantizedKeys: qK, quantizedValues: qV, - scale: scale, mask: .causal, - groupSize: cache.groupSize, bits: cache.bits, mode: cache.mode) + let url = tempURL() + try savePromptCache(url: url, cache: [cacheList], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) - #expect(out.shape == reference.shape) - // 8-bit quant error is << 0.1; the bug diverges by O(1). - let close = allClose(out, reference, rtol: 0.05, atol: 0.1).item(Bool.self) - #expect( - close, - "quantized causal attention diverges from full precision (nRepeats=\(nRepeats))") - } - } -} + #expect(loaded.count == 1) + let restored = try #require(loaded[0] as? CacheList) + let restoredMamba = try #require(restored[0] as? MambaCache) + let restoredSimple = try #require(restored[1] as? KVCacheSimple) -@Test("quantizedScaledDotProductAttention preserves the score dtype") -func preservesScoreDtype() { - withRandomState(MLXRandom.RandomState(seed: 0)) { - let (B, H, L, D) = (1, 2, 4, 64) - let scale = 1.0 / Float(D).squareRoot() - - // f32 passes even with a mis-typed fill; f16/bf16 are exactly what a - // float32 fill silently promotes — so assert the output keeps its dtype. - for dtype in [DType.float16, .bfloat16, .float32] { - let q = MLXRandom.normal([B, H, L, D]).asType(dtype) - let k = MLXRandom.normal([B, H, L, D]).asType(dtype) - let v = MLXRandom.normal([B, H, L, D]).asType(dtype) - - let cache = QuantizedKVCache(groupSize: 64, bits: 8) - let (qK, qV) = cache.updateQuantized(keys: k, values: v) - let out = quantizedScaledDotProductAttention( - queries: q, quantizedKeys: qK, quantizedValues: qV, - scale: scale, mask: .causal, - groupSize: cache.groupSize, bits: cache.bits, mode: cache.mode) - - #expect(out.dtype == dtype, "output promoted to \(out.dtype) for input \(dtype)") - #expect(out.asType(.float32).sum().item(Float.self).isFinite) // no -inf → NaN - } + assertArraysClose(restoredMamba.state, mamba.state, label: "mamba") + assertArraysClose(restoredSimple.state, simple.state, label: "simple") } -} -// MARK: - ropeOffset overridability + // MARK: - Simple cache round-trip with value assertions -/// A `BaseKVCache` subclass reporting a per-row RoPE offset, as a batched cache does. -private final class BatchOffsetProbeCache: BaseKVCache { - override var ropeOffset: RoPEOffset { .batch(MLXArray([10, 20])) } + @Test func testSimpleCacheRoundTrip() throws { + let cache = KVCacheSimple() + let keys = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 16, 64], dtype: .bfloat16) + _ = cache.update(keys: keys, values: values) - override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { - (keys, values) + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) + #expect(loaded.count == 1) + assertArraysClose(loaded[0].state, cache.state) } -} -/// Models read `ropeOffset` through a `KVCache` reference, so a subclass override has to -/// survive that dispatch. When `BaseKVCache` did not declare `ropeOffset`, the extension -/// default was the witness and this resolved to `.scalar(0)`, silently ignoring the subclass. -@Test func testSubclassRopeOffsetOverrideIsHonoredThroughKVCacheReference() { - let cache: any KVCache = BatchOffsetProbeCache() - - guard case .batch(let offsets) = cache.ropeOffset else { - Issue.record( - "subclass ropeOffset override ignored — resolved to the .scalar extension default") - return - } - #expect(offsets.asArray(Int32.self) == [10, 20]) -} + // MARK: - ArraysCache fully populated round-trip -// MARK: - RotatingKVCache.logicalView -// -// `logicalView(tail:)` is the read-only counterpart to `update(keys:values:)`: it exposes the -// ring's contents in chronological order without writing. Speculative decoding needs it to -// present committed history alongside K/V it has not committed yet. -// -// Nothing in this repo drove a `RotatingKVCache` ring past its wrap before these tests, so the -// rotation in `updateInPlace`, the linearization in `temporalOrder`, and the windowed mask that -// `makeMask` builds over the multi-token presentation were all uncovered. They are the -// foundation the view rests on, so they are pinned here too. - -/// K/V whose every element encodes its own sequence position: keys hold `+p`, values `-p`. -/// Any reordering, duplication, or K/V mix-up changes the numbers. -private func positionedKV( - _ positions: Range, headDim: Int = 2 -) -> (MLXArray, MLXArray) { - let count = positions.count - let keys = MLXArray( - positions.flatMap { Array(repeating: Float($0), count: headDim) }, - [1, 1, count, headDim]) - let values = MLXArray( - positions.flatMap { Array(repeating: Float(-$0), count: headDim) }, - [1, 1, count, headDim]) - return (keys, values) -} + @Test func testArraysCacheFullyPopulated() throws { + let cache = ArraysCache(size: 2) + cache[0] = MLXArray.ones([2, 4], dtype: .float32) + cache[1] = MLXArray.ones([2, 4], dtype: .float32) * 2.0 -/// Recover the sequence positions encoded by `positionedKV` from a `[B, H, S, D]` key array. -private func encodedPositions(_ keys: MLXArray) -> [Int] { - keys[0, 0, 0..., 0].asArray(Float.self).map { Int($0) } -} + let url = tempURL() + try savePromptCache(url: url, cache: [cache], metadata: [:]) + let (loaded, _) = try loadPromptCache(url: url) -/// Drive `cache` through `count` single-token writes, so the ring actually rotates. -private func fillOneAtATime(_ cache: RotatingKVCache, positions: Range) { - for p in positions { - let (k, v) = positionedKV(p ..< (p + 1)) - _ = cache.update(keys: k, values: v) + #expect(loaded.count == 1) + let restored = try #require(loaded[0] as? ArraysCache) + #expect(restored.slotCount == 2) + assertArraysClose(restored.state, cache.state) } -} - -@Test func testRotatingLogicalViewIsNilBeforeFirstWrite() { - #expect(RotatingKVCache(maxSize: 8, keep: 0).logicalView(tail: 8) == nil) -} -@Test func testRotatingLogicalViewReturnsChronologicalTailPastWrap() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) + /// Verify that copy() produces an independent cache: same type, same state, + /// but mutating the copy does not affect the original. + @Test( + .serialized, + arguments: cacheCreators) + func testCacheCopyIsIndependent(creator: (() -> any KVCache)) async throws { + let original = creator() - // The ring has wrapped twice; physical order is rotated, chronological order is not. - #expect(cache.offset == 20) + let keys = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) - let full = try #require(cache.logicalView(tail: 8)) - #expect( - encodedPositions(full.0) == Array(12 ..< 20), - "logicalView did not linearize the rotated ring") - #expect(encodedPositions(full.1).map { -$0 } == Array(12 ..< 20), "values diverged from keys") + // populate the original + switch original { + case let arrays as ArraysCache: + arrays[0] = keys + arrays[1] = values + case let quantized as QuantizedKVCache: + _ = quantized.updateQuantized(keys: keys, values: values) + default: + _ = original.update(keys: keys, values: values) + } - let short = try #require(cache.logicalView(tail: 3)) - #expect(encodedPositions(short.0) == [17, 18, 19], "a short tail took the wrong end") -} + let originalOffset = original.offset + let originalState = original.state + eval(originalState) + let originalMeta = original.metaState -@Test func testRotatingLogicalViewClampsTailToWhatTheCacheHolds() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 5) + // copy + let copied = original.copy() - #expect(encodedPositions(try #require(cache.logicalView(tail: 99)).0) == Array(0 ..< 5)) - #expect(encodedPositions(try #require(cache.logicalView(tail: 5)).0) == Array(0 ..< 5)) - #expect(try #require(cache.logicalView(tail: 0)).0.dim(2) == 0) - #expect(try #require(cache.logicalView(tail: -1)).0.dim(2) == 0, "negative tail must clamp") -} + // same type + #expect(type(of: original) == type(of: copied)) -@Test func testRotatingLogicalViewLeavesTheRingUntouched() { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) + // same offset and metadata + #expect(copied.offset == originalOffset) + #expect(copied.metaState == originalMeta) - let beforeState = cache.innerState().map { MLXArray($0.asArray(Float.self), $0.shape) } - let beforeOffset = cache.offset - let beforeMeta = cache.metaState + // same state values + let copiedState = copied.state + eval(copiedState) + #expect(copiedState.count == originalState.count) + for (origArr, copyArr) in zip(originalState, copiedState) { + #expect(origArr.shape == copyArr.shape) + #expect(allClose(origArr, copyArr).item(Bool.self)) + } - _ = cache.logicalView(tail: 7) - _ = cache.logicalView(tail: 3) + // mutate the copy — push more tokens through it + let moreKeys = MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) + let moreValues = MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) - let afterState = cache.innerState() - #expect(afterState.count == beforeState.count) - for (index, (before, after)) in zip(beforeState, afterState).enumerated() { - #expect(before.shape == after.shape, "innerState[\(index)] was reshaped by a read") - #expect( - allClose(before, after, rtol: 0, atol: 0).item(Bool.self), - "innerState[\(index)] was mutated by a read") + switch copied { + case let arrays as ArraysCache: + // overwrite slot 0 with a different array + arrays[0] = moreKeys + case let quantized as QuantizedKVCache: + _ = quantized.updateQuantized(keys: moreKeys, values: moreValues) + default: + _ = copied.update(keys: moreKeys, values: moreValues) + } + + // original must be unchanged + #expect(original.offset == originalOffset) + #expect(original.metaState == originalMeta) + let currentState = original.state + eval(currentState) + #expect(currentState.count == originalState.count) + for (origArr, savedArr) in zip(currentState, originalState) { + #expect(origArr.shape == savedArr.shape) + #expect(allClose(origArr, savedArr).item(Bool.self)) + } } - #expect(cache.offset == beforeOffset, "logicalView moved the offset") - #expect(cache.metaState == beforeMeta, "logicalView disturbed idx/offset bookkeeping") -} -@Test func testRotatingLogicalViewPreservesPinnedPrefix() throws { - // `keep` pins the oldest entries; the write path front-trims *after* them, so a view must - // splice around the prefix rather than take a flat tail. - let cache = RotatingKVCache(maxSize: 8, keep: 2) - fillOneAtATime(cache, positions: 0 ..< 20) - - let view = try #require(cache.logicalView(tail: 5)) - let positions = encodedPositions(view.0) - #expect(positions.count == 5) - #expect(Array(positions.prefix(2)) == [0, 1], "pinned prefix was evicted by the view") - #expect(positions == [0, 1] + Array(positions.suffix(3))) - #expect(positions.suffix(3).sorted() == Array(positions.suffix(3)), "tail out of order") -} + /// copy() on an empty (unpopulated) cache must not crash. + @Test( + .serialized, + arguments: cacheCreators) + func testCacheCopyOnEmptyCache(creator: (() -> any KVCache)) async throws { + let empty = creator() + let copied = empty.copy() + + #expect(type(of: empty) == type(of: copied)) + #expect(copied.offset == 0) + #expect(copied.state.count == empty.state.count) + } + + /// CacheList.copy() produces independent sub-caches. + @Test + func testCacheListCopyIsIndependent() async throws { + let sub1 = KVCacheSimple() + let sub2 = RotatingKVCache(maxSize: 32) + let composite = CacheList(sub1, sub2) + + let keys = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) + let values = MLXArray.ones([1, 8, 4, 64], dtype: .bfloat16) + _ = sub1.update(keys: keys, values: values) + _ = sub2.update(keys: keys, values: values) + + // snapshot original state — eval to materialize before copy + let originalState = composite.state + eval(originalState) + let originalOffset0 = sub1.offset + let originalOffset1 = sub2.offset + + let copied = composite.copy() + + #expect(copied is CacheList) + let copiedState = copied.state + eval(copiedState) + #expect(copiedState.count == originalState.count) + for (orig, copy) in zip(originalState, copiedState) { + #expect(orig.shape == copy.shape) + #expect(allClose(orig, copy).item(Bool.self)) + } + + // mutate inside the copy + let copiedList = copied as! CacheList + _ = copiedList[0].update( + keys: MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16), + values: MLXArray.zeros([1, 8, 2, 64], dtype: .bfloat16) + ) + + // originals unchanged + #expect(sub1.offset == originalOffset0) + #expect(sub2.offset == originalOffset1) + let currentState = composite.state + eval(currentState) + #expect(currentState.count == originalState.count) + for (orig, saved) in zip(currentState, originalState) { + #expect(orig.shape == saved.shape) + #expect(allClose(orig, saved).item(Bool.self)) + } + } + + // MARK: - Quantized attention causal masking + // Regression for the finfo.min mistranslation (masked fill was Float.leastNormalMagnitude ≈ 0). + + @Test + func testQuantizedAttentionCausalMaskMatchesFullPrecision() throws { + withRandomState(MLXRandom.RandomState(seed: 0)) { + let (B, nKVHeads, L, D) = (1, 2, 4, 64) + let scale = 1.0 / Float(D).squareRoot() + + // nRepeats 1 = MHA, 2 = GQA (exercises the 5-D reshape + .causal path that silently corrupts). + for nRepeats in [1, 2] { + let nQHeads = nKVHeads * nRepeats + let q = MLXRandom.normal([B, nQHeads, L, D]) + let k = MLXRandom.normal([B, nKVHeads, L, D]) + let v = MLXRandom.normal([B, nKVHeads, L, D]) + + // Reference: full-precision causal attention. + let reference = MLXFast.scaledDotProductAttention( + queries: q, keys: k, values: v, scale: scale, mask: .causal) + + // Path under test: quantized cache + .causal. + let cache = QuantizedKVCache(groupSize: 64, bits: 8) + let (qK, qV) = cache.updateQuantized(keys: k, values: v) + let out = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .causal, + groupSize: cache.groupSize, bits: cache.bits, mode: cache.mode) + + #expect(out.shape == reference.shape) + // 8-bit quant error is << 0.1; the bug diverges by O(1). + let close = allClose(out, reference, rtol: 0.05, atol: 0.1).item(Bool.self) + #expect( + close, + "quantized causal attention diverges from full precision (nRepeats=\(nRepeats))" + ) + } + } + } + + @Test("quantizedScaledDotProductAttention preserves the score dtype") + func preservesScoreDtype() { + withRandomState(MLXRandom.RandomState(seed: 0)) { + let (B, H, L, D) = (1, 2, 4, 64) + let scale = 1.0 / Float(D).squareRoot() + + // f32 passes even with a mis-typed fill; f16/bf16 are exactly what a + // float32 fill silently promotes — so assert the output keeps its dtype. + for dtype in [DType.float16, .bfloat16, .float32] { + let q = MLXRandom.normal([B, H, L, D]).asType(dtype) + let k = MLXRandom.normal([B, H, L, D]).asType(dtype) + let v = MLXRandom.normal([B, H, L, D]).asType(dtype) + + let cache = QuantizedKVCache(groupSize: 64, bits: 8) + let (qK, qV) = cache.updateQuantized(keys: k, values: v) + let out = quantizedScaledDotProductAttention( + queries: q, quantizedKeys: qK, quantizedValues: qV, + scale: scale, mask: .causal, + groupSize: cache.groupSize, bits: cache.bits, mode: cache.mode) + + #expect(out.dtype == dtype, "output promoted to \(out.dtype) for input \(dtype)") + #expect(out.asType(.float32).sum().item(Float.self).isFinite) // no -inf → NaN + } + } + } + + // MARK: - ropeOffset overridability + + /// A `BaseKVCache` subclass reporting a per-row RoPE offset, as a batched cache does. + private final class BatchOffsetProbeCache: BaseKVCache { + override var ropeOffset: RoPEOffset { .batch(MLXArray([10, 20])) } + + override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + (keys, values) + } + } -@Test func testRotatingLogicalViewFloorsAtThePinnedPrefix() throws { - // A pinned entry is never evictable, so `keep` is a floor on the view and not just a - // splice point: a `tail` below it still returns the prefix. The alternative -- honouring - // `tail` exactly -- would hand back a context the ring itself can never present. - let cache = RotatingKVCache(maxSize: 8, keep: 2) - fillOneAtATime(cache, positions: 0 ..< 20) + /// Models read `ropeOffset` through a `KVCache` reference, so a subclass override has to + /// survive that dispatch. When `BaseKVCache` did not declare `ropeOffset`, the extension + /// default was the witness and this resolved to `.scalar(0)`, silently ignoring the subclass. + @Test func testSubclassRopeOffsetOverrideIsHonoredThroughKVCacheReference() { + let cache: any KVCache = BatchOffsetProbeCache() - for tail in 0 ... 2 { - let view = try #require(cache.logicalView(tail: tail)) + guard case .batch(let offsets) = cache.ropeOffset else { + Issue.record( + "subclass ropeOffset override ignored — resolved to the .scalar extension default") + return + } + #expect(offsets.asArray(Int32.self) == [10, 20]) + } + + // MARK: - RotatingKVCache.logicalView + // + // `logicalView(tail:)` is the read-only counterpart to `update(keys:values:)`: it exposes the + // ring's contents in chronological order without writing. Speculative decoding needs it to + // present committed history alongside K/V it has not committed yet. + // + // Nothing in this repo drove a `RotatingKVCache` ring past its wrap before these tests, so the + // rotation in `updateInPlace`, the linearization in `temporalOrder`, and the windowed mask that + // `makeMask` builds over the multi-token presentation were all uncovered. They are the + // foundation the view rests on, so they are pinned here too. + + /// K/V whose every element encodes its own sequence position: keys hold `+p`, values `-p`. + /// Any reordering, duplication, or K/V mix-up changes the numbers. + private func positionedKV( + _ positions: Range, headDim: Int = 2 + ) -> (MLXArray, MLXArray) { + let count = positions.count + let keys = MLXArray( + positions.flatMap { Array(repeating: Float($0), count: headDim) }, + [1, 1, count, headDim]) + let values = MLXArray( + positions.flatMap { Array(repeating: Float(-$0), count: headDim) }, + [1, 1, count, headDim]) + return (keys, values) + } + + /// Recover the sequence positions encoded by `positionedKV` from a `[B, H, S, D]` key array. + private func encodedPositions(_ keys: MLXArray) -> [Int] { + keys[0, 0, 0..., 0].asArray(Float.self).map { Int($0) } + } + + /// Drive `cache` through `count` single-token writes, so the ring actually rotates. + private func fillOneAtATime(_ cache: RotatingKVCache, positions: Range) { + for p in positions { + let (k, v) = positionedKV(p ..< (p + 1)) + _ = cache.update(keys: k, values: v) + } + } + + @Test func testRotatingLogicalViewIsNilBeforeFirstWrite() { + #expect(RotatingKVCache(maxSize: 8, keep: 0).logicalView(tail: 8) == nil) + } + + @Test func testRotatingLogicalViewReturnsChronologicalTailPastWrap() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + + // The ring has wrapped twice; physical order is rotated, chronological order is not. + #expect(cache.offset == 20) + + let full = try #require(cache.logicalView(tail: 8)) + #expect( + encodedPositions(full.0) == Array(12 ..< 20), + "logicalView did not linearize the rotated ring") #expect( - encodedPositions(view.0) == [0, 1], - "tail \(tail) below `keep` dropped the pinned prefix") - #expect(encodedPositions(view.1).map { -$0 } == [0, 1], "values diverged from keys") + encodedPositions(full.1).map { -$0 } == Array(12 ..< 20), "values diverged from keys") + + let short = try #require(cache.logicalView(tail: 3)) + #expect(encodedPositions(short.0) == [17, 18, 19], "a short tail took the wrong end") } - // One past the floor is the first tail that actually selects anything. - let positions = encodedPositions(try #require(cache.logicalView(tail: 3)).0) - #expect(positions.count == 3) - #expect(Array(positions.prefix(2)) == [0, 1], "the prefix moved once the tail cleared it") -} + @Test func testRotatingLogicalViewClampsTailToWhatTheCacheHolds() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 5) -@Test func testRotatingLogicalViewFloorIsBoundedByWhatTheCacheHolds() throws { - // Fewer entries written than `keep` pins: the floor is what exists, not what is reserved. - let cache = RotatingKVCache(maxSize: 8, keep: 4) - fillOneAtATime(cache, positions: 0 ..< 2) + #expect(encodedPositions(try #require(cache.logicalView(tail: 99)).0) == Array(0 ..< 5)) + #expect(encodedPositions(try #require(cache.logicalView(tail: 5)).0) == Array(0 ..< 5)) + #expect(try #require(cache.logicalView(tail: 0)).0.dim(2) == 0) + #expect(try #require(cache.logicalView(tail: -1)).0.dim(2) == 0, "negative tail must clamp") + } - #expect(encodedPositions(try #require(cache.logicalView(tail: 0)).0) == [0, 1]) - #expect(encodedPositions(try #require(cache.logicalView(tail: 9)).0) == [0, 1]) -} + @Test func testRotatingLogicalViewLeavesTheRingUntouched() { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) -/// The property the speculative overlay rests on: for a multi-token write, the presentation the -/// cache *would* return equals `logicalView(tail: maxSize - 1)` followed by the new rows. An -/// adapter can therefore stage beside the ring and hand the model an identical view. -@Test func testRotatingLogicalViewPlusNewRowsEqualsTheWritePresentation() throws { - let window = 8 - let staged = 4 - - let cache = RotatingKVCache(maxSize: window, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) - - // Read the view and the mask *before* the write, exactly as an adapter would. - let view = try #require(cache.logicalView(tail: window - 1)) - let mask = cache.makeMask(n: staged, windowSize: window, returnArray: false) - - let (newKeys, newValues) = positionedKV(20 ..< (20 + staged)) - let presented = cache.update(keys: newKeys, values: newValues) - - let composedKeys = concatenated([view.0, newKeys], axis: 2) - let composedValues = concatenated([view.1, newValues], axis: 2) - - #expect( - encodedPositions(presented.0) == encodedPositions(composedKeys), - "staged presentation diverged from the live write path") - #expect( - allClose(presented.0, composedKeys, rtol: 0, atol: 0).item(Bool.self), - "keys diverged from the live write path") - #expect( - allClose(presented.1, composedValues, rtol: 0, atol: 0).item(Bool.self), - "values diverged from the live write path") - - // The mask the cache built before the write has to span exactly that presentation, or an - // adapter could not delegate mask construction to the live cache. - guard case .array(let maskArray) = mask else { - Issue.record("expected an array mask once offset + n exceeds the window, got \(mask)") - return - } - #expect( - maskArray.dim(-1) == composedKeys.dim(2), - "mask key axis \(maskArray.dim(-1)) != presented length \(composedKeys.dim(2))") - #expect(maskArray.dim(-2) == staged) -} + let beforeState = cache.innerState().map { MLXArray($0.asArray(Float.self), $0.shape) } + let beforeOffset = cache.offset + let beforeMeta = cache.metaState -/// Attention through the rotating cache's own presentation and mask, past a wrap, must equal a -/// reference that never rotated: every position kept in a plain array under an explicit -/// causal-intersect-window mask over absolute positions. -@Test func testRotatingCacheAttentionPastWrapMatchesLogicalOrderReference() { - withRandomState(MLXRandom.RandomState(seed: 0)) { - let window = 8 - let history = 20 - let queries = 4 - let heads = 2 - let headDim = 4 - let scale = 1.0 / Float(headDim).squareRoot() + _ = cache.logicalView(tail: 7) + _ = cache.logicalView(tail: 3) - let allKeys = MLXRandom.normal([1, heads, history + queries, headDim]) - let allValues = MLXRandom.normal([1, heads, history + queries, headDim]) - let q = MLXRandom.normal([1, heads, queries, headDim]) + let afterState = cache.innerState() + #expect(afterState.count == beforeState.count) + for (index, (before, after)) in zip(beforeState, afterState).enumerated() { + #expect(before.shape == after.shape, "innerState[\(index)] was reshaped by a read") + #expect( + allClose(before, after, rtol: 0, atol: 0).item(Bool.self), + "innerState[\(index)] was mutated by a read") + } + #expect(cache.offset == beforeOffset, "logicalView moved the offset") + #expect(cache.metaState == beforeMeta, "logicalView disturbed idx/offset bookkeeping") + } - let cache = RotatingKVCache(maxSize: window, keep: 0) - for p in 0 ..< history { - _ = cache.update( - keys: allKeys[0..., 0..., p ..< (p + 1), 0...], - values: allValues[0..., 0..., p ..< (p + 1), 0...]) + @Test func testRotatingLogicalViewPreservesPinnedPrefix() throws { + // `keep` pins the oldest entries; the write path front-trims *after* them, so a view must + // splice around the prefix rather than take a flat tail. + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< 20) + + let view = try #require(cache.logicalView(tail: 5)) + let positions = encodedPositions(view.0) + #expect(positions.count == 5) + #expect(Array(positions.prefix(2)) == [0, 1], "pinned prefix was evicted by the view") + #expect(positions == [0, 1] + Array(positions.suffix(3))) + #expect(positions.suffix(3).sorted() == Array(positions.suffix(3)), "tail out of order") + } + + @Test func testRotatingLogicalViewFloorsAtThePinnedPrefix() throws { + // A pinned entry is never evictable, so `keep` is a floor on the view and not just a + // splice point: a `tail` below it still returns the prefix. The alternative -- honouring + // `tail` exactly -- would hand back a context the ring itself can never present. + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< 20) + + for tail in 0 ... 2 { + let view = try #require(cache.logicalView(tail: tail)) + #expect( + encodedPositions(view.0) == [0, 1], + "tail \(tail) below `keep` dropped the pinned prefix") + #expect(encodedPositions(view.1).map { -$0 } == [0, 1], "values diverged from keys") } - let mask = cache.makeMask(n: queries, windowSize: window, returnArray: false) - let (cachedKeys, cachedValues) = cache.update( - keys: allKeys[0..., 0..., history ..< (history + queries), 0...], - values: allValues[0..., 0..., history ..< (history + queries), 0...]) - let out = MLXFast.scaledDotProductAttention( - queries: q, keys: cachedKeys, values: cachedValues, scale: scale, mask: mask) - - // Reference: all history retained, masked by absolute position. - let queryPositions = MLXArray(Int32(history) ..< Int32(history + queries))[0..., .newAxis] - let keyPositions = MLXArray(Int32(0) ..< Int32(history + queries))[.newAxis] - let referenceMask = - (queryPositions .>= keyPositions) & (queryPositions .< keyPositions + Int32(window)) - let reference = MLXFast.scaledDotProductAttention( - queries: q, keys: allKeys, values: allValues, scale: scale, mask: .array(referenceMask)) + // One past the floor is the first tail that actually selects anything. + let positions = encodedPositions(try #require(cache.logicalView(tail: 3)).0) + #expect(positions.count == 3) + #expect(Array(positions.prefix(2)) == [0, 1], "the prefix moved once the tail cleared it") + } + + @Test func testRotatingLogicalViewFloorIsBoundedByWhatTheCacheHolds() throws { + // Fewer entries written than `keep` pins: the floor is what exists, not what is reserved. + let cache = RotatingKVCache(maxSize: 8, keep: 4) + fillOneAtATime(cache, positions: 0 ..< 2) + + #expect(encodedPositions(try #require(cache.logicalView(tail: 0)).0) == [0, 1]) + #expect(encodedPositions(try #require(cache.logicalView(tail: 9)).0) == [0, 1]) + } + + /// The property the speculative overlay rests on: for a multi-token write, the presentation the + /// cache *would* return equals `logicalView(tail: maxSize - 1)` followed by the new rows. An + /// adapter can therefore stage beside the ring and hand the model an identical view. + @Test func testRotatingLogicalViewPlusNewRowsEqualsTheWritePresentation() throws { + let window = 8 + let staged = 4 + + let cache = RotatingKVCache(maxSize: window, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + + // Read the view and the mask *before* the write, exactly as an adapter would. + let view = try #require(cache.logicalView(tail: window - 1)) + let mask = cache.makeMask(n: staged, windowSize: window, returnArray: false) + + let (newKeys, newValues) = positionedKV(20 ..< (20 + staged)) + let presented = cache.update(keys: newKeys, values: newValues) - #expect(out.shape == reference.shape) + let composedKeys = concatenated([view.0, newKeys], axis: 2) + let composedValues = concatenated([view.1, newValues], axis: 2) + + #expect( + encodedPositions(presented.0) == encodedPositions(composedKeys), + "staged presentation diverged from the live write path") #expect( - allClose(out, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self), - "post-wrap attention diverged from the logical-order reference") + allClose(presented.0, composedKeys, rtol: 0, atol: 0).item(Bool.self), + "keys diverged from the live write path") + #expect( + allClose(presented.1, composedValues, rtol: 0, atol: 0).item(Bool.self), + "values diverged from the live write path") + + // The mask the cache built before the write has to span exactly that presentation, or an + // adapter could not delegate mask construction to the live cache. + guard case .array(let maskArray) = mask else { + Issue.record("expected an array mask once offset + n exceeds the window, got \(mask)") + return + } + #expect( + maskArray.dim(-1) == composedKeys.dim(2), + "mask key axis \(maskArray.dim(-1)) != presented length \(composedKeys.dim(2))") + #expect(maskArray.dim(-2) == staged) } -} -// MARK: - Variance-normalized KV cache + /// Attention through the rotating cache's own presentation and mask, past a wrap, must equal a + /// reference that never rotated: every position kept in a plain array under an explicit + /// causal-intersect-window mask over absolute positions. + @Test func testRotatingCacheAttentionPastWrapMatchesLogicalOrderReference() { + withRandomState(MLXRandom.RandomState(seed: 0)) { + let window = 8 + let history = 20 + let queries = 4 + let heads = 2 + let headDim = 4 + let scale = 1.0 / Float(headDim).squareRoot() + + let allKeys = MLXRandom.normal([1, heads, history + queries, headDim]) + let allValues = MLXRandom.normal([1, heads, history + queries, headDim]) + let q = MLXRandom.normal([1, heads, queries, headDim]) + + let cache = RotatingKVCache(maxSize: window, keep: 0) + for p in 0 ..< history { + _ = cache.update( + keys: allKeys[0..., 0..., p ..< (p + 1), 0...], + values: allValues[0..., 0..., p ..< (p + 1), 0...]) + } -@Test func testVarianceNormalizedKVCacheStoresCompletedTilesAndTail() throws { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) + let mask = cache.makeMask(n: queries, windowSize: window, returnArray: false) + let (cachedKeys, cachedValues) = cache.update( + keys: allKeys[0..., 0..., history ..< (history + queries), 0...], + values: allValues[0..., 0..., history ..< (history + queries), 0...]) + let out = MLXFast.scaledDotProductAttention( + queries: q, keys: cachedKeys, values: cachedValues, scale: scale, mask: mask) + + // Reference: all history retained, masked by absolute position. + let queryPositions = MLXArray(Int32(history) ..< Int32(history + queries))[ + 0..., .newAxis] + let keyPositions = MLXArray(Int32(0) ..< Int32(history + queries))[.newAxis] + let referenceMask = + (queryPositions .>= keyPositions) & (queryPositions .< keyPositions + Int32(window)) + let reference = MLXFast.scaledDotProductAttention( + queries: q, keys: allKeys, values: allValues, scale: scale, + mask: .array(referenceMask)) - let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) - eval(cachedKeys, cachedValues) + #expect(out.shape == reference.shape) + #expect( + allClose(out, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self), + "post-wrap attention diverged from the logical-order reference") + } + } - #expect(cache.offset == 40) - #expect(cachedKeys.shape == keys.shape) - #expect(cachedValues.shape == values.shape) - #expect(cache.metaState == ["32", "40", "4", "4", "2", "1", "8", "1", "float16", "float16"]) - #expect(cache.state.count == 10) - #expect(relativeRMSError(cachedKeys, keys) < 0.5) - #expect(relativeRMSError(cachedValues, values) < 0.5) -} + // MARK: - Variance-normalized KV cache -@Test func testVarianceNormalizedKVCacheSerializationRoundTrip() throws { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) - let (originalKeys, originalValues) = cache.update(keys: keys, values: values) - eval(originalKeys, originalValues) + @Test func testVarianceNormalizedKVCacheStoresCompletedTilesAndTail() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 40, 32]).asType(.float16) - let url = tempURL() - try savePromptCache(url: url, cache: [cache], metadata: ["kind": "variance-normalized"]) - let (loaded, metadata) = try loadPromptCache(url: url) + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) - #expect(metadata["kind"] == "variance-normalized") - let restored = try #require(loaded[0] as? VarianceNormalizedKVCache) - #expect(restored.metaState == cache.metaState) + #expect(cache.offset == 40) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) + #expect( + cache.metaState == ["32", "40", "4", "4", "2", "1", "8", "1", "float16", "float16"]) + #expect(cache.state.count == 10) + #expect(relativeRMSError(cachedKeys, keys) < 0.5) + #expect(relativeRMSError(cachedValues, values) < 0.5) + } - let moreKeys = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) - let moreValues = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) - let (restoredKeys, restoredValues) = restored.update(keys: moreKeys, values: moreValues) - eval(restoredKeys, restoredValues) + @Test func testVarianceNormalizedKVCacheInnerStateHoldsTheStoredSlabs() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 8 * 32 + 5, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 8 * 32 + 5, 32]).asType(.float16) + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) - #expect(restored.offset == 69) - #expect(restoredKeys.shape == [1, 1, 69, 32]) - #expect(restoredValues.shape == [1, 1, 69, 32]) -} + let stateBytes = cache.state.reduce(0) { $0 + $1.nbytes } + #expect(KVCacheStatus(cache: [cache]).memoryBytes == stateBytes) + #expect(cache.innerState().count < cache.state.count) + } -@Test func testVarianceNormalizedKVCachePreservesDTypeAtExactTileBoundary() throws { - for dtype in [DType.float32, .bfloat16] { + @Test func testVarianceNormalizedKVCacheSerializationRoundTrip() throws { let cache = VarianceNormalizedKVCache( tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let keys = deterministicTensor(shape: [1, 1, 64, 32], salt: 21).asType(dtype) - let values = deterministicTensor(shape: [1, 1, 64, 32], salt: 22).asType(dtype) - _ = cache.update(keys: keys, values: values) - eval(cache.state) + let keys = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 68, 32]).asType(.float16) + let (originalKeys, originalValues) = cache.update(keys: keys, values: values) + eval(originalKeys, originalValues) let url = tempURL() - try savePromptCache(url: url, cache: [cache]) - let (loaded, _) = try loadPromptCache(url: url) + try savePromptCache(url: url, cache: [cache], metadata: ["kind": "variance-normalized"]) + let (loaded, metadata) = try loadPromptCache(url: url) + + #expect(metadata["kind"] == "variance-normalized") let restored = try #require(loaded[0] as? VarianceNormalizedKVCache) - let copied = try #require(cache.copy() as? VarianceNormalizedKVCache) - let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) - let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) - - for candidate in [restored, copied] { - let (materializedKeys, materializedValues) = candidate.update( - keys: emptyKeys, values: emptyValues) - eval(materializedKeys, materializedValues) - #expect(materializedKeys.dtype == dtype) - #expect(materializedValues.dtype == dtype) - } - } -} + #expect(restored.metaState == cache.metaState) -@Test func testVarianceNormalizedKVCacheTrimOnlyReconstructsTheAffectedTile() throws { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) - let (beforeKeys, beforeValues) = cache.update(keys: keys, values: values) - eval(beforeKeys, beforeValues) - - #expect(cache.trim(10) == 10) - let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) - let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) - let (afterKeys, afterValues) = cache.update(keys: emptyKeys, values: emptyValues) - eval(afterKeys, afterValues) - - #expect(cache.offset == 60) - #expect(cache.metaState == ["32", "60", "4", "4", "2", "1", "28", "1", "float16", "float16"]) - #expect(cache.state.count == 10) - #expect(relativeRMSError(afterKeys, beforeKeys[.ellipsis, ..<60, 0...]) < 1e-3) - #expect(relativeRMSError(afterValues, beforeValues[.ellipsis, ..<60, 0...]) < 1e-3) -} + let moreKeys = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) + let moreValues = MLXRandom.normal([1, 1, 1, 32]).asType(.float16) + let (restoredKeys, restoredValues) = restored.update(keys: moreKeys, values: moreValues) + eval(restoredKeys, restoredValues) -@Test func testVarianceNormalizedKVCacheSupportsAsymmetricKeyValueBits() { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + #expect(restored.offset == 69) + #expect(restoredKeys.shape == [1, 1, 69, 32]) + #expect(restoredValues.shape == [1, 1, 69, 32]) + } - let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) - eval(cachedKeys, cachedValues) + @Test func testVarianceNormalizedKVCachePreservesDTypeAtExactTileBoundary() throws { + for dtype in [DType.float32, .bfloat16] { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = deterministicTensor(shape: [1, 1, 64, 32], salt: 21).asType(dtype) + let values = deterministicTensor(shape: [1, 1, 64, 32], salt: 22).asType(dtype) + _ = cache.update(keys: keys, values: values) + eval(cache.state) + + let url = tempURL() + try savePromptCache(url: url, cache: [cache]) + let (loaded, _) = try loadPromptCache(url: url) + let restored = try #require(loaded[0] as? VarianceNormalizedKVCache) + let copied = try #require(cache.copy() as? VarianceNormalizedKVCache) + let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) + let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: dtype) + + for candidate in [restored, copied] { + let (materializedKeys, materializedValues) = candidate.update( + keys: emptyKeys, values: emptyValues) + eval(materializedKeys, materializedValues) + #expect(materializedKeys.dtype == dtype) + #expect(materializedValues.dtype == dtype) + } + } + } - #expect(cache.offset == 32) - #expect(cache.metaState == ["32", "32", "4", "2", "2", "1", "0", "1", "float16", "float16"]) - #expect(cachedKeys.shape == keys.shape) - #expect(cachedValues.shape == values.shape) -} + @Test func testVarianceNormalizedKVCacheTrimOnlyReconstructsTheAffectedTile() throws { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 70, 32]).asType(.float16) + let (beforeKeys, beforeValues) = cache.update(keys: keys, values: values) + eval(beforeKeys, beforeValues) + + #expect(cache.trim(10) == 10) + let emptyKeys = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) + let emptyValues = MLXArray.zeros([1, 1, 0, 32], dtype: .float16) + let (afterKeys, afterValues) = cache.update(keys: emptyKeys, values: emptyValues) + eval(afterKeys, afterValues) + + #expect(cache.offset == 60) + #expect( + cache.metaState == ["32", "60", "4", "4", "2", "1", "28", "1", "float16", "float16"]) + #expect(cache.state.count == 10) + #expect(relativeRMSError(afterKeys, beforeKeys[.ellipsis, ..<60, 0...]) < 1e-3) + #expect(relativeRMSError(afterValues, beforeValues[.ellipsis, ..<60, 0...]) < 1e-3) + } -@Test func testVarianceNormalizedKVCacheSupportsPaperTargetTwoBitKV() { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + @Test func testVarianceNormalizedKVCacheSupportsAsymmetricKeyValueBits() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) - let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) - eval(cachedKeys, cachedValues) + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) - #expect(cache.offset == 32) - #expect(cache.metaState == ["32", "32", "2", "2", "2", "1", "0", "1", "float16", "float16"]) - #expect(cache.state.count == 8) - #expect(cachedKeys.shape == keys.shape) - #expect(cachedValues.shape == values.shape) -} + #expect(cache.offset == 32) + #expect( + cache.metaState == ["32", "32", "4", "2", "2", "1", "0", "1", "float16", "float16"]) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) + } -@Test func testVarianceNormalizedKVCacheMaterializationPreservesWideInputDTypes() { - for dtype in [DType.float32, .bfloat16] { + @Test func testVarianceNormalizedKVCacheSupportsPaperTargetTwoBitKV() { let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let magnitude = MLXArray(Float(100_000), dtype: dtype) - let keys = deterministicTensor(shape: [1, 1, 32, 32], salt: 11).asType(dtype) * magnitude - let values = deterministicTensor(shape: [1, 1, 32, 32], salt: 12).asType(dtype) * magnitude + tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) eval(cachedKeys, cachedValues) - #expect(cachedKeys.dtype == dtype) - #expect(cachedValues.dtype == dtype) - #expect(isFinite(cachedKeys).all().item(Bool.self)) - #expect(isFinite(cachedValues).all().item(Bool.self)) + #expect(cache.offset == 32) + #expect( + cache.metaState == ["32", "32", "2", "2", "2", "1", "0", "1", "float16", "float16"]) + #expect(cache.state.count == 8) + #expect(cachedKeys.shape == keys.shape) + #expect(cachedValues.shape == values.shape) } -} -@Test func testVarianceNormalizedKVCacheQuantizedTileAttentionMatchesMaterializedAttention() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let queries = deterministicTensor(shape: [1, 1, 4, 32], salt: 31) - let keys = deterministicTensor(shape: [1, 1, 36, 32], salt: 32) - let values = deterministicTensor(shape: [1, 1, 36, 32], salt: 33) - let scale = 1 / sqrt(Float(32)) - - let native = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: nativeCache, - scale: scale) - let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: cachedKeys, - values: cachedValues, - cache: nil, - scale: scale) - eval(native, materialized) - - #expect(relativeRMSError(native, materialized) < 1.5e-3) - #expect(nativeCache.offset == 36) - #expect( - nativeCache.metaState == ["32", "36", "4", "4", "2", "1", "4", "1", "float16", "float16"]) -} + @Test func testVarianceNormalizedKVCacheMaterializationPreservesWideInputDTypes() { + for dtype in [DType.float32, .bfloat16] { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let magnitude = MLXArray(Float(100_000), dtype: dtype) + let keys = + deterministicTensor(shape: [1, 1, 32, 32], salt: 11).asType(dtype) * magnitude + let values = + deterministicTensor(shape: [1, 1, 32, 32], salt: 12).asType(dtype) * magnitude + + let (cachedKeys, cachedValues) = cache.update(keys: keys, values: values) + eval(cachedKeys, cachedValues) + + #expect(cachedKeys.dtype == dtype) + #expect(cachedValues.dtype == dtype) + #expect(isFinite(cachedKeys).all().item(Bool.self)) + #expect(isFinite(cachedValues).all().item(Bool.self)) + } + } -@Test func testVarianceNormalizedKVCacheQuantizedTileAttentionSupportsGQA() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let queries = deterministicTensor(shape: [1, 4, 3, 32], salt: 34) - let keys = deterministicTensor(shape: [1, 2, 33, 32], salt: 35) - let values = deterministicTensor(shape: [1, 2, 33, 32], salt: 36) - let scale = 1 / sqrt(Float(32)) - - let native = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: nativeCache, - scale: scale) - let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: cachedKeys, - values: cachedValues, - cache: nil, - scale: scale) - eval(native, materialized) - - #expect(relativeRMSError(native, materialized) < 1.5e-3) - #expect(native.shape == [1, 4, 3, 32]) - #expect( - nativeCache.metaState == ["32", "33", "4", "4", "2", "1", "1", "1", "float16", "float16"]) -} + @Test func testVarianceNormalizedKVCacheQuantizedTileAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 1, 4, 32], salt: 31) + let keys = deterministicTensor(shape: [1, 1, 36, 32], salt: 32) + let values = deterministicTensor(shape: [1, 1, 36, 32], salt: 33) + let scale = 1 / sqrt(Float(32)) -@Test func testVarianceNormalizedKVCacheStackedTileAttentionMatchesMaterializedAttention() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let queries = deterministicTensor(shape: [1, 1, 2, 32], salt: 1) - // Thirty-three tiles exercises one immutable slab plus one pending tile. - let keys = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 2) - let values = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 3) - let scale = 1 / sqrt(Float(32)) - - let native = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: nativeCache, - scale: scale) - let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: cachedKeys, - values: cachedValues, - cache: nil, - scale: scale) - eval(native, materialized) - - #expect(relativeRMSError(native, materialized) < 1e-3) - #expect( - nativeCache.metaState == [ - "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", - ]) -} + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) -@Test func testVarianceNormalizedKVCacheStackedTileAttentionSupportsGQA() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let queries = deterministicTensor(shape: [1, 4, 2, 32], salt: 4) - let keys = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 5) - let values = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 6) - let scale = 1 / sqrt(Float(32)) - - let native = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: nativeCache, - scale: scale) - let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: cachedKeys, - values: cachedValues, - cache: nil, - scale: scale) - eval(native, materialized) - - #expect(relativeRMSError(native, materialized) < 1e-3) - #expect(native.shape == [1, 4, 2, 32]) - #expect( - nativeCache.metaState == [ - "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", - ]) -} + #expect(relativeRMSError(native, materialized) < 1.5e-3) + #expect(nativeCache.offset == 36) + #expect( + nativeCache.metaState == [ + "32", "36", "4", "4", "2", "1", "4", "1", "float16", "float16", + ]) + } -@Test func testApplyAttentionMaskSuppressesBoolMaskedLogits() { - let scores = MLXArray([Float(-10), Float(-20), Float(-30)]).reshaped(1, 1, 1, 3) - let mask = MLXArray([true, false, false]).reshaped(1, 1, 1, 3) + @Test func testVarianceNormalizedKVCacheQuantizedTileAttentionSupportsGQA() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 4, 3, 32], salt: 34) + let keys = deterministicTensor(shape: [1, 2, 33, 32], salt: 35) + let values = deterministicTensor(shape: [1, 2, 33, 32], salt: 36) + let scale = 1 / sqrt(Float(32)) - let weights = softmax(applyAttentionMask(scores: scores, mask: .array(mask)), axis: -1) - eval(weights) + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) - let values = weights.asArray(Float.self) - #expect(values[0] > 0.999) - #expect(values[1] < 1e-6) - #expect(values[2] < 1e-6) -} + #expect(relativeRMSError(native, materialized) < 1.5e-3) + #expect(native.shape == [1, 4, 3, 32]) + #expect( + nativeCache.metaState == [ + "32", "33", "4", "4", "2", "1", "1", "1", "float16", "float16", + ]) + } -@Test func testVarianceNormalizedKVCacheMaskedAttentionMatchesMaterializedAttention() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let queries = MLXArray.ones([1, 1, 4, 32], dtype: .float16) * -1 - let keys = MLXArray.ones([1, 1, 36, 32], dtype: .float16) - let values = concatenated( - [ - MLXArray.zeros([1, 1, 32, 32], dtype: .float16), - MLXArray.ones([1, 1, 4, 32], dtype: .float16) * 10, - ], axis: 2) - let scale = 1 / sqrt(Float(32)) - let mask = MLXFast.ScaledDotProductAttentionMaskMode.causal - - let native = attentionWithCacheUpdate( - queries: queries, - keys: keys, - values: values, - cache: nativeCache, - scale: scale, - mask: mask) - let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: cachedKeys, - values: cachedValues, - cache: nil, - scale: scale, - mask: mask) - eval(native, materialized) - - #expect(relativeRMSError(native, materialized) < 1e-3) -} + @Test func testVarianceNormalizedKVCacheStackedTileAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 1, 2, 32], salt: 1) + // Thirty-three tiles exercises one immutable slab plus one pending tile. + let keys = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 2) + let values = deterministicTensor(shape: [1, 1, 1_056, 32], salt: 3) + let scale = 1 / sqrt(Float(32)) -@Test func testVarianceNormalizedKVCacheAttentionTracksFP16OverLongDecode() { - let fp16Cache = KVCacheSimple() - let varianceNormalizedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let randomState = MLXRandom.RandomState(seed: 7) - let scale = 1 / sqrt(Float(32)) - var totalError: Float = 0 - var maxError: Float = 0 - let tokenCount = 96 - - for _ in 0 ..< tokenCount { - let queries = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) - let keys = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) - let values = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) - - let fp16 = attentionWithCacheUpdate( + let native = attentionWithCacheUpdate( queries: queries, keys: keys, values: values, - cache: fp16Cache, + cache: nativeCache, scale: scale) - let compressed = attentionWithCacheUpdate( + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1e-3) + #expect( + nativeCache.metaState == [ + "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", + ]) + } + + @Test func testVarianceNormalizedKVCacheStackedTileAttentionSupportsGQA() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = deterministicTensor(shape: [1, 4, 2, 32], salt: 4) + let keys = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 5) + let values = deterministicTensor(shape: [1, 2, 1_056, 32], salt: 6) + let scale = 1 / sqrt(Float(32)) + + let native = attentionWithCacheUpdate( queries: queries, keys: keys, values: values, - cache: varianceNormalizedCache, + cache: nativeCache, + scale: scale) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, scale: scale) - eval(fp16, compressed) + eval(native, materialized) - let error = relativeRMSError(compressed, fp16) - totalError += error - maxError = max(maxError, error) + #expect(relativeRMSError(native, materialized) < 1e-3) + #expect(native.shape == [1, 4, 2, 32]) + #expect( + nativeCache.metaState == [ + "32", "1056", "4", "4", "2", "33", "0", "1", "float16", "float16", + ]) } - #expect( - varianceNormalizedCache.metaState == [ - "32", "96", "4", "4", "2", "3", "0", "1", "float16", "float16", - ]) - #expect(totalError / Float(tokenCount) < 0.15) - #expect(maxError < 0.45) -} + @Test func testApplyAttentionMaskSuppressesBoolMaskedLogits() { + let scores = MLXArray([Float(-10), Float(-20), Float(-30)]).reshaped(1, 1, 1, 3) + let mask = MLXArray([true, false, false]).reshaped(1, 1, 1, 3) -@Test func testVarianceNormalizedKVCacheMemoryAccountingIncludesScaleOverhead() { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + let weights = softmax(applyAttentionMask(scores: scores, mask: .array(mask)), axis: -1) + eval(weights) - _ = cache.update(keys: keys, values: values) - eval(cache.state) + let values = weights.asArray(Float.self) + #expect(values[0] > 0.999) + #expect(values[1] < 1e-6) + #expect(values[2] < 1e-6) + } - let state = cache.state - let compressedBytes = state.reduce(0) { $0 + $1.nbytes } - let quantizedPayloadBytes = stride(from: 0, to: state.count, by: 8).reduce(0) { - $0 + state[$1].nbytes + state[$1 + 4].nbytes + @Test func testVarianceNormalizedKVCacheMaskedAttentionMatchesMaterializedAttention() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let queries = MLXArray.ones([1, 1, 4, 32], dtype: .float16) * -1 + let keys = MLXArray.ones([1, 1, 36, 32], dtype: .float16) + let values = concatenated( + [ + MLXArray.zeros([1, 1, 32, 32], dtype: .float16), + MLXArray.ones([1, 1, 4, 32], dtype: .float16) * 10, + ], axis: 2) + let scale = 1 / sqrt(Float(32)) + let mask = MLXFast.ScaledDotProductAttentionMaskMode.causal + + let native = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: nativeCache, + scale: scale, + mask: mask) + let (cachedKeys, cachedValues) = materializedCache.update(keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: cachedKeys, + values: cachedValues, + cache: nil, + scale: scale, + mask: mask) + eval(native, materialized) + + #expect(relativeRMSError(native, materialized) < 1e-3) } - let fp16Bytes = keys.nbytes + values.nbytes - #expect(cache.metaState == ["32", "64", "4", "4", "2", "2", "0", "1", "float16", "float16"]) - #expect(cache.compactStorageByteCount == compressedBytes) - #expect(compressedBytes > quantizedPayloadBytes) - #expect(compressedBytes < fp16Bytes) -} + @Test func testVarianceNormalizedKVCacheAttentionTracksFP16OverLongDecode() { + let fp16Cache = KVCacheSimple() + let varianceNormalizedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let randomState = MLXRandom.RandomState(seed: 7) + let scale = 1 / sqrt(Float(32)) + var totalError: Float = 0 + var maxError: Float = 0 + let tokenCount = 96 + + for _ in 0 ..< tokenCount { + let queries = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + let keys = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + let values = MLXRandom.normal([1, 1, 1, 32], key: randomState).asType(.float16) + + let fp16 = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: fp16Cache, + scale: scale) + let compressed = attentionWithCacheUpdate( + queries: queries, + keys: keys, + values: values, + cache: varianceNormalizedCache, + scale: scale) + eval(fp16, compressed) + + let error = relativeRMSError(compressed, fp16) + totalError += error + maxError = max(maxError, error) + } -@Test func testVarianceNormalizedKVCacheCoalescesTieredSlabs() { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 1) - let tokenCount = 32 * 32 * 8 - let queries = deterministicTensor(shape: [1, 1, 1, 32], salt: 41) - let keys = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 42) - let values = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 43) - - let output = cache.updateAndAttend( - queries: queries, - keys: keys, - values: values, - scale: 1 / sqrt(Float(32))) - eval(output) - - #expect(cache.offset == tokenCount) - #expect(cache.attentionPartitionCount == 1) - #expect(cache.compactStorageByteCount == cache.state.reduce(0) { $0 + $1.nbytes }) -} + #expect( + varianceNormalizedCache.metaState == [ + "32", "96", "4", "4", "2", "3", "0", "1", "float16", "float16", + ]) + #expect(totalError / Float(tokenCount) < 0.15) + #expect(maxError < 0.45) + } -@Test func testVarianceNormalizedKVCacheBoundsPartitionsBeforeLargeSlabBoundary() { - let nativeCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) - let materializedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) - let tokenCount = 31 * 32 - let queries = deterministicTensor(shape: [1, 4, 1, 32], salt: 51) - let keys = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 52) - let values = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 53) - let scale = 1 / sqrt(Float(32)) - - let native = nativeCache.updateAndAttend( - queries: queries, keys: keys, values: values, scale: scale) - let (materializedKeys, materializedValues) = materializedCache.update( - keys: keys, values: values) - let materialized = attentionWithCacheUpdate( - queries: queries, - keys: materializedKeys, - values: materializedValues, - cache: nil, - scale: scale) - eval(native, materialized) - - // Four-tile base slabs cap the old 31-dispatch cliff at ten partitions while preserving - // the quantized attention result. The next tile still coalesces to one 32-tile slab. - #expect(nativeCache.attentionPartitionCount == 10) - #expect(relativeRMSError(native, materialized) < 1.5e-3) -} + @Test func testVarianceNormalizedKVCacheMemoryAccountingIncludesScaleOverhead() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) -@Test func testVarianceNormalizedKVCacheHeadBatchesMatchIndependentHeads() { - let keys = deterministicTensor(shape: [1, 8, 128, 32], salt: 54) - let values = deterministicTensor(shape: [1, 8, 128, 32], salt: 55) - let batchedCache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) - let (batchedKeys, batchedValues) = batchedCache.update(keys: keys, values: values) + _ = cache.update(keys: keys, values: values) + eval(cache.state) + + let state = cache.state + let compressedBytes = state.reduce(0) { $0 + $1.nbytes } + let quantizedPayloadBytes = stride(from: 0, to: state.count, by: 8).reduce(0) { + $0 + state[$1].nbytes + state[$1 + 4].nbytes + } + let fp16Bytes = keys.nbytes + values.nbytes - var independentKeys: [MLXArray] = [] - var independentValues: [MLXArray] = [] - for head in 0 ..< 8 { + #expect( + cache.metaState == ["32", "64", "4", "4", "2", "2", "0", "1", "float16", "float16"]) + #expect(cache.compactStorageByteCount == compressedBytes) + #expect(compressedBytes > quantizedPayloadBytes) + #expect(compressedBytes < fp16Bytes) + } + + @Test func testVarianceNormalizedKVCacheCoalescesTieredSlabs() { let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 4, sinkhornIterations: 1) + let tokenCount = 32 * 32 * 8 + let queries = deterministicTensor(shape: [1, 1, 1, 32], salt: 41) + let keys = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 42) + let values = deterministicTensor(shape: [1, 1, tokenCount, 32], salt: 43) + + let output = cache.updateAndAttend( + queries: queries, + keys: keys, + values: values, + scale: 1 / sqrt(Float(32))) + eval(output) + + #expect(cache.offset == tokenCount) + #expect(cache.attentionPartitionCount == 1) + #expect(cache.compactStorageByteCount == cache.state.reduce(0) { $0 + $1.nbytes }) + } + + @Test func testVarianceNormalizedKVCacheBoundsPartitionsBeforeLargeSlabBoundary() { + let nativeCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let materializedCache = VarianceNormalizedKVCache( tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) - let (headKeys, headValues) = cache.update( - keys: keys[0..., head ..< head + 1, 0..., 0...], - values: values[0..., head ..< head + 1, 0..., 0...]) - independentKeys.append(headKeys) - independentValues.append(headValues) + let tokenCount = 31 * 32 + let queries = deterministicTensor(shape: [1, 4, 1, 32], salt: 51) + let keys = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 52) + let values = deterministicTensor(shape: [1, 2, tokenCount, 32], salt: 53) + let scale = 1 / sqrt(Float(32)) + + let native = nativeCache.updateAndAttend( + queries: queries, keys: keys, values: values, scale: scale) + let (materializedKeys, materializedValues) = materializedCache.update( + keys: keys, values: values) + let materialized = attentionWithCacheUpdate( + queries: queries, + keys: materializedKeys, + values: materializedValues, + cache: nil, + scale: scale) + eval(native, materialized) + + // Four-tile base slabs cap the old 31-dispatch cliff at ten partitions while preserving + // the quantized attention result. The next tile still coalesces to one 32-tile slab. + #expect(nativeCache.attentionPartitionCount == 10) + #expect(relativeRMSError(native, materialized) < 1.5e-3) } - let referenceKeys = concatenated(independentKeys, axis: 1) - let referenceValues = concatenated(independentValues, axis: 1) - eval(batchedKeys, batchedValues, referenceKeys, referenceValues) + @Test func testVarianceNormalizedKVCacheHeadBatchesMatchIndependentHeads() { + let keys = deterministicTensor(shape: [1, 8, 128, 32], salt: 54) + let values = deterministicTensor(shape: [1, 8, 128, 32], salt: 55) + let batchedCache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let (batchedKeys, batchedValues) = batchedCache.update(keys: keys, values: values) + + var independentKeys: [MLXArray] = [] + var independentValues: [MLXArray] = [] + for head in 0 ..< 8 { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 4, valueBits: 2, sinkhornIterations: 2) + let (headKeys, headValues) = cache.update( + keys: keys[0..., head ..< head + 1, 0..., 0...], + values: values[0..., head ..< head + 1, 0..., 0...]) + independentKeys.append(headKeys) + independentValues.append(headValues) + } - #expect(relativeRMSError(batchedKeys, referenceKeys) < 1e-6) - #expect(relativeRMSError(batchedValues, referenceValues) < 1e-6) -} + let referenceKeys = concatenated(independentKeys, axis: 1) + let referenceValues = concatenated(independentValues, axis: 1) + eval(batchedKeys, batchedValues, referenceKeys, referenceValues) -@Test func testVarianceNormalizedKVCacheTwoBitMemoryAccountingIsPaperRelevant() { - let cache = VarianceNormalizedKVCache( - tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) - let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + #expect(relativeRMSError(batchedKeys, referenceKeys) < 1e-6) + #expect(relativeRMSError(batchedValues, referenceValues) < 1e-6) + } - _ = cache.update(keys: keys, values: values) - eval(cache.state) + @Test func testVarianceNormalizedKVCacheTwoBitMemoryAccountingIsPaperRelevant() { + let cache = VarianceNormalizedKVCache( + tileSize: 32, keyBits: 2, valueBits: 2, sinkhornIterations: 2) + let keys = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 64, 32]).asType(.float16) - let compressedBytes = cache.state.reduce(0) { $0 + $1.nbytes } - let fp16Bytes = keys.nbytes + values.nbytes + _ = cache.update(keys: keys, values: values) + eval(cache.state) - #expect(cache.metaState == ["32", "64", "2", "2", "2", "2", "0", "1", "float16", "float16"]) - #expect(compressedBytes < fp16Bytes) -} + let compressedBytes = cache.state.reduce(0) { $0 + $1.nbytes } + let fp16Bytes = keys.nbytes + values.nbytes -@Test func testMaybeQuantizeKVCacheCanUseVarianceNormalizedStrategy() throws { - let simple = KVCacheSimple() - let keys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) - _ = simple.update(keys: keys, values: values) - - var cache: [KVCache] = [simple] - let configuration = try KVCacheConfiguration( - strategy: .varianceNormalized( - .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), - compatibility: .allowPartial) - _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) - - let converted = cache[0] as? VarianceNormalizedKVCache - #expect(converted != nil) - #expect(converted?.offset == 33) - #expect( - converted?.metaState == ["32", "33", "4", "4", "4", "1", "1", "1", "float16", "float16"]) -} + #expect( + cache.metaState == ["32", "64", "2", "2", "2", "2", "0", "1", "float16", "float16"]) + #expect(compressedBytes < fp16Bytes) + } -@Test func testMaybeQuantizeKVCacheDefersVarianceNormalizedStrategyUntilThreshold() throws { - let simple = KVCacheSimple() - let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) - let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) - _ = simple.update(keys: keys, values: values) + @Test func testMaybeQuantizeKVCacheCanUseVarianceNormalizedStrategy() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + let converted = cache[0] as? VarianceNormalizedKVCache + #expect(converted != nil) + #expect(converted?.offset == 33) + #expect( + converted?.metaState == [ + "32", "33", "4", "4", "4", "1", "1", "1", "float16", "float16", + ]) + } - var cache: [KVCache] = [simple] - let configuration = try KVCacheConfiguration( - strategy: .varianceNormalized( - .init( - keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4, - compressionStart: 64)), - compatibility: .allowPartial) - _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + @Test func testMaybeQuantizeKVCacheDefersVarianceNormalizedStrategyUntilThreshold() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + let values = MLXRandom.normal([1, 1, 32, 32]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init( + keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4, + compressionStart: 64)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is KVCacheSimple) + + let moreKeys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + let moreValues = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) + _ = cache[0].update(keys: moreKeys, values: moreValues) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is VarianceNormalizedKVCache) + #expect(cache[0].offset == 65) + } - #expect(cache[0] is KVCacheSimple) + @Test func testMaybeQuantizeKVCacheSkipsUnsupportedVarianceNormalizedDimensions() throws { + let simple = KVCacheSimple() + let keys = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) + let values = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) + _ = simple.update(keys: keys, values: values) + + var cache: [KVCache] = [simple] + let configuration = try KVCacheConfiguration( + strategy: .varianceNormalized( + .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), + compatibility: .allowPartial) + _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + + #expect(cache[0] is KVCacheSimple) + #expect(cache[0].offset == 33) + #expect( + !supportsVarianceNormalizedKVCache( + keyHeadDim: 96, valueHeadDim: 96, tileSize: 32)) + } - let moreKeys = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) - let moreValues = MLXRandom.normal([1, 1, 33, 32]).asType(.float16) - _ = cache[0].update(keys: moreKeys, values: moreValues) - _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) + @Test func testLegacyVarianceNormalizedSchemeResolvesToTypedConfiguration() throws { + let parameters = GenerateParameters(quantizedKVStart: 8, kvScheme: "varn4v2t32") + let resolved = try #require(try parameters.resolvedKVCacheConfiguration()) + #expect(resolved.strategy.identifier == KVCacheStrategyIdentifier.varianceNormalized) + guard case .varianceNormalized(let varn) = resolved.strategy.storage else { + Issue.record("Expected a variance-normalized strategy") + return + } + #expect(varn.keyBits == 4) + #expect(varn.valueBits == 2) + #expect(varn.tileSize == 32) + #expect(varn.sinkhornIterations == 8) + #expect(varn.compressionStart == 8) + } - #expect(cache[0] is VarianceNormalizedKVCache) - #expect(cache[0].offset == 65) -} + // MARK: - RotatingKVCache wrap-aware trim + // + // Trimming a wrapped ring used to silently corrupt it (the ring invariants cannot + // express a hole in the timeline). A wrapped trim now linearizes the ring to temporal + // order and cuts the newest rows: consistent and clamped, though not exact -- rows the + // rewound writes overwrote at the old edge of the window cannot come back, which is why + // `isTrimmable` stays false past the window for the exact-rewind machinery. Every + // consumer of the buffer (writes, masks, state) now bounds live rows by `idx` instead + // of assuming the logical `offset` still equals the fill. + + @Test func testRotatingTrimAfterWrapCutsNewestAndKeepsChronology() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) // wrapped ring holding 12 ..< 20 + + let trimmed = cache.trim(3) // rewind 17, 18, 19 + + #expect(trimmed == 3) + #expect(cache.offset == 17) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 17), "trim did not cut the newest rows") + #expect( + encodedPositions(view.1).map { -$0 } == Array(12 ..< 17), "values diverged from keys") + } -@Test func testMaybeQuantizeKVCacheSkipsUnsupportedVarianceNormalizedDimensions() throws { - let simple = KVCacheSimple() - let keys = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) - let values = MLXRandom.normal([1, 1, 33, 24]).asType(.float16) - _ = simple.update(keys: keys, values: values) - - var cache: [KVCache] = [simple] - let configuration = try KVCacheConfiguration( - strategy: .varianceNormalized( - .init(keyBits: 4, valueBits: 4, tileSize: 32, sinkhornIterations: 4)), - compatibility: .allowPartial) - _ = try applyKVCacheConfiguration(cache: &cache, configuration: configuration) - - #expect(cache[0] is KVCacheSimple) - #expect(cache[0].offset == 33) - #expect( - !supportsVarianceNormalizedKVCache( - keyHeadDim: 96, valueHeadDim: 96, tileSize: 32)) -} + @Test func testRotatingTrimAfterWrapClampsToNonPinnedSpan() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< 13) // pinned [0, 1], ring holds 7 ..< 13 -@Test func testLegacyVarianceNormalizedSchemeResolvesToTypedConfiguration() throws { - let parameters = GenerateParameters(quantizedKVStart: 8, kvScheme: "varn4v2t32") - let resolved = try #require(try parameters.resolvedKVCacheConfiguration()) - #expect(resolved.strategy.identifier == KVCacheStrategyIdentifier.varianceNormalized) - guard case .varianceNormalized(let varn) = resolved.strategy.storage else { - Issue.record("Expected a variance-normalized strategy") - return - } - #expect(varn.keyBits == 4) - #expect(varn.valueBits == 2) - #expect(varn.tileSize == 32) - #expect(varn.sinkhornIterations == 8) - #expect(varn.compressionStart == 8) -} + let trimmed = cache.trim(100) -// MARK: - RotatingKVCache wrap-aware trim -// -// Trimming a wrapped ring used to silently corrupt it (the ring invariants cannot -// express a hole in the timeline). A wrapped trim now linearizes the ring to temporal -// order and cuts the newest rows: consistent and clamped, though not exact -- rows the -// rewound writes overwrote at the old edge of the window cannot come back, which is why -// `isTrimmable` stays false past the window for the exact-rewind machinery. Every -// consumer of the buffer (writes, masks, state) now bounds live rows by `idx` instead -// of assuming the logical `offset` still equals the fill. - -@Test func testRotatingTrimAfterWrapCutsNewestAndKeepsChronology() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) // wrapped ring holding 12 ..< 20 - - let trimmed = cache.trim(3) // rewind 17, 18, 19 - - #expect(trimmed == 3) - #expect(cache.offset == 17) - let view = try #require(cache.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(12 ..< 17), "trim did not cut the newest rows") - #expect(encodedPositions(view.1).map { -$0 } == Array(12 ..< 17), "values diverged from keys") -} + #expect(trimmed == 6, "the pinned prefix must bound the cut") + #expect(cache.offset == 7) + let view = try #require(cache.logicalView(tail: 8)) + #expect( + encodedPositions(view.0) == [0, 1], "the pinned prefix must survive a maximal trim") + } -@Test func testRotatingTrimAfterWrapClampsToNonPinnedSpan() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 2) - fillOneAtATime(cache, positions: 0 ..< 13) // pinned [0, 1], ring holds 7 ..< 13 + @Test func testRotatingSingleTokenRegrowthAfterWrapTrimPresentsOnlyLiveRows() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // holds 12 ..< 17 + + // The buffer regrows from 5 rows; the presentation must never include the + // freshly allocated (dead) rows. + let (k, v) = positionedKV(17 ..< 18) + let presented = cache.update(keys: k, values: v) + #expect(encodedPositions(presented.0) == Array(12 ..< 18)) + #expect(cache.offset == 18) + + // Refill through the rotation boundary and verify chronology survives re-wrapping. + fillOneAtATime(cache, positions: 18 ..< 25) + #expect(cache.offset == 25) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(17 ..< 25)) + } - let trimmed = cache.trim(100) + @Test func testRotatingMultiTokenWriteAfterWrapTrimStaysChronological() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // holds 12 ..< 17 - #expect(trimmed == 6, "the pinned prefix must bound the cut") - #expect(cache.offset == 7) - let view = try #require(cache.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == [0, 1], "the pinned prefix must survive a maximal trim") -} + // The speculative verify shape: a multi-token write straight after a rewind. + let (k, v) = positionedKV(17 ..< 21) + let presented = cache.update(keys: k, values: v) + #expect(encodedPositions(presented.0) == Array(12 ..< 21)) + #expect(cache.offset == 21) -@Test func testRotatingSingleTokenRegrowthAfterWrapTrimPresentsOnlyLiveRows() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) - cache.trim(3) // holds 12 ..< 17 - - // The buffer regrows from 5 rows; the presentation must never include the - // freshly allocated (dead) rows. - let (k, v) = positionedKV(17 ..< 18) - let presented = cache.update(keys: k, values: v) - #expect(encodedPositions(presented.0) == Array(12 ..< 18)) - #expect(cache.offset == 18) - - // Refill through the rotation boundary and verify chronology survives re-wrapping. - fillOneAtATime(cache, positions: 18 ..< 25) - #expect(cache.offset == 25) - let view = try #require(cache.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(17 ..< 25)) -} + fillOneAtATime(cache, positions: 21 ..< 24) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(16 ..< 24)) + } -@Test func testRotatingMultiTokenWriteAfterWrapTrimStaysChronological() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) - cache.trim(3) // holds 12 ..< 17 + @Test func testRotatingRepeatedTrimAfterWrapTakesTemporalPath() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) - // The speculative verify shape: a multi-token write straight after a rewind. - let (k, v) = positionedKV(17 ..< 21) - let presented = cache.update(keys: k, values: v) - #expect(encodedPositions(presented.0) == Array(12 ..< 21)) - #expect(cache.offset == 21) + #expect(cache.trim(2) == 2) // ring path: holds 12 ..< 18 + #expect(cache.trim(2) == 2) // temporal path: holds 12 ..< 16 - fillOneAtATime(cache, positions: 21 ..< 24) - let view = try #require(cache.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(16 ..< 24)) -} + #expect(cache.offset == 16) + let view = try #require(cache.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 16)) + } -@Test func testRotatingRepeatedTrimAfterWrapTakesTemporalPath() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) + @Test func testRotatingWrapTrimSurvivesCopyAndMetaStateRoundTrip() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) - #expect(cache.trim(2) == 2) // ring path: holds 12 ..< 18 - #expect(cache.trim(2) == 2) // temporal path: holds 12 ..< 16 + let copied = try #require(cache.copy() as? RotatingKVCache) + #expect(copied.trim(3) == 3) + let view = try #require(copied.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 17)) + #expect(cache.offset == 20, "trimming the copy must not touch the original") + } - #expect(cache.offset == 16) - let view = try #require(cache.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(12 ..< 16)) -} + @Test func testRotatingLegacyMetaStateDerivesRingLayout() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) -@Test func testRotatingWrapTrimSurvivesCopyAndMetaStateRoundTrip() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) + // A cache saved before the wrapped flag existed has 6 metaState values; the + // ring layout must be derived, not assumed away. + let legacyMetaState = Array(cache.metaState.dropLast()) + #expect(legacyMetaState.count == 6) - let copied = try #require(cache.copy() as? RotatingKVCache) - #expect(copied.trim(3) == 3) - let view = try #require(copied.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(12 ..< 17)) - #expect(cache.offset == 20, "trimming the copy must not touch the original") -} + let restored = RotatingKVCache(maxSize: 8, keep: 0) + restored.state = cache.state.map { $0[.ellipsis] } + restored.metaState = legacyMetaState -@Test func testRotatingLegacyMetaStateDerivesRingLayout() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 20), "legacy restore lost the ring layout") + #expect(restored.trim(3) == 3) + let trimmedView = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(trimmedView.0) == Array(12 ..< 17)) + } - // A cache saved before the wrapped flag existed has 6 metaState values; the - // ring layout must be derived, not assumed away. - let legacyMetaState = Array(cache.metaState.dropLast()) - #expect(legacyMetaState.count == 6) + @Test(arguments: [5, 6, 7]) + func testRotatingRestoredTrimAtRingBoundary(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 16) - let restored = RotatingKVCache(maxSize: 8, keep: 0) - restored.state = cache.state.map { $0[.ellipsis] } - restored.metaState = legacyMetaState + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) - let view = try #require(restored.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(12 ..< 20), "legacy restore lost the ring layout") - #expect(restored.trim(3) == 3) - let trimmedView = try #require(restored.logicalView(tail: 8)) - #expect(encodedPositions(trimmedView.0) == Array(12 ..< 17)) -} + #expect(restored.trim(3) == 3) + #expect(restored.offset == 13) + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(8 ..< 13)) + #expect(encodedPositions(view.1) == Array(8 ..< 13).map { -$0 }) + #expect(restored.state.allSatisfy { $0.dim(2) == 5 }) + } -@Test(arguments: [5, 6, 7]) -func testRotatingRestoredTrimAtRingBoundary(metadataCount: Int) throws { - let source = RotatingKVCache(maxSize: 8) - fillOneAtATime(source, positions: 0 ..< 16) - - let restored = RotatingKVCache(maxSize: 8) - restored.state = source.state.map { $0[.ellipsis] } - restored.metaState = Array(source.metaState.prefix(metadataCount)) - - #expect(restored.trim(3) == 3) - #expect(restored.offset == 13) - let view = try #require(restored.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(8 ..< 13)) - #expect(encodedPositions(view.1) == Array(8 ..< 13).map { -$0 }) - #expect(restored.state.allSatisfy { $0.dim(2) == 5 }) -} + @Test(arguments: [5, 6, 7]) + func testRotatingRestoredTrimKeepsKeysAndValuesAligned(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 20) -@Test(arguments: [5, 6, 7]) -func testRotatingRestoredTrimKeepsKeysAndValuesAligned(metadataCount: Int) throws { - let source = RotatingKVCache(maxSize: 8) - fillOneAtATime(source, positions: 0 ..< 20) - - let restored = RotatingKVCache(maxSize: 8) - restored.state = source.state.map { $0[.ellipsis] } - restored.metaState = Array(source.metaState.prefix(metadataCount)) - - // The shortened key buffer ends before the old write index. Its new shape - // must not change how the value buffer is ordered during the same trim. - #expect(restored.trim(5) == 5) - #expect(restored.offset == 15) - let view = try #require(restored.logicalView(tail: 8)) - #expect(encodedPositions(view.0) == Array(12 ..< 15)) - #expect(encodedPositions(view.1) == Array(12 ..< 15).map { -$0 }) -} + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) -private func expectRotatingContents( - _ cache: RotatingKVCache, _ positions: [Int], - sourceLocation: SourceLocation = #_sourceLocation -) throws { - let view = try #require(cache.logicalView(tail: Int.max), sourceLocation: sourceLocation) - #expect(view.0.dim(2) == positions.count, sourceLocation: sourceLocation) - #expect(view.1.dim(2) == positions.count, sourceLocation: sourceLocation) - #expect( - cache.state.allSatisfy { $0.dim(2) == positions.count }, sourceLocation: sourceLocation) - // Empty MLX arrays need no host readback. - if !positions.isEmpty { - #expect(encodedPositions(view.0) == positions, sourceLocation: sourceLocation) - #expect(encodedPositions(view.1) == positions.map { -$0 }, sourceLocation: sourceLocation) + // The shortened key buffer ends before the old write index. Its new shape + // must not change how the value buffer is ordered during the same trim. + #expect(restored.trim(5) == 5) + #expect(restored.offset == 15) + let view = try #require(restored.logicalView(tail: 8)) + #expect(encodedPositions(view.0) == Array(12 ..< 15)) + #expect(encodedPositions(view.1) == Array(12 ..< 15).map { -$0 }) } -} - -@Test(arguments: [5, 6, 7], [false, true]) -func testRotatingRestorationAcceptsEitherSetterOrder( - metadataCount: Int, metadataFirst: Bool -) throws { - for count in [3, 8, 9, 16, 20] { - for prefill in [false, true] { - let source = RotatingKVCache(maxSize: 8, step: 4) - if prefill { - let (k, v) = positionedKV(0 ..< count) - _ = source.update(keys: k, values: v) - } else { - fillOneAtATime(source, positions: 0 ..< count) - } - let metadata = Array(source.metaState.prefix(metadataCount)) - let arrays = source.state.map { $0[.ellipsis] } - // The saved capacity must replace the constructor's capacity before inference. - let restored = RotatingKVCache(maxSize: 1) - if metadataFirst { - restored.metaState = metadata - restored.state = arrays - } else { - restored.state = arrays - restored.metaState = metadata - } - let start = prefill ? 0 : max(0, count - 8) - try expectRotatingContents(restored, Array(start ..< count)) - #expect(restored.trim(2) == 2) - #expect(restored.offset == count - 2) - try expectRotatingContents(restored, Array(start ..< (count - 2))) + private func expectRotatingContents( + _ cache: RotatingKVCache, _ positions: [Int], + sourceLocation: SourceLocation = #_sourceLocation + ) throws { + let view = try #require(cache.logicalView(tail: Int.max), sourceLocation: sourceLocation) + #expect(view.0.dim(2) == positions.count, sourceLocation: sourceLocation) + #expect(view.1.dim(2) == positions.count, sourceLocation: sourceLocation) + #expect( + cache.state.allSatisfy { $0.dim(2) == positions.count }, sourceLocation: sourceLocation) + // Empty MLX arrays need no host readback. + if !positions.isEmpty { + #expect(encodedPositions(view.0) == positions, sourceLocation: sourceLocation) + #expect( + encodedPositions(view.1) == positions.map { -$0 }, sourceLocation: sourceLocation) } } -} -@Test(arguments: [5, 6, 7], [false, true]) -func testRotatingRestoredShortChronologicalBufferCanGrow( - metadataCount: Int, metadataFirst: Bool -) throws { - let source = RotatingKVCache(maxSize: 8) - fillOneAtATime(source, positions: 0 ..< 20) - // Legacy updateConcat could leave maxSize - 1 chronological rows when given - // an empty append. idx < maxSize && offset > idx cannot identify its layout. - let empty = positionedKV(20 ..< 20) - _ = source.update(keys: empty.0, values: empty.1) - try expectRotatingContents(source, Array(13 ..< 20)) - - let restored = RotatingKVCache(maxSize: 8) - let metadata = Array(source.metaState.prefix(metadataCount)) - let arrays = source.state.map { $0[.ellipsis] } - if metadataFirst { - restored.metaState = metadata - restored.state = arrays - } else { - restored.state = arrays - restored.metaState = metadata - } - #expect(restored.metaState.last == "false") - fillOneAtATime(restored, positions: 20 ..< 21) - try expectRotatingContents(restored, Array(13 ..< 21)) - #expect(restored.trim(3) == 3) - try expectRotatingContents(restored, Array(13 ..< 18)) -} + @Test(arguments: [5, 6, 7], [false, true]) + func testRotatingRestorationAcceptsEitherSetterOrder( + metadataCount: Int, metadataFirst: Bool + ) throws { + for count in [3, 8, 9, 16, 20] { + for prefill in [false, true] { + let source = RotatingKVCache(maxSize: 8, step: 4) + if prefill { + let (k, v) = positionedKV(0 ..< count) + _ = source.update(keys: k, values: v) + } else { + fillOneAtATime(source, positions: 0 ..< count) + } + let metadata = Array(source.metaState.prefix(metadataCount)) + let arrays = source.state.map { $0[.ellipsis] } + // The saved capacity must replace the constructor's capacity before inference. + let restored = RotatingKVCache(maxSize: 1) + if metadataFirst { + restored.metaState = metadata + restored.state = arrays + } else { + restored.state = arrays + restored.metaState = metadata + } + + let start = prefill ? 0 : max(0, count - 8) + try expectRotatingContents(restored, Array(start ..< count)) + #expect(restored.trim(2) == 2) + #expect(restored.offset == count - 2) + try expectRotatingContents(restored, Array(start ..< (count - 2))) + } + } + } -@Test(arguments: [5, 6, 7], [13, 14, 20]) -func testRotatingRestoredTrimPreservesPinnedPrefix(metadataCount: Int, count: Int) throws { - let source = RotatingKVCache(maxSize: 8, keep: 2) - fillOneAtATime(source, positions: 0 ..< count) + @Test(arguments: [5, 6, 7], [false, true]) + func testRotatingRestoredShortChronologicalBufferCanGrow( + metadataCount: Int, metadataFirst: Bool + ) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 20) + // Legacy updateConcat could leave maxSize - 1 chronological rows when given + // an empty append. idx < maxSize && offset > idx cannot identify its layout. + let empty = positionedKV(20 ..< 20) + _ = source.update(keys: empty.0, values: empty.1) + try expectRotatingContents(source, Array(13 ..< 20)) - for firstTrim in [3, 100] { let restored = RotatingKVCache(maxSize: 8) - restored.state = source.state.map { $0[.ellipsis] } - restored.metaState = Array(source.metaState.prefix(metadataCount)) - let removed = min(firstTrim, 6) - #expect(restored.trim(firstTrim) == removed) - try expectRotatingContents( - restored, [0, 1] + Array((count - 6) ..< (count - removed))) - // The second trim operates on temporal storage, even if the first used a ring. - #expect(restored.trim(100) == 6 - removed) - #expect(restored.trim(1) == 0) - #expect(restored.offset == count - 6) - try expectRotatingContents(restored, [0, 1]) - - let next = restored.offset - fillOneAtATime(restored, positions: next ..< (next + 8)) - try expectRotatingContents(restored, [0, 1] + Array((next + 2) ..< (next + 8))) - } - try expectRotatingContents(source, [0, 1] + Array((count - 6) ..< count)) -} + let metadata = Array(source.metaState.prefix(metadataCount)) + let arrays = source.state.map { $0[.ellipsis] } + if metadataFirst { + restored.metaState = metadata + restored.state = arrays + } else { + restored.state = arrays + restored.metaState = metadata + } + #expect(restored.metaState.last == "false") + fillOneAtATime(restored, positions: 20 ..< 21) + try expectRotatingContents(restored, Array(13 ..< 21)) + #expect(restored.trim(3) == 3) + try expectRotatingContents(restored, Array(13 ..< 18)) + } -@Test(arguments: [1, 2, 5, 8]) -func testRotatingTrimBeforeEvictionCanRewindThroughPrefix(count: Int) throws { - let cache = RotatingKVCache(maxSize: 8, keep: 2) - fillOneAtATime(cache, positions: 0 ..< count) - let metadata = cache.metaState - #expect(cache.trim(0) == 0) - #expect(cache.trim(-1) == 0) - #expect(cache.metaState == metadata) - #expect(cache.trim(100) == count) - #expect(cache.offset == 0) - try expectRotatingContents(cache, []) - fillOneAtATime(cache, positions: 0 ..< 3) - try expectRotatingContents(cache, [0, 1, 2]) -} + @Test(arguments: [5, 6, 7], [13, 14, 20]) + func testRotatingRestoredTrimPreservesPinnedPrefix(metadataCount: Int, count: Int) throws { + let source = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(source, positions: 0 ..< count) + + for firstTrim in [3, 100] { + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + let removed = min(firstTrim, 6) + #expect(restored.trim(firstTrim) == removed) + try expectRotatingContents( + restored, [0, 1] + Array((count - 6) ..< (count - removed))) + // The second trim operates on temporal storage, even if the first used a ring. + #expect(restored.trim(100) == 6 - removed) + #expect(restored.trim(1) == 0) + #expect(restored.offset == count - 6) + try expectRotatingContents(restored, [0, 1]) + + let next = restored.offset + fillOneAtATime(restored, positions: next ..< (next + 8)) + try expectRotatingContents(restored, [0, 1] + Array((next + 2) ..< (next + 8))) + } + try expectRotatingContents(source, [0, 1] + Array((count - 6) ..< count)) + } -@Test(arguments: [0, 2], [1, 3]) -func testRotatingTrimOversizedPrefillThenResume(keep: Int, nextCount: Int) throws { - let cache = RotatingKVCache(maxSize: 8, keep: keep, step: 4) - fillOneAtATime(cache, positions: 0 ..< 20) - let (k, v) = positionedKV(20 ..< 23) - _ = cache.update(keys: k, values: v) // ten chronological rows - #expect(cache.trim(5) == 5) - #expect(cache.offset == 18) - let prefix = Array(0 ..< keep) - try expectRotatingContents(cache, prefix + Array((13 + keep) ..< 18)) - - let mask = cache.makeMask(n: nextCount, windowSize: 8, returnArray: true) - let next = positionedKV(18 ..< (18 + nextCount)) - let presented = cache.update(keys: next.0, values: next.1) - let expected = prefix + Array((13 + keep) ..< (18 + nextCount)) - #expect(encodedPositions(presented.0) == expected) - #expect(encodedPositions(presented.1) == expected.map { -$0 }) - if case .array(let array) = mask { - #expect(array.dim(-1) == presented.0.dim(2)) - } - fillOneAtATime(cache, positions: (18 + nextCount) ..< 30) - try expectRotatingContents(cache, prefix + Array((22 + keep) ..< 30)) -} + @Test(arguments: [1, 2, 5, 8]) + func testRotatingTrimBeforeEvictionCanRewindThroughPrefix(count: Int) throws { + let cache = RotatingKVCache(maxSize: 8, keep: 2) + fillOneAtATime(cache, positions: 0 ..< count) + let metadata = cache.metaState + #expect(cache.trim(0) == 0) + #expect(cache.trim(-1) == 0) + #expect(cache.metaState == metadata) + #expect(cache.trim(100) == count) + #expect(cache.offset == 0) + try expectRotatingContents(cache, []) + fillOneAtATime(cache, positions: 0 ..< 3) + try expectRotatingContents(cache, [0, 1, 2]) + } -@Test(arguments: [5, 6, 7]) -func testRotatingTrimSurvivesPromptCachePersistenceAndCopy(metadataCount: Int) throws { - let source = RotatingKVCache(maxSize: 8) - fillOneAtATime(source, positions: 0 ..< 16) - let url = tempURL() - let legacyURL = tempURL() - let roundTripURL = tempURL() - defer { - for file in [url, legacyURL, roundTripURL] { - try? FileManager.default.removeItem(at: file) + @Test(arguments: [0, 2], [1, 3]) + func testRotatingTrimOversizedPrefillThenResume(keep: Int, nextCount: Int) throws { + let cache = RotatingKVCache(maxSize: 8, keep: keep, step: 4) + fillOneAtATime(cache, positions: 0 ..< 20) + let (k, v) = positionedKV(20 ..< 23) + _ = cache.update(keys: k, values: v) // ten chronological rows + #expect(cache.trim(5) == 5) + #expect(cache.offset == 18) + let prefix = Array(0 ..< keep) + try expectRotatingContents(cache, prefix + Array((13 + keep) ..< 18)) + + let mask = cache.makeMask(n: nextCount, windowSize: 8, returnArray: true) + let next = positionedKV(18 ..< (18 + nextCount)) + let presented = cache.update(keys: next.0, values: next.1) + let expected = prefix + Array((13 + keep) ..< (18 + nextCount)) + #expect(encodedPositions(presented.0) == expected) + #expect(encodedPositions(presented.1) == expected.map { -$0 }) + if case .array(let array) = mask { + #expect(array.dim(-1) == presented.0.dim(2)) } + fillOneAtATime(cache, positions: (18 + nextCount) ..< 30) + try expectRotatingContents(cache, prefix + Array((22 + keep) ..< 30)) } - try savePromptCache(url: url, cache: [source]) - // Exercise the real file loader with each historical metadata format. - let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) - var metadata = savedMetadata - for index in metadataCount ..< 7 { - metadata.removeValue(forKey: "0.0.\(index)") - } - // MLX loads lazily, so keep the source files intact while their arrays are live. - try save(arrays: arrays, metadata: metadata, url: legacyURL) - let (loaded, _) = try loadPromptCache(url: legacyURL) - let restored = try #require(loaded.first as? RotatingKVCache) - #expect(restored.trim(3) == 3) - try expectRotatingContents(restored, Array(8 ..< 13)) - - // A post-trim cache has more history than live rows; its explicit false flag - // must survive serialization instead of being inferred from those counters. - try savePromptCache(url: roundTripURL, cache: [restored]) - let (reloaded, _) = try loadPromptCache(url: roundTripURL) - let roundTrip = try #require(reloaded.first as? RotatingKVCache) - let copied = try #require(roundTrip.copy() as? RotatingKVCache) - #expect(copied.trim(2) == 2) - fillOneAtATime(copied, positions: 11 ..< 20) - try expectRotatingContents(copied, Array(12 ..< 20)) - try expectRotatingContents(roundTrip, Array(8 ..< 13)) - try expectRotatingContents(restored, Array(8 ..< 13)) - try expectRotatingContents(source, Array(8 ..< 16)) - #expect(roundTrip.offset == 13) - #expect(source.offset == 16) -} -@Test(arguments: [5, 6, 7], [1, 3]) -func testRotatingRestoredTrimAttentionMatchesSurvivingContext( - metadataCount: Int, queryCount: Int -) throws { - let keys = deterministicTensor(shape: [1, 2, 20, 4], salt: 1).asType(.float32) - let values = deterministicTensor(shape: [1, 2, 20, 4], salt: 2).asType(.float32) - let queries = deterministicTensor(shape: [1, 2, queryCount, 4], salt: 3).asType(.float32) - let source = RotatingKVCache(maxSize: 8) - for p in 0 ..< 20 { - _ = source.update( - keys: keys[.ellipsis, p ..< (p + 1), 0...], - values: values[.ellipsis, p ..< (p + 1), 0...]) - } - let restored = RotatingKVCache(maxSize: 8) - restored.state = source.state.map { $0[.ellipsis] } - restored.metaState = Array(source.metaState.prefix(metadataCount)) - #expect(restored.trim(5) == 5) // only positions 12, 13, 14 survive - let mask = restored.makeMask(n: queryCount, windowSize: 4, returnArray: false) - let (cachedKeys, cachedValues) = restored.update( - keys: keys[.ellipsis, 15 ..< (15 + queryCount), 0...], - values: values[.ellipsis, 15 ..< (15 + queryCount), 0...]) - let output = MLXFast.scaledDotProductAttention( - queries: queries, keys: cachedKeys, values: cachedValues, scale: 0.5, mask: mask) - let reference = MLXFast.scaledDotProductAttention( - queries: queries, - keys: keys[.ellipsis, 12 ..< (15 + queryCount), 0...], - values: values[.ellipsis, 12 ..< (15 + queryCount), 0...], - scale: 0.5, - mask: .array(createCausalMask(n: queryCount, offset: 3, windowSize: 4))) - #expect(allClose(output, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) -} + @Test(arguments: [5, 6, 7]) + func testRotatingTrimSurvivesPromptCachePersistenceAndCopy(metadataCount: Int) throws { + let source = RotatingKVCache(maxSize: 8) + fillOneAtATime(source, positions: 0 ..< 16) + let url = tempURL() + let legacyURL = tempURL() + let roundTripURL = tempURL() + defer { + for file in [url, legacyURL, roundTripURL] { + try? FileManager.default.removeItem(at: file) + } + } + try savePromptCache(url: url, cache: [source]) + // Exercise the real file loader with each historical metadata format. + let (arrays, savedMetadata) = try loadArraysAndMetadata(url: url) + var metadata = savedMetadata + for index in metadataCount ..< 7 { + metadata.removeValue(forKey: "0.0.\(index)") + } + // MLX loads lazily, so keep the source files intact while their arrays are live. + try save(arrays: arrays, metadata: metadata, url: legacyURL) + let (loaded, _) = try loadPromptCache(url: legacyURL) + let restored = try #require(loaded.first as? RotatingKVCache) + #expect(restored.trim(3) == 3) + try expectRotatingContents(restored, Array(8 ..< 13)) + + // A post-trim cache has more history than live rows; its explicit false flag + // must survive serialization instead of being inferred from those counters. + try savePromptCache(url: roundTripURL, cache: [restored]) + let (reloaded, _) = try loadPromptCache(url: roundTripURL) + let roundTrip = try #require(reloaded.first as? RotatingKVCache) + let copied = try #require(roundTrip.copy() as? RotatingKVCache) + #expect(copied.trim(2) == 2) + fillOneAtATime(copied, positions: 11 ..< 20) + try expectRotatingContents(copied, Array(12 ..< 20)) + try expectRotatingContents(roundTrip, Array(8 ..< 13)) + try expectRotatingContents(restored, Array(8 ..< 13)) + try expectRotatingContents(source, Array(8 ..< 16)) + #expect(roundTrip.offset == 13) + #expect(source.offset == 16) + } + + @Test(arguments: [5, 6, 7], [1, 3]) + func testRotatingRestoredTrimAttentionMatchesSurvivingContext( + metadataCount: Int, queryCount: Int + ) throws { + let keys = deterministicTensor(shape: [1, 2, 20, 4], salt: 1).asType(.float32) + let values = deterministicTensor(shape: [1, 2, 20, 4], salt: 2).asType(.float32) + let queries = deterministicTensor(shape: [1, 2, queryCount, 4], salt: 3).asType(.float32) + let source = RotatingKVCache(maxSize: 8) + for p in 0 ..< 20 { + _ = source.update( + keys: keys[.ellipsis, p ..< (p + 1), 0...], + values: values[.ellipsis, p ..< (p + 1), 0...]) + } + let restored = RotatingKVCache(maxSize: 8) + restored.state = source.state.map { $0[.ellipsis] } + restored.metaState = Array(source.metaState.prefix(metadataCount)) + #expect(restored.trim(5) == 5) // only positions 12, 13, 14 survive + let mask = restored.makeMask(n: queryCount, windowSize: 4, returnArray: false) + let (cachedKeys, cachedValues) = restored.update( + keys: keys[.ellipsis, 15 ..< (15 + queryCount), 0...], + values: values[.ellipsis, 15 ..< (15 + queryCount), 0...]) + let output = MLXFast.scaledDotProductAttention( + queries: queries, keys: cachedKeys, values: cachedValues, scale: 0.5, mask: mask) + let reference = MLXFast.scaledDotProductAttention( + queries: queries, + keys: keys[.ellipsis, 12 ..< (15 + queryCount), 0...], + values: values[.ellipsis, 12 ..< (15 + queryCount), 0...], + scale: 0.5, + mask: .array(createCausalMask(n: queryCount, offset: 3, windowSize: 4))) + #expect(allClose(output, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) + } -@Test func testRotatingSingleTokenMaskAfterWrapTrimMatchesEquivalentFreshCache() throws { - // After a wrapped trim the cache holds 5 live rows; the sliding-window mask for - // the next single-token step must match a fresh cache holding the same rows. - let windowSize = 4 + @Test func testRotatingSingleTokenMaskAfterWrapTrimMatchesEquivalentFreshCache() throws { + // After a wrapped trim the cache holds 5 live rows; the sliding-window mask for + // the next single-token step must match a fresh cache holding the same rows. + let windowSize = 4 - let trimmedCache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(trimmedCache, positions: 0 ..< 20) - trimmedCache.trim(3) // 5 live rows + let trimmedCache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(trimmedCache, positions: 0 ..< 20) + trimmedCache.trim(3) // 5 live rows - let freshCache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(freshCache, positions: 0 ..< 5) // 5 live rows + let freshCache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(freshCache, positions: 0 ..< 5) // 5 live rows - let trimmedMask = trimmedCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) - let freshMask = freshCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) + let trimmedMask = trimmedCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) + let freshMask = freshCache.makeMask(n: 1, windowSize: windowSize, returnArray: false) - guard case .array(let trimmedArray) = trimmedMask, case .array(let freshArray) = freshMask - else { - Issue.record("expected array masks, got \(trimmedMask) and \(freshMask)") - return + guard case .array(let trimmedArray) = trimmedMask, case .array(let freshArray) = freshMask + else { + Issue.record("expected array masks, got \(trimmedMask) and \(freshMask)") + return + } + #expect(trimmedArray.shape == freshArray.shape) + #expect((trimmedArray .== freshArray).all().item(Bool.self)) } - #expect(trimmedArray.shape == freshArray.shape) - #expect((trimmedArray .== freshArray).all().item(Bool.self)) -} -@Test func testRotatingMultiTokenMaskWidthMatchesPresentationAfterWrapTrim() throws { - let cache = RotatingKVCache(maxSize: 8, keep: 0) - fillOneAtATime(cache, positions: 0 ..< 20) - cache.trim(3) // 5 live rows + @Test func testRotatingMultiTokenMaskWidthMatchesPresentationAfterWrapTrim() throws { + let cache = RotatingKVCache(maxSize: 8, keep: 0) + fillOneAtATime(cache, positions: 0 ..< 20) + cache.trim(3) // 5 live rows - // Models build the mask before the write; its key width must equal the rows the - // write presents, or attention shapes diverge. - let mask = cache.makeMask(n: 3, windowSize: 4, returnArray: true) - let (k, v) = positionedKV(17 ..< 20) - let presented = cache.update(keys: k, values: v) + // Models build the mask before the write; its key width must equal the rows the + // write presents, or attention shapes diverge. + let mask = cache.makeMask(n: 3, windowSize: 4, returnArray: true) + let (k, v) = positionedKV(17 ..< 20) + let presented = cache.update(keys: k, values: v) - guard case .array(let maskArray) = mask else { - Issue.record("expected an array mask, got \(mask)") - return + guard case .array(let maskArray) = mask else { + Issue.record("expected an array mask, got \(mask)") + return + } + #expect(maskArray.dim(-1) == presented.0.dim(2)) } - #expect(maskArray.dim(-1) == presented.0.dim(2)) } diff --git a/Tests/MLXLMTests/LabeledImageGeneratorTests.swift b/Tests/MLXLMTests/LabeledImageGeneratorTests.swift new file mode 100644 index 0000000000..af2c2b83cb --- /dev/null +++ b/Tests/MLXLMTests/LabeledImageGeneratorTests.swift @@ -0,0 +1,100 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLMCommon +import MLXVLM +import Testing + +@Suite("Labeled image generators") +struct LabeledImageGeneratorTests { + + private func message(_ labels: [String?]) -> Chat.Message { + .user( + "which one is blue?", + images: labels.map { .url(URL(fileURLWithPath: "/tmp/example.png"), label: $0) }) + } + + private func parts(_ raw: MLXLMCommon.Message) throws -> [[String: String]] { + try #require(raw["content"] as? [[String: String]]) + } + + private var imagesThenText: [[String: String]] { + [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "[B]"], + ["type": "image"], + ["type": "text", "text": "which one is blue?"], + ] + } + + @Test("Qwen2VL names each image before itself") + func qwen2VL() throws { + let raw = Qwen2VLMessageGenerator().generate(message: message(["A", "B"])) + let content = try parts(raw) + #expect(content == imagesThenText) + #expect(raw["role"] as? String == "user") + } + + @Test("Qwen3VL names each image before itself") + func qwen3VL() throws { + let content = try parts(Qwen3VLMessageGenerator().generate(message: message(["A", "B"]))) + #expect(content == imagesThenText) + } + + @Test("Gemma4 names each image before itself") + func gemma4() throws { + let content = try parts(Gemma4MessageGenerator().generate(message: message(["A", "B"]))) + #expect(content == imagesThenText) + } + + @Test("Mistral3 names each image before itself") + func mistral3() throws { + let content = try parts(Mistral3MessageGenerator().generate(message: message(["A", "B"]))) + #expect(content == imagesThenText) + } + + @Test("FastVLM names each image before itself") + func fastVLM() throws { + let content = try parts(FastVLMMessageGenerator().generate(message: message(["A", "B"]))) + #expect(content == imagesThenText) + } + + @Test("GlmOcr keeps its text first and still names each image") + func glmOcr() throws { + let content = try parts(GlmOcrMessageGenerator().generate(message: message(["A", "B"]))) + #expect( + content == [ + ["type": "text", "text": "which one is blue?"], + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "[B]"], + ["type": "image"], + ]) + } + + @Test("Gemma4 keeps a system message as a plain string") + func gemma4SystemMessage() throws { + let raw = Gemma4MessageGenerator().generate(message: .system("You are useful.")) + #expect(raw["content"] as? String == "You are useful.") + } + + @Test("An unlabeled message keeps the array it had before labels") + func unlabeledMessagesAreUnchanged() throws { + let unlabeled = message([nil, nil]) + let qwen = try parts(Qwen2VLMessageGenerator().generate(message: unlabeled)) + #expect( + qwen == [ + ["type": "image"], + ["type": "image"], + ["type": "text", "text": "which one is blue?"], + ]) + let glm = try parts(GlmOcrMessageGenerator().generate(message: unlabeled)) + #expect( + glm == [ + ["type": "text", "text": "which one is blue?"], + ["type": "image"], + ["type": "image"], + ]) + } +} diff --git a/Tests/MLXLMTests/MatmulPrecision.swift b/Tests/MLXLMTests/MatmulPrecision.swift new file mode 100644 index 0000000000..1e63305554 --- /dev/null +++ b/Tests/MLXLMTests/MatmulPrecision.swift @@ -0,0 +1,91 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import XCTest + +/// The precision MLX uses for float32 matmuls on the machine running the tests, measured once. +/// +/// On hardware with neural accelerators (M5 and later) MLX runs float32 matmuls as TF32 unless +/// `MLX_ENABLE_TF32=0`. That costs about three decimal digits, which matters for every test +/// that computes one prompt two ways — whole against windowed, cold against warm — and asserts +/// the logits agree. Those differences are ~1e-6 with IEEE float32 and ~3e-3 with TF32, so a +/// fixed bound sized for one machine fails on the other for reasons that have nothing to do +/// with the code under test. +/// +/// Pinning `MLX_ENABLE_TF32=0` for the test process would remove the variable, but it would +/// also stop testing the path that ships by default on current hardware, and it is read once +/// per process at MLX's first use, so it would have to be set before any test runs. Measure +/// instead. +enum MatmulPrecision { + + /// True when float32 matmuls lose precision (TF32 on the neural accelerators). + /// + /// Measured rather than inferred from the device or `MLX_ENABLE_TF32`: the same float32 + /// inputs are multiplied on the GPU and on the CPU, which always uses IEEE float32. The + /// gap is ~1e-7 relative when the GPU does the same, and ~1e-3 when it uses TF32 — three + /// orders of magnitude apart, so the threshold between them needs no tuning. + static let isReducedFloat32: Bool = relativeMatmulError > 1e-5 + + /// Relative difference between a GPU and a CPU float32 matmul of the same inputs. + static let relativeMatmulError: Float = { + let a = withRandomState(MLXRandom.RandomState(seed: 0)) { MLXRandom.normal([64, 512]) } + let b = withRandomState(MLXRandom.RandomState(seed: 1)) { MLXRandom.normal([512, 64]) } + let gpu = matmul(a, b, stream: .gpu) + let cpu = matmul(a, b, stream: .cpu) + return abs(gpu - cpu).max().item(Float.self) / abs(cpu).max().item(Float.self) + }() + + /// A tolerance sized for IEEE float32, and the value to use instead when this machine + /// computes float32 matmuls as TF32. + /// + /// Two explicit numbers rather than one scale factor: what reduced precision costs a + /// comparison depends on how many matmuls feed it and whether the difference is relative + /// or absolute, so each call site states what it measured rather than inheriting a guess. + static func tolerance(float32: Double, reduced: Double) -> Double { + isReducedFloat32 ? reduced : float32 + } + + static func tolerance(float32: Float, reduced: Float) -> Float { + isReducedFloat32 ? reduced : float32 + } + + /// The bound for asserting that two executions of the same prompt produce the same logits. + /// + /// `1e-3` is what these tests have always used, and it stays exactly that on hardware + /// that computes float32 matmuls in float32. TF32 raises the noise of splitting a forward + /// to a few times 1e-3; 2e-2 clears that with margin while staying far below the O(1) + /// shift a real positioning error produces. + static let splitTolerance: Float = tolerance(float32: 1e-3, reduced: 2e-2) +} + +final class MatmulPrecisionTests: XCTestCase { + + /// The probe decides how strict every tolerance derived from it is, so check it on every + /// machine rather than only on the rare one that sets `MLX_ENABLE_TF32=0`. + /// + /// What can be asserted anywhere is that the measurement is unambiguous: float32 lands near + /// 1e-7 and TF32 near 1e-3, so a reading between 1e-5 and 1e-4 means the two regimes are no + /// longer cleanly separated and the threshold needs a human. On pre-M5 hardware — CI, and + /// most developer machines — this is the assertion that catches a probe that has started + /// reporting reduced precision and quietly loosening every bound. + /// + /// There is no converse check that accelerator hardware *must* measure as reduced: nothing + /// exposes "this GPU has neural accelerators", and MLX is free to change when it uses them. + func testPrecisionProbeLandsClearlyInOneRegime() { + let error = MatmulPrecision.relativeMatmulError + XCTAssertTrue( + error < 1e-5 || error > 1e-4, + """ + float32 matmul relative error \(error) falls between the float32 (~1e-7) and \ + TF32 (~1e-3) regimes; MatmulPrecision.isReducedFloat32 can no longer tell them apart + """) + + // When TF32 is disabled the answer is known, whatever the hardware. + if ProcessInfo.processInfo.environment["MLX_ENABLE_TF32"] == "0" { + XCTAssertFalse( + MatmulPrecision.isReducedFloat32, + "float32 matmuls measured as reduced precision despite MLX_ENABLE_TF32=0") + } + } +} diff --git a/Tests/MLXLMTests/MessageContentPartsTests.swift b/Tests/MLXLMTests/MessageContentPartsTests.swift new file mode 100644 index 0000000000..72a46b6d2c --- /dev/null +++ b/Tests/MLXLMTests/MessageContentPartsTests.swift @@ -0,0 +1,176 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLMCommon +import Testing + +@Suite("Message content parts") +struct MessageContentPartsTests { + + let generator = DefaultMessageGenerator() + + private func image(_ label: String?) -> UserInput.Image { + .url(URL(fileURLWithPath: "/tmp/example.png"), label: label) + } + + @Test("No images gives one text part") + func noImages() { + let message = Chat.Message.user("hello") + #expect( + generator.contentParts(for: message, layout: .imagesThenVideosThenText) + == [["type": "text", "text": "hello"]]) + } + + @Test("A name holding a marker character is left out, and its image stays") + func markerNameIsLeftOut() { + let message = Chat.Message.user("hello", images: [image("<|image|>"), image("B")]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "image"], + ["type": "text", "text": "[B]"], + ["type": "image"], + ["type": "text", "text": "hello"], + ]) + } + + @Test("Every marker character costs the name, on any layout") + func everyMarkerCharacterIsRefused() { + for label in ["", "a|b", "[a", "a]"] { + let message = Chat.Message.user("hello", images: [image(label)]) + for layout: MessageContentLayout in [ + .imagesThenVideosThenText, .imagesThenText, .textThenImages, + ] { + let parts = generator.contentParts(for: message, layout: layout) + #expect( + !parts.contains(["type": "text", "text": "[\(label)]"]), + "\(label) reached the parts on \(layout)") + #expect(parts.contains(["type": "image"]), "\(label) lost its image") + } + } + } + + @Test("Unlabeled images give the array generators produced before labels") + func unlabeledImagesAreUnchanged() { + let message = Chat.Message.user("hello", images: [image(nil), image(nil)]) + #expect( + generator.contentParts(for: message, layout: .imagesThenVideosThenText) + == [ + ["type": "image"], + ["type": "image"], + ["type": "text", "text": "hello"], + ]) + #expect( + generator.contentParts(for: message, layout: .textThenImages) + == [ + ["type": "text", "text": "hello"], + ["type": "image"], + ["type": "image"], + ]) + } + + @Test("One labeled image is named immediately before itself") + func oneLabeledImage() { + let message = Chat.Message.user("hello", images: [image("A")]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "hello"], + ]) + } + + @Test("Each label sits directly before its own image, with nothing between") + func threeLabeledImages() { + let message = Chat.Message.user( + "which one is blue?", images: [image("A"), image("B"), image("C")]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "[B]"], + ["type": "image"], + ["type": "text", "text": "[C]"], + ["type": "image"], + ["type": "text", "text": "which one is blue?"], + ]) + } + + @Test("No part carries a separator, in any layout") + func noSeparatorAnywhere() { + let message = Chat.Message.user( + "which one is blue?", images: [image("A"), image("B")]) + for layout: MessageContentLayout in [ + .imagesThenVideosThenText, .imagesThenText, .textThenImages, + ] { + for part in generator.contentParts(for: message, layout: layout) { + let text = part["text"] ?? "" + #expect(!text.contains("\u{2060}"), "word joiner in \(text) for \(layout)") + #expect(!text.contains("\u{200B}"), "zero width space in \(text) for \(layout)") + #expect(!text.contains("\n"), "newline in \(text) for \(layout)") + } + } + } + + @Test("An unlabeled image among labeled ones is a bare image part") + func mixedLabels() { + let message = Chat.Message.user("hello", images: [image("A"), image(nil)]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "image"], + ["type": "text", "text": "hello"], + ]) + } + + @Test("Text first puts the prose ahead of the labeled images") + func textFirstLayout() { + let message = Chat.Message.user("hello", images: [image("A"), image("B")]) + #expect( + generator.contentParts(for: message, layout: .textThenImages) + == [ + ["type": "text", "text": "hello"], + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "[B]"], + ["type": "image"], + ]) + } + + @Test("Video parts appear only in the layout that emits them") + func videoParts() { + let message = Chat.Message.user( + "hello", images: [image("A")], + videos: [.url(URL(fileURLWithPath: "/tmp/example.mov"))]) + #expect( + generator.contentParts(for: message, layout: .imagesThenVideosThenText) + == [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "video"], + ["type": "text", "text": "hello"], + ]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "text", "text": "[A]"], + ["type": "image"], + ["type": "text", "text": "hello"], + ]) + } + + @Test("Empty text still gives a text part") + func emptyTextStillGivesAPart() { + let message = Chat.Message.user("", images: [image(nil)]) + #expect( + generator.contentParts(for: message, layout: .imagesThenText) + == [ + ["type": "image"], + ["type": "text", "text": ""], + ]) + } +} diff --git a/Tests/MLXLMTests/ModelCheckpointTests.swift b/Tests/MLXLMTests/ModelCheckpointTests.swift new file mode 100644 index 0000000000..1665f8bf11 --- /dev/null +++ b/Tests/MLXLMTests/ModelCheckpointTests.swift @@ -0,0 +1,89 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN +import Testing + +@testable import MLXLMCommon + +struct ModelCheckpointTests { + @Test + func legacySanitizationErrorsReachCheckpointPreparation() { + final class FailingModel: Module, BaseLanguageModel { + enum Failure: Error { case sanitization } + + func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + throw Failure.sanitization + } + } + let model: any BaseLanguageModel = FailingModel() + #expect(throws: FailingModel.Failure.self) { + try model.prepareCheckpoint(.init(weights: [:])) + } + } + + @Test + func nameMappingsPreservePrecisionAndSourceMetadata() throws { + let checkpoint = ModelCheckpoint( + weights: ["head.fc.weight": MLXArray.zeros([32, 32])], + metadata: ["format": "mlx"], weightMetadata: ["head.fc.weight": [:]], + perLayerQuantization: .init( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: [ + "head.fc": .quantize(.init(groupSize: 32, bits: 8)), + "target.fc": .skip, + ])) + let mapped = try checkpoint.mapNames { name in + name.hasPrefix("head.") ? "mtp." + name.dropFirst(5) : nil + } + #expect(mapped.weights["mtp.fc.weight"] != nil) + #expect(mapped.metadata(forWeight: "mtp.fc.weight").isEmpty) + #expect(mapped.metadata["format"] == "mlx") + #expect(mapped.perLayerQuantization?.quantization(layer: "mtp.fc")?.bits == 8) + #expect(mapped.perLayerQuantization?.quantization(layer: "mtp.other")?.bits == 4) + #expect(mapped.perLayerQuantization?.perLayerQuantization["target.fc"] == nil) + } + + @Test + func tensorAliasesCannotOverwriteEachOther() { + let checkpoint = ModelCheckpoint(weights: [ + "a.weight": MLXArray(1), "b.weight": MLXArray(2), + ]) + #expect(throws: ModelCheckpoint.MappingError.self) { + try checkpoint.mapNames { _ in "weight" } + } + } + + @Test + func layerSettingAliasesCannotOverwriteEachOther() { + let checkpoint = ModelCheckpoint( + weights: [:], + perLayerQuantization: .init(perLayerQuantization: [ + "a": .skip, "b": .quantize(.init(groupSize: 32, bits: 8)), + ])) + #expect(throws: ModelCheckpoint.MappingError.self) { + try checkpoint.mapNames { _ in "layer" } + } + } + + @Test + func shardMetadataStaysWithTheTensorThatSuppliedIt() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let first = directory.appendingPathComponent("model.safetensors") + let second = directory.appendingPathComponent("mtp.safetensors") + try save( + arrays: ["target.weight": MLXArray(1), "shared.weight": MLXArray(1)], + metadata: ["format": "mlx"], url: first) + try save(arrays: ["mtp.weight": MLXArray(2), "shared.weight": MLXArray(2)], url: second) + let checkpoint = try loadModelCheckpoint(urls: [first, second]) + #expect(checkpoint.metadata["format"] == "mlx") + #expect(checkpoint.metadata(forWeight: "target.weight")["format"] == "mlx") + #expect(checkpoint.metadata(forWeight: "mtp.weight").isEmpty) + #expect(checkpoint.metadata(forWeight: "shared.weight").isEmpty) + #expect(checkpoint.weights["shared.weight"]?.item(Int.self) == 2) + } +} diff --git a/Tests/MLXLMTests/NanbeigeTests.swift b/Tests/MLXLMTests/NanbeigeTests.swift index a37af0b0c5..2a2028133e 100644 --- a/Tests/MLXLMTests/NanbeigeTests.swift +++ b/Tests/MLXLMTests/NanbeigeTests.swift @@ -217,7 +217,7 @@ final class NanbeigeTests: XCTestCase { let logitsW = try prefillLogits(model, t2, cache: cacheW) XCTAssertLessThanOrEqual( - maxAbsDiff(logitsW, logitsF), 1e-3, + maxAbsDiff(logitsW, logitsF), MatmulPrecision.splitTolerance, "warm continuation diverged from cold full prefill") } diff --git a/Tests/MLXLMTests/NemotronHTests.swift b/Tests/MLXLMTests/NemotronHTests.swift index 0d8406ffc8..4c0d06f72a 100644 --- a/Tests/MLXLMTests/NemotronHTests.swift +++ b/Tests/MLXLMTests/NemotronHTests.swift @@ -185,6 +185,36 @@ public class NemotronHTests: XCTestCase { XCTAssertEqual(config.routedScalingFactor, 1.0) } + func testConfigurationDecodingDenseWithoutMoEKeys() throws { + // A dense checkpoint (e.g. NVIDIA-Nemotron-3-Nano-4B) has no "E" layers and + // ships none of the MoE keys; it must still decode, and build a model. + let json = """ + { + "vocab_size": 100, + "hidden_size": 64, + "num_hidden_layers": 4, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "mamba_num_heads": 4, + "mamba_head_dim": 16, + "ssm_state_size": 16, + "conv_kernel": 4, + "n_groups": 2, + "intermediate_size": 128, + "hybrid_override_pattern": "M-M*" + } + """ + + let config = try JSONDecoder().decode( + NemotronHConfiguration.self, from: json.data(using: .utf8)!) + + XCTAssertEqual(config.moeIntermediateSize, 0) + XCTAssertEqual(config.moeSharedExpertIntermediateSize, 0) + XCTAssertEqual(config.nRoutedExperts, 0) + XCTAssertEqual(config.numExpertsPerTok, 0) + _ = NemotronHModel(config) // no MoE layer is built, so no expert count is needed + } + // MARK: - Weight Sanitization Tests func testSanitizeConv1dWeights() throws { diff --git a/Tests/MLXLMTests/ParoQuantCheckpointTests.swift b/Tests/MLXLMTests/ParoQuantCheckpointTests.swift new file mode 100644 index 0000000000..978e99a3c7 --- /dev/null +++ b/Tests/MLXLMTests/ParoQuantCheckpointTests.swift @@ -0,0 +1,120 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN +import Testing + +@testable import MLXLMCommon + +struct ParoQuantCheckpointTests { + @Test(arguments: [false, true]) + func checkpointPreparationPreservesPrecision(prepared: Bool) async throws { + let directory = try makeCheckpoint(prepared: prepared) + defer { try? FileManager.default.removeItem(at: directory) } + let container = try await loadParoQuantModel( + from: directory, + typeRegistry: ModelTypeRegistry(creators: [ + "qwen3_5": { _ in CheckpointModel() } + ]), + tokenizerLoader: TestTokenizerLoader()) + try await container.perform { context in + let model = try #require(context.model as? CheckpointModel) + let layer = try #require(model.layer as? QuantizedLinear) + #expect(layer.bits == 8) + #expect(layer.weight.asArray(UInt32.self).allSatisfy { $0 == 17 }) + } + } + + @Test(arguments: [false, true]) + func checkpointPreparationPropagatesCollisions(prepared: Bool) async throws { + let directory = try makeCheckpoint(prepared: prepared, collision: true) + defer { try? FileManager.default.removeItem(at: directory) } + await #expect(throws: ModelCheckpoint.MappingError.self) { + try await loadParoQuantModel( + from: directory, + typeRegistry: ModelTypeRegistry(creators: [ + "qwen3_5": { _ in CheckpointModel() } + ]), + tokenizerLoader: TestTokenizerLoader()) + } + } + + private func makeCheckpoint(prepared: Bool, collision: Bool = false) throws -> URL { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let config = """ + { + "model_type": "qwen3_5", + "architectures": ["Qwen3_5ForConditionalGeneration"], + "quantization_config": { + "quant_method": "paroquant", "bits": 4, "group_size": 32, "krot": 8 + } + } + """ + try Data(config.utf8).write(to: directory.appendingPathComponent("config.json")) + var weights = [ + "source.layer.weight": MLXArray.full([32, 8], values: MLXArray(UInt32(17))), + "source.layer.scales": MLXArray.ones([32, 1]), + "source.layer.biases": MLXArray.zeros([32, 1]), + "mtp.layer.weight": MLXArray.zeros([32, 32]), + ] + if collision { + weights["layer.weight"] = MLXArray.zeros([32, 8], type: UInt32.self) + } + try save(arrays: weights, url: directory.appendingPathComponent("model.safetensors")) + if prepared { + ParoQuantPreparedCheckpoint.write( + weights: weights, + manifest: try ParoQuantPreparedCheckpoint.currentManifest(directory: directory), + directory: directory) + #expect( + FileManager.default.fileExists( + atPath: directory.appendingPathComponent( + ParoQuantPreparedCheckpoint.fileName + ).path)) + } + return directory + } + + private enum TestError: Error { + case legacySanitizerCalled + } + + private struct TestTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { + TestTokenizer() + } + } + + private final class CheckpointModel: Module, LanguageModel, KVCacheDimensionProvider { + @ModuleInfo var layer: Linear + let kvHeads: [Int] = [] + + override init() { + _layer.wrappedValue = Linear(32, 32, bias: false) + super.init() + } + + func prepareCheckpoint(_ checkpoint: ModelCheckpoint) throws -> ModelCheckpoint { + var checkpoint = checkpoint + checkpoint.perLayerQuantization?.perLayerQuantization["source.layer"] = + .quantize(.init(groupSize: 32, bits: 8)) + return try checkpoint.mapNames( + using: .init([ + .excludePrefix("mtp"), .replacePrefix("source", with: ""), + ])) + } + + func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + throw TestError.legacySanitizerCalled + } + + func prepare( + _ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters + ) throws -> PrepareResult { + .tokens(input.text) + } + } +} diff --git a/Tests/MLXLMTests/Qwen35ContinuationTests.swift b/Tests/MLXLMTests/Qwen35ContinuationTests.swift index 3fc5b66865..929a4666c6 100644 --- a/Tests/MLXLMTests/Qwen35ContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen35ContinuationTests.swift @@ -127,7 +127,7 @@ final class Qwen35ContinuationTests: XCTestCase { prefill: .init())) XCTAssertLessThanOrEqual( - maxAbsDiff(warmLogits, fullLogits), 1e-3, + maxAbsDiff(warmLogits, fullLogits), MatmulPrecision.splitTolerance, "rank-1 warm continuation diverged from full prefill") } } @@ -262,7 +262,7 @@ final class Qwen35ContinuationTests: XCTestCase { maxAbsDiff(restoredImageLogits, warmImageLogits), 1e-6, "disk-restored state diverged when a later turn added another image") XCTAssertLessThanOrEqual( - maxAbsDiff(restoredImageLogits, coldLogits), 1e-3, + maxAbsDiff(restoredImageLogits, coldLogits), MatmulPrecision.splitTolerance, "restored two-image continuation diverged from full prefill") } } diff --git a/Tests/MLXLMTests/Qwen35FusedGDNProjectionTests.swift b/Tests/MLXLMTests/Qwen35FusedGDNProjectionTests.swift index 56c488e369..2514944fde 100644 --- a/Tests/MLXLMTests/Qwen35FusedGDNProjectionTests.swift +++ b/Tests/MLXLMTests/Qwen35FusedGDNProjectionTests.swift @@ -489,4 +489,45 @@ final class Qwen35FusedGDNProjectionTests: XCTestCase { Double(referenceTokens.count) / fusedDecodeMedian, checksum)) } + + // MARK: - Memory + + /// Active MLX memory once the GPU is idle and Metal's completion handlers + /// have released their temporaries. + private func settledActiveMemory() -> Int { + Stream.gpu.synchronize() + usleep(150_000) + Memory.clearCache() + return Memory.activeMemory + } + + /// The fused projection is not a registered child, so a decode trace that + /// read it as a tape constant would keep its arrays alive after the model + /// is gone (MLX does not release every constant of an erased trace). + func testCompiledDecodeReleasesFusedProjectionWithTheModel() throws { + let base = settledActiveMemory() + try autoreleasepool { + let model = Qwen35TextModel(try llmConfiguration()) + let layers = model.modules().compactMap { $0 as? Qwen35GatedDeltaNet } + XCTAssertFalse(layers.isEmpty) + for layer in layers { + try quantize(layer) + } + try model.prepare() + XCTAssertTrue(layers.allSatisfy(\.hasFusedInputProjection)) + + let cache = try model.newCache(parameters: nil) + for token: Int32 in [1, 2, 3] { + let logits = model(MLXArray([token]).reshaped(1, 1), cache: cache) + eval(logits) + } + XCTAssertGreaterThan(model.model.compiledDecodeSegmentCount, 0) + eval(cache.flatMap(\.state)) + } + // MLX keeps one scalar constant of an erased trace alive (the kernel's + // step count); anything weight-sized is the projection. + let retained = settledActiveMemory() - base + XCTAssertLessThan( + retained, 64, "\(retained) bytes stayed allocated after the model was dropped") + } } diff --git a/Tests/MLXLMTests/Qwen35MTPTests.swift b/Tests/MLXLMTests/Qwen35MTPTests.swift index afb7f68261..97cc0ce7eb 100644 --- a/Tests/MLXLMTests/Qwen35MTPTests.swift +++ b/Tests/MLXLMTests/Qwen35MTPTests.swift @@ -1,9 +1,10 @@ import Foundation import MLX -import MLXLMCommon +import MLXNN import Testing @testable import MLXLLM +@testable import MLXLMCommon @testable import MLXVLM @Test @@ -33,7 +34,7 @@ func testQwen35MTPDraftSanitizeKeepsAndShiftsMTPNorms() throws { from: Data(qwen35TextConfigJSON(mtpLayers: 1).utf8)) let drafter = MLXLLM.Qwen35MTPDraftModel(cfg) - let sanitized = drafter.sanitize(weights: [ + let sanitized = try drafter.sanitize(weights: [ "mtp.norm.weight": MLXArray.zeros([16]), "mtp.pre_fc_norm_embedding.weight": MLXArray.zeros([16]), "mtp.layers.0.self_attn.q_proj.weight": MLXArray.zeros([32, 16]), @@ -56,6 +57,29 @@ func testQwen35MTPDraftSanitizeKeepsAndShiftsMTPNorms() throws { #expect(allClose(pre, MLXArray.ones([16]), rtol: 0, atol: 0).item(Bool.self)) } +@Test(arguments: [false, true]) +func testQwen35MTPDraftSanitizeRejectsCompetingComponents(vision: Bool) throws { + let data = Data(qwen35TextConfigJSON(mtpLayers: 1).utf8) + let drafter: any BaseLanguageModel + if vision { + drafter = MLXVLM.Qwen35VLMNextNDraftModel( + try JSONDecoder().decode(MLXVLM.Qwen35Configuration.TextConfiguration.self, from: data)) + } else { + drafter = MLXLLM.Qwen35MTPDraftModel( + try JSONDecoder().decode(MLXLLM.Qwen35TextConfiguration.self, from: data)) + } + let weights = [ + "mtp.norm.weight": MLXArray.zeros([16]), + "language_model.mtp.norm.weight": MLXArray.ones([16]), + ] + #expect(throws: CheckpointComponent.SelectionError.self) { + try drafter.sanitize(weights: weights) + } + #expect(throws: CheckpointComponent.SelectionError.self) { + try drafter.sanitize(weights: weights, metadata: [:]) + } +} + @Test func testQwen35StandaloneMTPDoesNotDoubleShiftConvertedNorms() throws { let cfg = try JSONDecoder().decode( @@ -64,7 +88,7 @@ func testQwen35StandaloneMTPDoesNotDoubleShiftConvertedNorms() throws { let drafter = MLXLLM.Qwen35MTPDraftModel(cfg, preconvertedNorms: true) let weight = MLXArray.zeros([16]) - let sanitized = drafter.sanitize(weights: ["mtp.norm.weight": weight]) + let sanitized = try drafter.sanitize(weights: ["mtp.norm.weight": weight]) let norm = try #require(sanitized["mtp.norm.weight"]) eval(norm) #expect(allClose(norm, weight, rtol: 0, atol: 0).item(Bool.self)) @@ -86,7 +110,7 @@ func testQwen35MTPDraftSanitizeStacksPerExpertMoEWeights() throws { "mtp.layers.0.mlp.experts.1.down_proj.weight": MLXArray.ones([16, 16]), ] - let sanitized = drafter.sanitize(weights: weights) + let sanitized = try drafter.sanitize(weights: weights) #expect(sanitized["mtp.layers.0.mlp.experts.0.gate_proj.weight"] == nil) #expect(sanitized["mtp.layers.0.mlp.switch_mlp.gate_proj.weight"]?.shape == [2, 16, 16]) @@ -103,7 +127,7 @@ func testQwen35MTPDraftInstantiatesDedicatedEmbeddingWhenConfigured() throws { let drafter = MLXLLM.Qwen35MTPDraftModel(cfg) #expect(drafter.mtp.embedTokens != nil) - let sanitized = drafter.sanitize(weights: [ + let sanitized = try drafter.sanitize(weights: [ "mtp.embed_tokens.weight": MLXArray.zeros([16, 16]), "model.embed_tokens.weight": MLXArray.ones([16, 16]), ]) @@ -111,6 +135,10 @@ func testQwen35MTPDraftInstantiatesDedicatedEmbeddingWhenConfigured() throws { #expect(sanitized["model.embed_tokens.weight"] == nil) } +/// Bound for comparing a gated-delta-net state reached two ways. Wider on machines whose +/// float32 matmuls run as TF32; see ``MatmulPrecision``. +private let gdnStateTolerance = MatmulPrecision.tolerance(float32: 1e-5, reduced: 2e-3) + @Suite(.serialized) struct Qwen35MTPMetalTests { @Test @@ -318,7 +346,12 @@ struct Qwen35MTPMetalTests { #expect(restored.count == expected.count) for (actual, reference) in zip(restored, expected) { eval(actual, reference) - #expect(allClose(actual, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) + // The checkpoint and the prefix run reach the same state through + // differently shaped matmuls, so the bound follows the machine's + // float32 matmul precision; see MatmulPrecision. + #expect( + allClose(actual, reference, rtol: gdnStateTolerance, atol: gdnStateTolerance) + .item(Bool.self)) } } @@ -342,7 +375,9 @@ struct Qwen35MTPMetalTests { #expect(speculativeCache.restoreSpeculativeCheckpoint()) for (actual, reference) in zip(speculativeCache.state, prefixCache.state) { eval(actual, reference) - #expect(allClose(actual, reference, rtol: 1e-5, atol: 1e-5).item(Bool.self)) + #expect( + allClose(actual, reference, rtol: gdnStateTolerance, atol: gdnStateTolerance) + .item(Bool.self)) } } @@ -506,3 +541,354 @@ private func qwen35StandaloneMTPConfigJSON() -> String { } """ } + +@Suite(.serialized) +struct Qwen35CheckpointLoadingTests { + @Test(arguments: [false, true]) + func convertedEmbeddedFactoryPreservesMixedPrecision(vision: Bool) async throws { + let fixture = try await makeFixture( + vision: vision, standalone: false, prefix: "language_model.mtp.", bits: 4) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let context = try await fixture.factory.load( + from: fixture.directory, using: UnusedTokenizerLoader()) + let fc = try #require( + (context.model as? MLXLLM.Qwen35MTPDraftModel)?.mtp.fc as? QuantizedLinear + ?? (context.model as? MLXVLM.Qwen35VLMNextNDraftModel)?.mtp.fc as? QuantizedLinear) + #expect(fc.bits == 8) + #expect( + context.model.modules().compactMap { $0 as? QuantizedLinear }.contains { $0.bits == 4 }) + } + + @Test(arguments: [false, true]) + func targetLoaderExcludesConvertedMTPComponent(vision: Bool) throws { + let data = try fixtureConfiguration(vision: vision, standalone: false, bits: nil) + let target: any BaseLanguageModel + if vision { + target = MLXVLM.Qwen35( + try JSONDecoder().decode(MLXVLM.Qwen35Configuration.self, from: data)) + } else { + target = MLXLLM.Qwen35Model( + try JSONDecoder().decode(MLXLLM.Qwen35Configuration.self, from: data)) + } + var weights = Dictionary(uniqueKeysWithValues: target.parameters().flattened()) + let count = weights.count + weights["language_model.mtp.norm.weight"] = MLXArray.zeros([64]) + weights["language_model.mtp.fc.weight"] = MLXArray.zeros([64, 128]) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try save( + arrays: weights, metadata: ["format": "mlx"], + url: directory.appendingPathComponent("model.safetensors")) + try loadWeights(modelDirectory: directory, model: target) + #expect(target.parameters().flattened().count == count) + } + + @Test + func conversionRoundTripRetainsNormConvention() async throws { + let fixture = try await makeFixture(vision: false, standalone: false, prefix: "mtp.") + let output = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + defer { + try? FileManager.default.removeItem(at: fixture.directory) + try? FileManager.default.removeItem(at: output) + } + let context = try await fixture.factory.load( + from: fixture.directory, using: UnusedTokenizerLoader()) + _ = try convert( + modelDirectory: fixture.directory, model: context.model, to: output, + bits: 4, groupSize: 32) + let (_, metadata) = try loadArraysAndMetadata( + url: output.appendingPathComponent("model.safetensors")) + #expect(metadata[Qwen35CheckpointPolicy.normMetadataKey] == "scale") + let reloaded = try await fixture.factory.load(from: output, using: UnusedTokenizerLoader()) + let norm = try #require( + reloaded.model.parameters().flattened().first { $0.0 == "mtp.norm.weight" }?.1) + #expect(norm.asArray(Float.self) == Array(repeating: 1, count: 64)) + } + + @Test + func expertParametersAndSettingsAreTransformedTogether() throws { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + let prefix = "mtp.layers.0.mlp" + var weights = [String: MLXArray]() + for expert in 0 ..< 2 { + for (parameter, shape) in [ + ("weight", [64, 8]), ("scales", [64, 2]), ("biases", [64, 2]), + ] { + weights["\(prefix).experts.\(expert).up_proj.\(parameter)"] = MLXArray.zeros(shape) + } + } + let checkpoint = ModelCheckpoint( + weights: weights, + perLayerQuantization: .init( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: [ + "\(prefix).experts.0.up_proj": .quantize(.init(groupSize: 32, bits: 8)), + "\(prefix).experts.1.up_proj": .quantize(.init(groupSize: 32, bits: 8)), + ])) + let prepared = try policy.prepare(checkpoint, mtpNumHiddenLayers: 1, numExperts: 2) + #expect(prepared.weights["\(prefix).switch_mlp.up_proj.weight"]?.shape == [2, 64, 8]) + #expect(prepared.weights["\(prefix).switch_mlp.up_proj.scales"]?.shape == [2, 64, 2]) + #expect(prepared.weights["\(prefix).switch_mlp.up_proj.biases"]?.shape == [2, 64, 2]) + #expect( + prepared.perLayerQuantization?.quantization(layer: "\(prefix).switch_mlp.up_proj")?.bits + == 8) + #expect( + prepared.perLayerQuantization?.perLayerQuantization["\(prefix).experts.0.up_proj"] + == nil) + } + + @Test(arguments: [false, true], [4, 5, 8]) + func standaloneFactoryLoadsPublishedLayout(vision: Bool, bits: Int) async throws { + let fixture = try await makeFixture(vision: vision, standalone: true, bits: bits) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let context = try await fixture.factory.load( + from: fixture.directory, using: UnusedTokenizerLoader()) + let parameters = context.model.parameters().flattened() + #expect(parameters.count == 31) + let norm = try #require(parameters.first { $0.0 == "mtp.norm.weight" }?.1) + #expect(norm.asArray(Float.self) == Array(repeating: 1, count: 64)) + let fc = try #require( + (context.model as? MLXLLM.Qwen35MTPDraftModel)?.mtp.fc as? QuantizedLinear + ?? (context.model as? MLXVLM.Qwen35VLMNextNDraftModel)?.mtp.fc as? QuantizedLinear) + #expect(fc.bits == 8) + let projections = context.model.modules().compactMap { $0 as? MLXNN.QuantizedLinear } + #expect(projections.contains { $0.bits == bits }) + } + + @Test(arguments: [false, true], ["mtp.", "language_model.mtp."]) + func embeddedFactoryLoadsComponentWithoutTargetWeights(vision: Bool, prefix: String) + async throws + { + let fixture = try await makeFixture(vision: vision, standalone: false, prefix: prefix) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let context = try await fixture.factory.load( + from: fixture.directory, using: UnusedTokenizerLoader()) + let weights = Dictionary(uniqueKeysWithValues: context.model.parameters().flattened()) + #expect(weights.count == 15) + #expect(weights["model.embed_tokens.weight"] == nil) + #expect(weights["mtp.norm.weight"]?.asArray(Float.self) == Array(repeating: 1, count: 64)) + } + + @Test + func targetMetadataDoesNotClassifyTheRawMTPShard() throws { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + let checkpoint = ModelCheckpoint( + weights: ["mtp.norm.weight": MLXArray.zeros([64])], + metadata: ["format": "mlx"], weightMetadata: ["mtp.norm.weight": [:]]) + let prepared = try policy.prepare(checkpoint, mtpNumHiddenLayers: 1, numExperts: 0) + #expect( + prepared.weights["mtp.norm.weight"]?.asArray(Float.self) + == Array(repeating: 1, count: 64)) + } + + @Test + func explicitNormConventionOverridesLegacyLayout() throws { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + let raw = ModelCheckpoint( + weights: ["language_model.mtp.norm.weight": MLXArray.zeros([4])], + metadata: [Qwen35CheckpointPolicy.normMetadataKey: "offset"]) + let prepared = try policy.prepare(raw, mtpNumHiddenLayers: 1, numExperts: 0) + #expect(prepared.weights["mtp.norm.weight"]?.asArray(Float.self) == [1, 1, 1, 1]) + let scale = ModelCheckpoint( + weights: prepared.weights, + metadata: [Qwen35CheckpointPolicy.normMetadataKey: "scale"]) + let repeated = try policy.prepare(scale, mtpNumHiddenLayers: 1, numExperts: 0) + #expect(repeated.weights["mtp.norm.weight"]?.asArray(Float.self) == [1, 1, 1, 1]) + } + + @Test + func missingAndCompetingComponentsAreRejected() { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + for weights in [ + ["model.layers.0.weight": MLXArray(1)], + ["mtp.norm.weight": MLXArray(1), "language_model.mtp.fc.weight": MLXArray(1)], + ] { + #expect(throws: CheckpointComponent.SelectionError.self) { + try policy.prepare(.init(weights: weights), mtpNumHiddenLayers: 1, numExperts: 0) + } + } + } + + @Test + func conflictingAndUnknownNormMetadataIsRejected() { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + let weights = [ + "mtp.norm.weight": MLXArray.zeros([4]), + "mtp.layers.0.input_layernorm.weight": MLXArray.zeros([4]), + ] + for metadata in [ + ["mtp.norm.weight": [Qwen35CheckpointPolicy.normMetadataKey: "unknown"]], + [ + "mtp.norm.weight": [Qwen35CheckpointPolicy.normMetadataKey: "scale"], + "mtp.layers.0.input_layernorm.weight": [ + Qwen35CheckpointPolicy.normMetadataKey: "offset" + ], + ], + ] { + #expect(throws: Qwen35CheckpointPolicy.LoadingError.self) { + try policy.prepare( + .init(weights: weights, weightMetadata: metadata), mtpNumHiddenLayers: 1, + numExperts: 0) + } + } + } + + @Test + func targetLayoutsShareComponentSelectionAndQuantizationMapping() throws { + let checkpoint = ModelCheckpoint( + weights: [ + "model.language_model.layers.0.self_attn.q_proj.weight": MLXArray(1), + "mtp.fc.weight": MLXArray(2), + "lm_head.weight": MLXArray(3), + "notmtp.weight": MLXArray(4), + ], + perLayerQuantization: .init(perLayerQuantization: [ + "model.language_model.layers.0.self_attn.q_proj": .quantize( + .init(groupSize: 32, bits: 8)) + ])) + for layout in [Qwen35CheckpointPolicy.TargetLayout.text, .wrappedText, .vision] { + let prepared = try Qwen35CheckpointPolicy.prepareTarget( + checkpoint, layout: layout, tiedWordEmbeddings: true) + let prefix = layout == .text ? "model." : "language_model.model." + let projection = prefix + "layers.0.self_attn.q_proj" + #expect(prepared.weights[projection + ".weight"] != nil) + #expect(prepared.perLayerQuantization?.quantization(layer: projection)?.bits == 8) + #expect(prepared.weights.count == 2) + #expect(prepared.weights["notmtp.weight"] != nil) + } + } + + @Test + func unknownAndMissingWeightsStillFailStrictFactoryLoading() async throws { + for missing in [false, true] { + let fixture = try await makeFixture(vision: false, standalone: true) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let url = fixture.directory.appendingPathComponent("model.safetensors") + var weights = try loadArrays(url: url) + eval(Array(weights.values)) + if missing { + weights.removeValue(forKey: "norm.weight") + } else { + weights["unexpected.weight"] = MLXArray(1) + } + try save(arrays: weights, metadata: ["format": "mlx"], url: url) + await #expect(throws: (any Error).self) { + try await fixture.factory.load( + from: fixture.directory, using: UnusedTokenizerLoader()) + } + } + } + + @Test + func expertPrecisionCannotChangeDuringStacking() throws { + let policy = Qwen35CheckpointPolicy(layout: .embedded, preconvertedNorms: false) + let prefix = "mtp.layers.0.mlp.experts" + let weights = [ + "\(prefix).0.up_proj.weight": MLXArray.zeros([64, 64]), + "\(prefix).1.up_proj.weight": MLXArray.zeros([64, 64]), + ] + let checkpoint = ModelCheckpoint( + weights: weights, + perLayerQuantization: .init( + quantization: .init(groupSize: 32, bits: 4), + perLayerQuantization: [ + "\(prefix).0.up_proj": .quantize(.init(groupSize: 32, bits: 8)) + ])) + #expect(throws: Qwen35CheckpointPolicy.LoadingError.self) { + try policy.prepare(checkpoint, mtpNumHiddenLayers: 1, numExperts: 2) + } + #expect(throws: Qwen35CheckpointPolicy.LoadingError.self) { + try policy.prepare( + .init(weights: ["\(prefix).0.up_proj.weight": MLXArray.zeros([64, 64])]), + mtpNumHiddenLayers: 1, numExperts: 2) + } + } + + private struct Fixture { + let directory: URL + let factory: MTPDrafterModelFactory + } + + private func makeFixture( + vision: Bool, standalone: Bool, prefix: String = "", bits: Int? = nil + ) async throws -> Fixture { + let config = try fixtureConfiguration( + vision: vision, standalone: standalone, bits: bits, prefix: prefix) + let registry = ModelTypeRegistry() + let modelType = standalone ? "qwen3_5_mtp" : "qwen3_5" + await registry.registerModelType(modelType) { data in + try makeDrafter(configuration: data, vision: vision) + } + let model = try makeDrafter(configuration: config, vision: vision) + if let bits { + quantize(model: model) { path, _ in (32, path == "mtp.fc" ? 8 : bits, .affine) } + } + var weights = [String: MLXArray]() + for (name, array) in model.parameters().flattened() { + let serialized = prefix + name.dropFirst("mtp.".count) + let isNorm = name.contains("norm") + weights[serialized] = isNorm ? MLXArray.ones(array.shape) : array + if prefix == "mtp.", isNorm { weights[serialized] = MLXArray.zeros(array.shape) } + } + if !standalone { weights["model.embed_tokens.weight"] = MLXArray.zeros([16, 64]) } + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + do { + try config.write(to: directory.appendingPathComponent("config.json")) + try save( + arrays: weights, metadata: standalone ? ["format": "mlx"] : [:], + url: directory.appendingPathComponent("model.safetensors")) + } catch { + try? FileManager.default.removeItem(at: directory) + throw error + } + return Fixture( + directory: directory, + factory: MTPDrafterModelFactory( + typeRegistry: registry, modelRegistry: MTPDrafterRegistry.shared)) + } + + private func fixtureConfiguration( + vision: Bool, standalone: Bool, bits: Int?, prefix: String = "mtp." + ) throws -> Data { + let json = + vision + ? qwen35VLMConfigJSON(mtpLayers: 1) + : qwen35WrappedTextConfigJSON(modelType: "qwen3_5") + let sized = json.replacingOccurrences( + of: "\"hidden_size\": 16", with: "\"hidden_size\": 64" + ) + .replacingOccurrences(of: "\"intermediate_size\": 32", with: "\"intermediate_size\": 128") + .replacingOccurrences(of: "\"head_dim\": 8", with: "\"head_dim\": 32") + var root = try #require( + JSONSerialization.jsonObject(with: Data(sized.utf8)) as? [String: Any]) + if standalone { root["model_type"] = "qwen3_5_mtp" } + if let bits { + root["quantization"] = [ + "group_size": 32, "bits": bits, + (standalone ? "fc" : prefix + "fc"): ["group_size": 32, "bits": 8], + ] + } + return try JSONSerialization.data(withJSONObject: root) + } +} + +private func makeDrafter(configuration: Data, vision: Bool) throws -> any MTPDrafterModel { + if vision { + return MLXVLM.Qwen35VLMNextNDraftModel( + try JSONDecoder().decode(MLXVLM.Qwen35Configuration.self, from: configuration)) + } + return MLXLLM.Qwen35MTPDraftModel( + try JSONDecoder().decode(MLXLLM.Qwen35Configuration.self, from: configuration)) +} + +private struct UnusedTokenizerLoader: TokenizerLoader { + func load(from url: URL) async throws -> any Tokenizer { + throw ModelFactoryError.invalidConfiguration( + "MTP checkpoints must borrow the target tokenizer.") + } +} diff --git a/Tests/MLXLMTests/Qwen35SanitizeTests.swift b/Tests/MLXLMTests/Qwen35SanitizeTests.swift index d5e7e87220..e56887f953 100644 --- a/Tests/MLXLMTests/Qwen35SanitizeTests.swift +++ b/Tests/MLXLMTests/Qwen35SanitizeTests.swift @@ -74,12 +74,12 @@ final class Qwen35SanitizeTests: XCTestCase { "model.norm.weight": dummy, // Already-namespaced path — verify the existing rename branch // still fires. - "model.language_model.layers.0.mlp.up_proj.weight": dummy, + "model.language_model.layers.0.mlp.gate_proj.weight": dummy, // Top-level path the existing logic remaps. "lm_head.weight": dummy, ] - let sanitized = model.sanitize(weights: weights) + let sanitized = try model.sanitize(weights: weights) // Bare `model.*` keys are now under `language_model.model.*`. XCTAssertNotNil( @@ -89,6 +89,7 @@ final class Qwen35SanitizeTests: XCTestCase { sanitized["language_model.model.layers.0.self_attn.q_proj.weight"]) XCTAssertNotNil(sanitized["language_model.model.embed_tokens.weight"]) XCTAssertNotNil(sanitized["language_model.model.norm.weight"]) + XCTAssertNotNil(sanitized["language_model.model.layers.0.mlp.gate_proj.weight"]) // The `lm_head` rename branch is preserved. XCTAssertNotNil(sanitized["language_model.lm_head.weight"]) @@ -103,6 +104,20 @@ final class Qwen35SanitizeTests: XCTestCase { } } + func testCompetingAliasesAreRejectedDuringCheckpointPreparation() throws { + let model = Qwen35(try makeMinimalConfig()) + let weights = [ + "model.layers.0.mlp.up_proj.weight": MLXArray.zeros([1, 1]), + "model.language_model.layers.0.mlp.up_proj.weight": MLXArray.ones([1, 1]), + ] + XCTAssertThrowsError(try model.prepareCheckpoint(.init(weights: weights))) { error in + XCTAssertTrue(error is ModelCheckpoint.MappingError) + } + XCTAssertThrowsError(try model.sanitize(weights: weights)) { error in + XCTAssertTrue(error is ModelCheckpoint.MappingError) + } + } + /// A pre-converted MLX checkpoint (conv1d already sanitized, trailing dim /// == 1, no MTP tensors) already stores RMSNorm weights in the shifted /// convention. Sanitize must NOT add the `+1` again: double-shifting every @@ -120,7 +135,7 @@ final class Qwen35SanitizeTests: XCTestCase { "language_model.model.norm.weight": MLXArray.zeros([8]), ] - let sanitized = model.sanitize(weights: weights) + let sanitized = try model.sanitize(weights: weights) let norm = try XCTUnwrap(sanitized["language_model.model.norm.weight"]) XCTAssertEqual( @@ -128,6 +143,24 @@ final class Qwen35SanitizeTests: XCTestCase { "pre-converted norm weight must not be +1 shifted (double-shift => garbage)") } + /// A converted MLX checkpoint can keep its MTP head. Its keys must not + /// reach the model, or loading fails with unhandled keys. + func testMLXCheckpointDropsMTPWeights() throws { + let config = try makeMinimalConfig() + let model = Qwen35(config) + + let dummy = MLXArray.zeros([1, 1]) + let weights: [String: MLXArray] = [ + "language_model.model.norm.weight": dummy, + "language_model.mtp.fc.weight": dummy, + "language_model.mtp.layers.0.self_attn.q_proj.weight": dummy, + ] + + let sanitized = try model.sanitize(weights: weights, metadata: ["format": "mlx"]) + + XCTAssertEqual(Set(sanitized.keys), ["language_model.model.norm.weight"]) + } + /// A raw HF checkpoint (unsanitized conv1d, trailing dim != 1) stores /// RMSNorm weights un-shifted, so sanitize must add the `+1`. func testRawCheckpointNormWeightsAreShifted() throws { @@ -140,7 +173,7 @@ final class Qwen35SanitizeTests: XCTestCase { "language_model.model.norm.weight": MLXArray.zeros([8]), ] - let sanitized = model.sanitize(weights: weights) + let sanitized = try model.sanitize(weights: weights) let norm = try XCTUnwrap(sanitized["language_model.model.norm.weight"]) XCTAssertEqual( diff --git a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift index b264d992b2..96c2730dca 100644 --- a/Tests/MLXLMTests/Qwen3VLContinuationTests.swift +++ b/Tests/MLXLMTests/Qwen3VLContinuationTests.swift @@ -135,7 +135,7 @@ final class Qwen3VLContinuationTests: XCTestCase { prefill: .init())) XCTAssertLessThanOrEqual( - maxAbsDiff(warmLogits, fullLogits), 1e-3, + maxAbsDiff(warmLogits, fullLogits), MatmulPrecision.splitTolerance, "rank-1 warm continuation diverged from full prefill") } } @@ -231,7 +231,7 @@ final class Qwen3VLContinuationTests: XCTestCase { model.prepare(input, cache: windowedCache, state: nil, prefill: .init(stepSize: 8))) XCTAssertLessThanOrEqual( - maxAbsDiff(windowedLogits, singleLogits), 1e-3, + maxAbsDiff(windowedLogits, singleLogits), MatmulPrecision.splitTolerance, "padding changed Qwen3-VL windowed M-RoPE semantics") } } diff --git a/Tests/MLXLMTests/RerankerTests.swift b/Tests/MLXLMTests/RerankerTests.swift index d94ea88cf0..394172ed3a 100644 --- a/Tests/MLXLMTests/RerankerTests.swift +++ b/Tests/MLXLMTests/RerankerTests.swift @@ -134,9 +134,9 @@ struct RerankerTests { let reranker = makeConstantReranker( scoreKind: .normalizedRelevance, scores: [0.5]) let task = Task { - try await reranker.scores(query: "q", documents: ["d"]) + withUnsafeCurrentTask { $0?.cancel() } + return try await reranker.scores(query: "q", documents: ["d"]) } - task.cancel() await #expect(throws: CancellationError.self) { try await task.value @@ -568,6 +568,30 @@ struct RerankerTests { #expect(scores[0] <= 1) } + @Test(arguments: [DType.bfloat16, .float16, .float32]) + func jinaCosineSimilarityUsesFloat32Reductions(dtype: DType) { + let query = MLXArray([Float(1), 2, 3]).reshaped(1, 3).asType(dtype) + let documents = MLXArray([Float(3), 2, 1, -3, -2, -1, 0, 0, 0]) + .reshaped(3, 3).asType(dtype) + + let output = jinaCosineSimilarity(documents, query) + let scores = output.asArray(Float.self) + + #expect(output.dtype == .float32) + #expect(abs(scores[0] - 10.0 / 14.0) < 1e-6) + #expect(abs(scores[1] + 10.0 / 14.0) < 1e-6) + #expect(scores[2] == 0) + } + + @Test(arguments: [Float(1e-5), 1e3]) + func jinaCosineSimilarityAvoidsFloat16UnderflowAndOverflow(scale: Float) { + let vector = (MLXArray([Float(1), 2, 3]) * scale).reshaped(1, 3).asType(.float16) + let score = jinaCosineSimilarity(vector, vector).item(Float.self) + + #expect(score.isFinite) + #expect(abs(score - 1) < 1e-6) + } + @Test func causalScoringUsesMicroBatchesAndReturnsNormalizedRelevance() async throws { let tokenizer = ByteRerankerTokenizer() let model = TestCausalRerankerModel( @@ -604,6 +628,77 @@ struct RerankerTests { #expect(model.callShapes == [[1, 512]]) } + @Test(arguments: [false, true], [false, true]) + func qwenFinalTokenLogitsMatchFullProjection(tied: Bool, quantized: Bool) throws { + let configuration = try JSONDecoder().decode( + MLXLLM.Qwen3Configuration.self, + from: Data( + """ + { + "vocab_size": 128, "hidden_size": 64, "num_hidden_layers": 2, + "intermediate_size": 128, "num_attention_heads": 4, + "num_key_value_heads": 2, "head_dim": 16, "rms_norm_eps": 1e-6, + "tie_word_embeddings": \(tied) + } + """.utf8)) + + for dtype: DType in [.float32, .float16] { + let model = withRandomState(MLXRandom.RandomState(seed: 42)) { + MLXLLM.Qwen3Model(configuration) + } + model.apply { $0.dtype.isFloatingPoint ? $0.asType(dtype) : $0 } + if quantized { + quantize(model: model, groupSize: 32, bits: 4) + } + for lengths in [[1], [1, 3, 8], [8, 4, 8]] { + let width = lengths.max() ?? 1 + let rows = lengths.enumerated().map { row, length in + (0 ..< width).map { column in + column < length ? (row * 13 + column * 7 + 1) % 128 : 0 + } + } + let tokens = MLXArray(rows.flatMap { $0 }).reshaped(lengths.count, width) + let full = model(tokens, cache: nil) + let expected = stacked( + lengths.enumerated().map { row, length in full[row, length - 1] }) + let actual = model.lastTokenLogits(tokens, sequenceLengths: lengths) + + #expect(actual.shape == [lengths.count, 128]) + let tolerance: Float = dtype == .float16 ? 0.02 : 0.0001 + #expect(abs(actual - expected).max().item(Float.self) < tolerance) + } + } + } + + @Test func causalScoringUsesFinalTokenCapabilityAndKeepsSingletonPrefill() async throws { + let tokenizer = ByteRerankerTokenizer() + let container = makeModelContainer( + model: TestFinalTokenRerankerModel(tokenizer: tokenizer), tokenizer: tokenizer) + let reference = makeModelContainer( + model: TestCausalRerankerModel( + trueTokenID: tokenizer.trueTokenID, falseTokenID: tokenizer.falseTokenID), + tokenizer: tokenizer) + let documents = ["bbbb", "a", String(repeating: "c", count: 1_000)] + let options = RerankExecutionOptions(maxBatchSize: 2, maxBatchTokens: 1_024) + + let actual = try await container.causalRerankerScores( + query: "q", documents: documents, instruction: nil, + maxInputTokens: 512, options: options) + let expected = try await reference.causalRerankerScores( + query: "q", documents: documents, instruction: nil, + maxInputTokens: 512, options: options) + let calls = try await container.perform { context in + let model = try #require(context.model as? TestFinalTokenRerankerModel) + return (model.projectedLengths, model.fullForwardShapes) + } + + #expect(actual == expected) + #expect(calls.0.count == 1) + #expect(calls.0.first?.count == 2) + #expect(calls.0.first?.first != calls.0.first?.last) + #expect(calls.1 == [[1, 512]]) + } + @Test func jinaFactoryRegistrationUsesArchitecture() async throws { let model = try await LLMTypeRegistry.shared.createModel( configuration: try jinaConfigurationData(), modelType: "qwen3") @@ -957,6 +1052,38 @@ private final class TestEncoderRerankerModel: Module, RerankerModel, @unchecked } } +private final class TestFinalTokenRerankerModel: Module, CausalRerankerModel { + private let base: TestCausalRerankerModel + private(set) var projectedLengths = [[Int]]() + private(set) var fullForwardShapes = [[Int]]() + + init(tokenizer: ByteRerankerTokenizer) { + base = TestCausalRerankerModel( + trueTokenID: tokenizer.trueTokenID, falseTokenID: tokenizer.falseTokenID) + } + + func lastTokenLogits(_ inputs: MLXArray, sequenceLengths: [Int]) -> MLXArray { + projectedLengths.append(sequenceLengths) + let full = base(.init(tokens: inputs), cache: nil, state: nil).logits + return stacked(sequenceLengths.enumerated().map { row, length in full[row, length - 1] }) + } + + func prepare( + _ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters + ) throws -> PrepareResult { + .tokens(input.text) + } + + func callAsFunction( + _ input: LMInput.Text, cache: [KVCache]?, state: LMOutput.State? + ) -> LMOutput { + fullForwardShapes.append(input.tokens.shape) + return base(input, cache: cache, state: state) + } + + func newCache(parameters: GenerateParameters?) -> [KVCache] { [] } +} + private final class TestCausalRerankerModel: Module, LanguageModel, ListwiseRerankerModel, @unchecked Sendable { diff --git a/Tests/MLXLMTests/RoPEApplicationTests.swift b/Tests/MLXLMTests/RoPEApplicationTests.swift index 05aa3d08f6..b4548b495b 100644 --- a/Tests/MLXLMTests/RoPEApplicationTests.swift +++ b/Tests/MLXLMTests/RoPEApplicationTests.swift @@ -47,13 +47,18 @@ struct RoPEApplicationTests { eval(outputSeq) // With correct RoPE these would match. The buggy code would use - // different offsets for keys/queries. - let match = allClose(outputBatch, outputSeq, atol: 1e-4) + // different offsets for keys/queries. The tolerance is wider on + // machines whose float32 matmuls run as TF32; see MatmulPrecision. + let match = allClose( + outputBatch, outputSeq, + atol: MatmulPrecision.tolerance(float32: 1e-4, reduced: 5e-3)) eval(match) - print(outputBatch) - print(outputSeq) - print(abs(outputSeq - outputBatch)) - #expect(match.item(Bool.self)) + #expect( + match.item(Bool.self), + """ + batch and sequential attention differ by up to \ + \(abs(outputSeq - outputBatch).max().item(Float.self)) + """) } } } diff --git a/Tests/MLXLMTests/SSMTests.swift b/Tests/MLXLMTests/SSMTests.swift index bdf4e0f35a..8d34a1fa32 100644 --- a/Tests/MLXLMTests/SSMTests.swift +++ b/Tests/MLXLMTests/SSMTests.swift @@ -4,9 +4,15 @@ import MLX import MLXLLM import Testing +/// Compare two float32 results that differ only in how the work was split. +/// +/// The tolerances are wider on machines whose float32 matmuls run as TF32 — see +/// ``MatmulPrecision``. The message reports the worst element so a failure says how far off it +/// was, not just that it was. private func expectAllClose( - _ actual: MLXArray, _ expected: MLXArray, label: String, rtol: Double = 1e-4, - atol: Double = 1e-5 + _ actual: MLXArray, _ expected: MLXArray, label: String, + rtol: Double = MatmulPrecision.tolerance(float32: 1e-4, reduced: 5e-3), + atol: Double = MatmulPrecision.tolerance(float32: 1e-5, reduced: 5e-4) ) { guard actual.shape == expected.shape else { Issue.record("\(label) shape \(actual.shape) != \(expected.shape)") @@ -14,7 +20,7 @@ private func expectAllClose( } #expect( allClose(actual, expected, rtol: rtol, atol: atol).item(Bool.self), - "\(label) values differ") + "\(label) values differ by up to \(MLX.abs(actual - expected).max().item(Float.self))") } @Test func testSSMAttnChunkedMatchesUnchunkedValuesAndGradients() { @@ -81,7 +87,8 @@ private func expectAllClose( for (index, pair) in zip(chunkedGradients, referenceGradients).enumerated() { expectAllClose( pair.0, pair.1, label: "\(gradientLabels[index]) gradient (step \(step))", - rtol: 5e-4, atol: 5e-5) + rtol: MatmulPrecision.tolerance(float32: 5e-4, reduced: 5e-3), + atol: MatmulPrecision.tolerance(float32: 5e-5, reduced: 5e-4)) } } } diff --git a/Tests/MLXLMTests/SpecialTokenLabelScreenTests.swift b/Tests/MLXLMTests/SpecialTokenLabelScreenTests.swift new file mode 100644 index 0000000000..e82a30e90f --- /dev/null +++ b/Tests/MLXLMTests/SpecialTokenLabelScreenTests.swift @@ -0,0 +1,143 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXVLM +import Testing + +private struct SpecialTokenStubTokenizer: MLXLMCommon.Tokenizer { + let specials: [String] + + private static let scalarBase = 1_000_000 + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + var ids: [Int] = [] + var rest = Substring(text) + while let scalar = rest.unicodeScalars.first { + if let index = specials.firstIndex(where: { rest.hasPrefix($0) }) { + ids.append(index) + rest = rest.dropFirst(specials[index].count) + } else { + ids.append(Self.scalarBase + Int(scalar.value)) + rest = rest.dropFirst() + } + } + return ids + } + + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.compactMap { id -> String? in + if specials.indices.contains(id) { + return skipSpecialTokens ? nil : specials[id] + } + guard let scalar = Unicode.Scalar(UInt32(id - Self.scalarBase)) else { return nil } + return String(Character(scalar)) + } + .joined() + } + + func convertTokenToId(_ token: String) -> Int? { specials.firstIndex(of: token) } + + func convertIdToToken(_ id: Int) -> String? { + specials.indices.contains(id) ? specials[id] : nil + } + + var bosToken: String? { nil } + var eosToken: String? { nil } + var unknownToken: String? { nil } + + func applyChatTemplate( + messages: [[String: any Sendable]], + tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [] } +} + +private let mistralTokenizer = SpecialTokenStubTokenizer(specials: ["[IMG]", "[INST]"]) + +private func image(_ name: String, label: String?) -> UserInput.Image { + .url(URL(fileURLWithPath: "/tmp/\(name).png"), label: label) +} + +@Suite("Special-token label screen") +struct SpecialTokenLabelScreenTests { + + @Test("A label whose bracketed form is a special token is removed, and its image stays") + func specialTokenLabelsAreRemoved() { + let input = UserInput(chat: [ + .user( + "which one?", + images: [ + image("a", label: "IMG"), image("b", label: "receipt"), + image("c", label: "INST"), image("d", label: "IMG2"), + ]) + ]) + + let screened = input.removingSpecialTokenLabels(using: mistralTokenizer) + + #expect(screened.images.map(\.label) == [nil, "receipt", nil, "IMG2"]) + } + + @Test("A text prompt comes back unchanged") + func textPromptIsUnchanged() { + // `UserInput(prompt:images:)` builds a `.chat` prompt, so set `.text` directly. + var input = UserInput(prompt: "hello", images: [image("a", label: "IMG")]) + input.prompt = .text("hello") + + let screened = input.removingSpecialTokenLabels(using: mistralTokenizer) + + #expect(screened.images.map(\.label) == ["IMG"]) + } + + @Test("After the screen, the Mistral3 generator writes no [IMG] text part") + func screenedLabelNeverReachesThePrompt() throws { + let input = UserInput(chat: [ + .user("what is in this picture?", images: [image("a", label: "IMG")]) + ]) + + let messages = Mistral3MessageGenerator().generate( + from: input.removingSpecialTokenLabels(using: mistralTokenizer)) + + let content = try #require(messages.first?["content"] as? [[String: String]]) + #expect(content.filter { $0["type"] == "image" }.count == 1) + #expect(!content.contains { $0["text"] == "[IMG]" }) + } + + @Test("A configured generator gets screened labels too") + func configuredGeneratorPathIsScreened() async throws { + let delegate = CapturingUserInputProcessor() + let processor = MessageGeneratorUserInputProcessor( + processor: delegate, messageGenerator: Mistral3MessageGenerator(), + tokenizer: mistralTokenizer) + + _ = try await processor.prepare( + input: UserInput(chat: [ + .user("what is in this picture?", images: [image("a", label: "IMG")]) + ])) + + guard case .messages(let messages) = delegate.prompt else { + Issue.record("expected generated messages, got \(String(describing: delegate.prompt))") + return + } + let content = try #require(messages.first?["content"] as? [[String: String]]) + #expect(content.filter { $0["type"] == "image" }.count == 1) + #expect(!content.contains { $0["text"] == "[IMG]" }) + } +} + +/// `@unchecked Sendable` is safe only while `lock` guards every access to `storedPrompt`. +private final class CapturingUserInputProcessor: UserInputProcessor, @unchecked Sendable { + private let lock = NSLock() + private var storedPrompt: UserInput.Prompt? + + var prompt: UserInput.Prompt? { + lock.withLock { storedPrompt } + } + + func prepare(input: UserInput) async throws -> LMInput { + let prompt = input.prompt + lock.withLock { storedPrompt = prompt } + return LMInput(tokens: MLXArray([Int32(0)])) + } +} diff --git a/Tests/MLXLMTests/TokenIteratorClearCacheTests.swift b/Tests/MLXLMTests/TokenIteratorClearCacheTests.swift index 8368f077cf..bd052bba8a 100644 --- a/Tests/MLXLMTests/TokenIteratorClearCacheTests.swift +++ b/Tests/MLXLMTests/TokenIteratorClearCacheTests.swift @@ -30,6 +30,8 @@ final class TokenIteratorClearCacheTests: XCTestCase { do { let buffer = MLXArray.zeros([seeded], dtype: .uint8) + 1 eval(buffer) + // Wait for Metal completion handlers to release temporary buffers. + Stream.defaultStream.synchronize() } XCTAssertGreaterThanOrEqual(Memory.cacheMemory, seeded) diff --git a/Tests/MLXLMTests/ToolTests.swift b/Tests/MLXLMTests/ToolTests.swift index baccb1e9bb..058c2adf43 100644 --- a/Tests/MLXLMTests/ToolTests.swift +++ b/Tests/MLXLMTests/ToolTests.swift @@ -1441,6 +1441,320 @@ struct ToolTests { #expect(toolCall.function.arguments["seen"] == .string("false")) } + @Test("Gemma reads marker-quoted strings inside a nested object") + func testGemmaMarkerStringsInNestedObject() throws { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let content = + #"<|tool_call>call:fhir_search{resourceType:<|"|>Observation<|"|>,"# + + #"searchParams:{_count:<|"|>1<|"|>,_sort:<|"|>effective_datetime-1<|"|>}}"# + + #""# + + let toolCall = try #require(parser.parse(content: content, tools: Self.gemmaSearchTools)) + + #expect(toolCall.function.name == "fhir_search") + #expect(toolCall.function.arguments.count == 2) + #expect(toolCall.function.arguments["resourceType"] == .string("Observation")) + #expect( + toolCall.function.arguments["searchParams"] + == .object(["_count": .string("1"), "_sort": .string("effective_datetime-1")])) + } + + @Test("Gemma reads a single-key nested object with a marker-quoted string") + func testGemmaSingleKeyNestedObject() throws { + let value = try gemmaSearchParams(#"{name:<|"|>Maria Schneider<|"|>}"#) + + #expect(value == .object(["name": .string("Maria Schneider")])) + } + + @Test("Gemma reads marker-quoted keys inside nested objects") + func testGemmaMarkerQuotedNestedKeys() throws { + // The chat template writes keys bare, but the model sometimes marker-quotes them. + let value = try gemmaSearchParams( + #"{<|"|>given name<|"|>:<|"|>Maria<|"|>,"# + + #"filter:{<|"|>a b<|"|>:1,<|"|>code<|"|>:<|"|>8867-4<|"|>}}"#) + + #expect( + value + == .object([ + "given name": .string("Maria"), + "filter": .object(["a b": .int(1), "code": .string("8867-4")]), + ])) + } + + @Test( + "Gemma reads nested keys written with a marker or a leading space", + arguments: [ + #"{_count:<|"|>1<|"|>,<|"|>_sort<|"|>:<|"|>-effectiveDateTime<|"|>}"#, + #"{_count:<|"|>1<|"|>, _sort:<|"|>-effectiveDateTime<|"|>}"#, + ]) + func testGemmaNestedKeyVariantsFromModelOutput(_ body: String) throws { + // gemma-4-e2b-it wrote both shapes with thinking off; the template writes neither. + let value = try gemmaSearchParams(body) + + #expect(value == .object(["_count": .string("1"), "_sort": .string("-effectiveDateTime")])) + } + + @Test("Gemma trims a space before a top-level argument key") + func testGemmaTopLevelKeyAfterSpace() throws { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let tools = Self.gemmaTools("get_weather", ["city": "string", "days": "integer"]) + let content = #"<|tool_call>call:get_weather{city:<|"|>Paris<|"|>, days:3}"# + + let toolCall = try #require(parser.parse(content: content, tools: tools)) + + #expect(toolCall.function.arguments.count == 2) + #expect(toolCall.function.arguments["city"] == .string("Paris")) + #expect(toolCall.function.arguments["days"] == .int(3)) + } + + @Test( + "Gemma reads a marker-quoted top-level argument key", + arguments: [ + #"{<|"|>city<|"|>:<|"|>Paris<|"|>,days:3}"#, + #"{city:<|"|>Paris<|"|>, <|"|>days<|"|>:3}"#, + ]) + func testGemmaMarkerQuotedTopLevelKey(_ body: String) throws { + // The template writes keys bare. gemma-4-e2b-it marker-quoted a nested key in live + // output; the top level is read the same way, as transformers and mlx-lm do. + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let tools = Self.gemmaTools("get_weather", ["city": "string", "days": "integer"]) + let content = "<|tool_call>call:get_weather\(body)" + + let toolCall = try #require(parser.parse(content: content, tools: tools)) + + #expect(toolCall.function.arguments.count == 2) + #expect(toolCall.function.arguments["city"] == .string("Paris")) + #expect(toolCall.function.arguments["days"] == .int(3)) + } + + @Test("Gemma reads marker-quoted strings in an array nested several objects deep") + func testGemmaMarkerStringsInDeeplyNestedArray() throws { + let marker = #"<|"|>"# + let value = try gemmaSearchParams( + "{filter:{code:{any:[\(marker)8867-4\(marker),\(marker)line one\nline two\(marker)]}," + + "status:\(marker)final\(marker)}}") + + #expect( + value + == .object([ + "filter": .object([ + "code": .object([ + "any": .array([.string("8867-4"), .string("line one\nline two")]) + ]), + "status": .string("final"), + ]) + ])) + } + + @Test("Gemma reads marker-quoted strings inside an array of objects") + func testGemmaMarkerStringsInArrayOfObjects() throws { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let tools = Self.gemmaTools("record_vitals", ["entries": "array", "codes": "array"]) + let content = + #"<|tool_call>call:record_vitals{entries:["# + + #"{code:<|"|>8867-4<|"|>,unit:<|"|>/min<|"|>},"# + + #"{code:<|"|>8480-6<|"|>,unit:<|"|>mm[Hg]<|"|>}],"# + + #"codes:[<|"|>a,b<|"|>,<|"|>c<|"|>]}"# + + let toolCall = try #require(parser.parse(content: content, tools: tools)) + + #expect(toolCall.function.arguments.count == 2) + #expect( + toolCall.function.arguments["entries"] + == .array([ + .object(["code": .string("8867-4"), "unit": .string("/min")]), + .object(["code": .string("8480-6"), "unit": .string("mm[Hg]")]), + ])) + #expect(toolCall.function.arguments["codes"] == .array([.string("a,b"), .string("c")])) + } + + @Test("Gemma reads bare scalars and marker-quoted strings mixed in one nested object") + func testGemmaMixedScalarsAndMarkerStrings() throws { + let value = try gemmaSearchParams(#"{active:true,_count:5,name:<|"|>Maria<|"|>}"#) + + #expect( + value == .object(["active": .bool(true), "_count": .int(5), "name": .string("Maria")])) + } + + @Test("Gemma keeps a raw newline inside a nested marker-quoted string") + func testGemmaRawNewlineInNestedString() throws { + let marker = #"<|"|>"# + let value = try gemmaSearchParams("{note:\(marker)line one\nline two\(marker)}") + + #expect(value == .object(["note": .string("line one\nline two")])) + } + + @Test("Gemma keeps a raw tab inside a nested marker-quoted string") + func testGemmaRawTabInNestedString() throws { + let marker = #"<|"|>"# + let value = try gemmaSearchParams("{note:\(marker)dose\t5 mg\(marker)}") + + #expect(value == .object(["note": .string("dose\t5 mg")])) + } + + @Test( + "Gemma keeps other control characters inside a nested marker-quoted string", + arguments: [ + "\r", "\r\n", "\u{0}", "\u{1}", "\u{8}", "\u{B}", "\u{C}", "\u{1B}", "\u{1F}", "\u{7F}", + ]) + func testGemmaControlCharacterInNestedString(_ control: String) throws { + let marker = #"<|"|>"# + let value = try gemmaSearchParams("{note:\(marker)a\(control)b\(marker)}") + + #expect(value == .object(["note": .string("a\(control)b")])) + } + + @Test("Gemma keeps quotes, backslashes and protocol punctuation inside a nested string") + func testGemmaPunctuationInNestedString() throws { + let value = try gemmaSearchParams( + #"{q:<|"|>say "hi", C:\new\\dir {x:1}, [a]: \u0041<|"|>}"#) + + #expect(value == .object(["q": .string(#"say "hi", C:\new\\dir {x:1}, [a]: \u0041"#)])) + } + + @Test("Gemma keeps empty and backslash-ended strings inside a nested object") + func testGemmaEmptyAndTrailingBackslashInNestedString() throws { + let value = try gemmaSearchParams(#"{a:<|"|><|"|>,b:<|"|>C:\<|"|>,c:<|"|>\\<|"|>}"#) + + #expect( + value == .object(["a": .string(""), "b": .string(#"C:\"#), "c": .string(#"\\"#)])) + } + + @Test("Gemma keeps non-ASCII text inside a nested marker-quoted string") + func testGemmaNonASCIIInNestedString() throws { + let value = try gemmaSearchParams(#"{name:<|"|>Jürgen Groß, Straße 5 🩺<|"|>}"#) + + #expect(value == .object(["name": .string("Jürgen Groß, Straße 5 🩺")])) + } + + @Test("FunctionGemma reads escape-marker strings inside a nested object") + func testFunctionGemmaNestedEscapeStrings() throws { + let parser = GemmaFunctionParser( + startTag: "", endTag: "", + escapeMarker: "") + let content = + "call:f{p:{a:x, y\nz,n:2}}" + + let toolCall = try #require(parser.parse(content: content, tools: nil)) + + #expect( + toolCall.function.arguments["p"] == .object(["a": .string("x, y\nz"), "n": .int(2)])) + } + + @Test( + "FunctionGemma keeps escape markers inside JSON-quoted nested strings", + arguments: [ + (#"{"a":"xyz"}"#, "xyz"), + (#"{a:"hi"}"#, "hi"), + ]) + func testFunctionGemmaMarkersInsideQuotedString(_ literal: String, _ expected: String) throws { + // Not in the dialect. Pins that text which already parses is read before any rewrite. + let parser = GemmaFunctionParser( + startTag: "", endTag: "", + escapeMarker: "") + let content = "call:f{p:\(literal)}" + + let toolCall = try #require(parser.parse(content: content, tools: nil)) + + #expect(toolCall.function.arguments["p"] == .object(["a": .string(expected)])) + } + + @Test( + "FunctionGemma keeps the text of a brace value with an unpaired escape marker", + arguments: [ + #"{a:"",b:yes}"#, + #"{a:"xy",b:yes}"#, + ]) + func testFunctionGemmaUnpairedEscapeMarker(_ literal: String) throws { + let parser = GemmaFunctionParser( + startTag: "", endTag: "", + escapeMarker: "") + let content = "call:f{p:\(literal)}" + + let toolCall = try #require(parser.parse(content: content, tools: nil)) + + // Malformed input. The last marker has no partner and `yes` is not JSON, + // so the raw text is kept. + #expect(toolCall.function.arguments.count == 1) + #expect(toolCall.function.arguments["p"] == .string(literal)) + } + + @Test("FunctionGemma quotes a paired marker and keeps an unpaired one that follows") + func testFunctionGemmaUnpairedMarkerAfterPairedString() throws { + let parser = GemmaFunctionParser( + startTag: "", endTag: "", + escapeMarker: "") + let literal = #"{a:x,b:""}"# + let content = "call:f{p:\(literal)}" + + let toolCall = try #require(parser.parse(content: content, tools: nil)) + + // Malformed input. The text after the unpaired marker is kept as is, + // so `b` stays a JSON string. + #expect( + toolCall.function.arguments["p"] + == .object(["a": .string("x"), "b": .string("")])) + } + + @Test("Gemma reads a nested marker-quoted object without a tool schema") + func testGemmaNestedMarkerObjectWithoutSchema() throws { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let content = + #"<|tool_call>call:fhir_search{searchParams:{_count:<|"|>1<|"|>,_sort:<|"|>x<|"|>}}"# + + #""# + + let toolCall = try #require(parser.parse(content: content, tools: nil)) + + #expect(toolCall.function.arguments.count == 1) + #expect( + toolCall.function.arguments["searchParams"] + == .object(["_count": .string("1"), "_sort": .string("x")])) + } + + @Test("Gemma keeps the raw text of a brace value the schema declares a string") + func testGemmaStringParameterKeepsRawBraceText() throws { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + // The template would marker-quote a string value. This pins that a string + // parameter keeps raw brace text and skips the rewrite. + let tools = Self.gemmaTools("annotate", ["payload": "string"]) + let raw = #"{note:<|"|>a<|"|>}"# + let content = "<|tool_call>call:annotate{payload:\(raw)}" + + let toolCall = try #require(parser.parse(content: content, tools: tools)) + + #expect(toolCall.function.arguments["payload"] == .string(raw)) + } + + @Test("Gemma 4 processor reads a streamed nested marker-quoted object") + func testGemma4ProcessorStreamedNestedMarkerObject() throws { + let processor = ToolCallProcessor(format: .gemma4, tools: Self.gemmaSearchTools) + let marker = #"<|"|>"# + let content = + "<|tool_call>call:fhir_search{resourceType:\(marker)Observation\(marker)," + + "searchParams:{_count:\(marker)1\(marker)," + + "note:\(marker)line one\nline two\(marker)}}" + + var visible = "" + for character in content { + if let text = processor.processChunk(String(character)) { visible += text } + } + processor.processEOS() + + #expect(visible.isEmpty) + #expect(processor.toolCalls.count == 1) + let toolCall = try #require(processor.toolCalls.first) + #expect(toolCall.function.arguments["resourceType"] == .string("Observation")) + #expect( + toolCall.function.arguments["searchParams"] + == .object(["_count": .string("1"), "note": .string("line one\nline two")])) + } + @Test("Test Gemma 4 Format via ToolCallProcessor") func testGemma4FormatProcessor() throws { let processor = ToolCallProcessor(format: .gemma4) @@ -1474,6 +1788,36 @@ struct ToolTests { #expect(toolCall.function.arguments["expression"] == .string("2+2")) } + private static func gemmaTools( + _ name: String, _ properties: [String: String] + ) -> [[String: any Sendable]] { + [ + [ + "function": [ + "name": name, + "parameters": [ + "type": "object", + "properties": properties.mapValues { + ["type": $0] as [String: any Sendable] + } as [String: any Sendable], + ] as [String: any Sendable], + ] as [String: any Sendable] + ] + ] + } + + private static let gemmaSearchTools = gemmaTools( + "fhir_search", ["resourceType": "string", "searchParams": "object"]) + + /// Parses a Gemma 4 `fhir_search` call and returns its `searchParams` argument. + private func gemmaSearchParams(_ body: String) throws -> JSONValue? { + let parser = GemmaFunctionParser( + startTag: "<|tool_call>", endTag: "", escapeMarker: #"<|"|>"#) + let content = "<|tool_call>call:fhir_search{searchParams:\(body)}" + let toolCall = try #require(parser.parse(content: content, tools: Self.gemmaSearchTools)) + return toolCall.function.arguments["searchParams"] + } + // MARK: - Kimi K2 Format Tests @Test("Test Kimi K2 Tool Call Parser") diff --git a/Tests/MLXLMTests/TurboQuantTests.swift b/Tests/MLXLMTests/TurboQuantTests.swift index 38e385ade2..807d63181f 100644 --- a/Tests/MLXLMTests/TurboQuantTests.swift +++ b/Tests/MLXLMTests/TurboQuantTests.swift @@ -203,10 +203,12 @@ struct TurboQuantMSECodecTests { let codec = MSECodec(dim: 128, bits: 3, seed: 42) #expect(codec.useWHT, "dim=128 should use WHT") - let product = matmul(codec.rotation, codec.rotationT) + let product = matmul(codec.rotation, codec.rotationT, stream: .cpu) let identity = MLXArray.identity(128) let diff = MLX.abs(product - identity).max().item(Float.self) - #expect(diff < 1e-4, "WHT rotation should be orthogonal, max diff: \(diff)") + // TF32 matmuls (neural accelerators) leave ~2e-4 here; see MatmulPrecision. + let tolerance: Float = MatmulPrecision.tolerance(float32: 1e-4, reduced: 1e-3) + #expect(diff < tolerance, "WHT rotation should be orthogonal, max diff: \(diff)") } @Test func whtEncodeDecodeRoundTrip() { @@ -394,6 +396,38 @@ struct TurboQuantKVCacheTests { "State should have 2 or 4 arrays, got \(state.count)") } + /// Regression test: the cache inherited an empty `innerState()`, so `eval(cache)` + /// skipped its buffers and `KVCacheStatus` counted zero bytes for it. + @Test func cacheInnerStateHoldsRawAndCompressedStorage() { + let cache = TurboQuantKVCache(bits: 4) + let B = 1 + let H = 2 + let D = 128 + + let keys = MLXRandom.normal([B, H, 4, D]) + let values = MLXRandom.normal([B, H, 4, D]) + eval(keys, values) + _ = cache.update(keys: keys, values: values) + + // Prefill keeps raw keys and values in 256-row steps. + let rawBytes = 2 * (B * H * 256 * D) * 4 + #expect(KVCacheStatus(cache: [cache]).memoryBytes == rawBytes) + + let newKey = MLXRandom.normal([B, H, 1, D]) + let newValue = MLXRandom.normal([B, H, 1, D]) + let queries = MLXRandom.normal([B, H * 2, 1, D]) + eval(newKey, newValue, queries) + eval( + cache.compressedAttention( + queries: queries, keys: newKey, values: newValue, + scale: 1.0 / sqrt(Float(D)))) + + #expect(cache.isCompressed) + let compressedBytes = KVCacheStatus(cache: [cache]).memoryBytes + #expect(compressedBytes == cache.memoryBytes) + #expect(compressedBytes > 0 && compressedBytes < rawBytes) + } + @Test func cacheIsTrimmable() { let cache = TurboQuantKVCache(bits: 4) #expect(cache.isTrimmable == true) diff --git a/Tests/MLXLMTests/UserInputAudioTests.swift b/Tests/MLXLMTests/UserInputAudioTests.swift new file mode 100644 index 0000000000..e5e599876b --- /dev/null +++ b/Tests/MLXLMTests/UserInputAudioTests.swift @@ -0,0 +1,72 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import Testing + +@Suite("UserInput.Audio source") +struct UserInputAudioTests { + + @Test("The url factory makes a url source") + func urlFactoryMakesAURLSource() { + let audio = UserInput.Audio.url(URL(fileURLWithPath: "/tmp/example.wav")) + guard case .url(let url) = audio.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/example.wav") + } + + @Test("The array factory makes an array source") + func arrayFactoryMakesAnArraySource() { + let audio = UserInput.Audio.array(MLXArray([0.25, -0.5, 1] as [Float])) + guard case .array(let array) = audio.source else { + Issue.record("expected an array source") + return + } + #expect(array.asArray(Float.self) == [0.25, -0.5, 1]) + } + + @Test("A factory works as an implicit member") + func factoryWorksAsAnImplicitMember() { + let audio: UserInput.Audio = .url(URL(fileURLWithPath: "/tmp/implicit.wav")) + guard case .url(let url) = audio.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/implicit.wav") + } + + @Test("A factory can be passed where a function of one argument is expected") + func factoryWorksAsAFunctionValue() { + let urls = [URL(fileURLWithPath: "/tmp/a.wav"), URL(fileURLWithPath: "/tmp/b.wav")] + let audios = urls.map(UserInput.Audio.url) + let paths = audios.compactMap { audio -> String? in + guard case .url(let url) = audio.source else { return nil } + return url.path + } + #expect(paths == ["/tmp/a.wav", "/tmp/b.wav"]) + } + + @Test("A factory works as a function value without a type context") + func factoryWorksWithoutATypeContext() { + let make = UserInput.Audio.url + let audio = make(URL(fileURLWithPath: "/tmp/bare.wav")) + guard case .url(let url) = audio.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/bare.wav") + } + + @Test("The initializer stores the source") + func initializerStoresTheSource() { + let audio = UserInput.Audio(source: .url(URL(fileURLWithPath: "/tmp/init.wav"))) + guard case .url(let url) = audio.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/init.wav") + } +} diff --git a/Tests/MLXLMTests/UserInputImageTests.swift b/Tests/MLXLMTests/UserInputImageTests.swift new file mode 100644 index 0000000000..58d6daa694 --- /dev/null +++ b/Tests/MLXLMTests/UserInputImageTests.swift @@ -0,0 +1,69 @@ +// Copyright © 2026 Apple Inc. + +import CoreImage +import Foundation +import MLX +import MLXLMCommon +import Testing + +@Suite("UserInput.Image label") +struct UserInputImageTests { + + @Test("A URL image defaults to no label") + func urlImageHasNoLabelByDefault() { + let image = UserInput.Image.url(URL(fileURLWithPath: "/tmp/example.png")) + #expect(image.label == nil) + guard case .url(let url) = image.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/example.png") + } + + @Test("A factory carries the label through to the value") + func factoryCarriesTheLabel() { + let image = UserInput.Image.url( + URL(fileURLWithPath: "/tmp/example.png"), label: "Photo_A1B2C3") + #expect(image.label == "Photo_A1B2C3") + } + + @Test("A CIImage source round-trips through asCIImage") + func ciImageSourceRoundTrips() throws { + let source = CIImage(color: .red).cropped(to: CGRect(x: 0, y: 0, width: 4, height: 2)) + let image = UserInput.Image.ciImage(source, label: "A") + let recovered = try image.asCIImage() + #expect(recovered.extent.width == 4) + #expect(recovered.extent.height == 2) + #expect(image.label == "A") + } + + @Test("An array source becomes an image of the same size") + func arraySourceBecomesAnImage() throws { + let array = MLXArray.ones([3, 3, 4]) * 255 + let image = UserInput.Image.array(array) + let recovered = try image.asCIImage() + #expect(recovered.extent.width == 4) + #expect(recovered.extent.height == 3) + #expect(image.label == nil) + } + + @Test("A factory can be passed where a function of one argument is expected") + func factoryWorksAsAFunctionValue() { + let urls = [URL(fileURLWithPath: "/tmp/a.png"), URL(fileURLWithPath: "/tmp/b.png")] + let images = urls.map(UserInput.Image.url) + #expect(images.count == 2) + #expect(images.allSatisfy { $0.label == nil }) + let paths = images.compactMap { image -> String? in + guard case .url(let url) = image.source else { return nil } + return url.path + } + #expect(paths == ["/tmp/a.png", "/tmp/b.png"]) + } + + @Test("A label can be set after construction") + func labelIsMutable() { + var image = UserInput.Image.url(URL(fileURLWithPath: "/tmp/example.png")) + image.label = "B" + #expect(image.label == "B") + } +} diff --git a/Tests/MLXLMTests/UserInputVideoTests.swift b/Tests/MLXLMTests/UserInputVideoTests.swift new file mode 100644 index 0000000000..fd1fd88726 --- /dev/null +++ b/Tests/MLXLMTests/UserInputVideoTests.swift @@ -0,0 +1,88 @@ +// Copyright © 2026 Apple Inc. + +import AVFoundation +import CoreMedia +import Foundation +import MLXLMCommon +import Testing + +@Suite("UserInput.Video source") +struct UserInputVideoTests { + + @Test("The url factory makes a url source") + func urlFactoryMakesAURLSource() { + let video = UserInput.Video.url(URL(fileURLWithPath: "/tmp/example.mov")) + guard case .url(let url) = video.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/example.mov") + } + + @Test("The avAsset factory makes an avAsset source") + func avAssetFactoryMakesAnAVAssetSource() { + let asset = AVURLAsset(url: URL(fileURLWithPath: "/tmp/asset.mov")) + let video = UserInput.Video.avAsset(asset) + guard case .avAsset(let sourceAsset) = video.source else { + Issue.record("expected an avAsset source") + return + } + #expect((sourceAsset as? AVURLAsset)?.url.path == "/tmp/asset.mov") + } + + @Test("The frames factory makes a frames source") + func framesFactoryMakesAFramesSource() { + let frame = UserInput.VideoFrame( + image: .url(URL(fileURLWithPath: "/tmp/frame.png")), + timeStamp: CMTime(value: 1200, timescale: 600)) + let video = UserInput.Video.frames([frame]) + guard case .frames(let frames) = video.source else { + Issue.record("expected a frames source") + return + } + #expect(frames.count == 1) + #expect(frames.first?.timeStamp.seconds == 2) + } + + @Test("A factory works as an implicit member") + func factoryWorksAsAnImplicitMember() { + let video: UserInput.Video = .url(URL(fileURLWithPath: "/tmp/implicit.mov")) + guard case .url(let url) = video.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/implicit.mov") + } + + @Test("A factory can be passed where a function of one argument is expected") + func factoryWorksAsAFunctionValue() { + let urls = [URL(fileURLWithPath: "/tmp/a.mov"), URL(fileURLWithPath: "/tmp/b.mov")] + let videos = urls.map(UserInput.Video.url) + let paths = videos.compactMap { video -> String? in + guard case .url(let url) = video.source else { return nil } + return url.path + } + #expect(paths == ["/tmp/a.mov", "/tmp/b.mov"]) + } + + @Test("A factory works as a function value without a type context") + func factoryWorksWithoutATypeContext() { + let make = UserInput.Video.url + let video = make(URL(fileURLWithPath: "/tmp/bare.mov")) + guard case .url(let url) = video.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/bare.mov") + } + + @Test("The initializer stores the source") + func initializerStoresTheSource() { + let video = UserInput.Video(source: .url(URL(fileURLWithPath: "/tmp/init.mov"))) + guard case .url(let url) = video.source else { + Issue.record("expected a url source") + return + } + #expect(url.path == "/tmp/init.mov") + } +} diff --git a/Tests/MLXLMTests/VLMImageTokenMismatchTests.swift b/Tests/MLXLMTests/VLMImageTokenMismatchTests.swift new file mode 100644 index 0000000000..069f3184a1 --- /dev/null +++ b/Tests/MLXLMTests/VLMImageTokenMismatchTests.swift @@ -0,0 +1,114 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import Testing + +@testable import MLXVLM + +struct VLMImageTokenMismatchTests { + + private static func makeTinyMistral3() throws -> Mistral3VLM { + let json = """ + { + "model_type": "mistral3", + "image_token_index": 10, + "spatial_merge_size": 1, + "vision_feature_layer": -1, + "text_config": { + "model_type": "mistral", + "hidden_size": 32, + "num_hidden_layers": 2, + "intermediate_size": 64, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 16, + "rms_norm_eps": 1e-5, + "vocab_size": 100, + "max_position_embeddings": 512, + "rope_parameters": { "rope_theta": 10000.0 } + }, + "vision_config": { + "model_type": "pixtral", + "hidden_size": 32, + "num_hidden_layers": 1, + "num_attention_heads": 2, + "intermediate_size": 64, + "patch_size": 8, + "image_size": 32 + } + } + """ + let config = try JSONDecoder().decode( + Mistral3VLMConfiguration.self, from: Data(json.utf8)) + return withRandomState(MLXRandom.RandomState(seed: 42)) { + Mistral3VLM(config) + } + } + + @Test("Mistral3 raises rather than aborting when the counts disagree") + func mistral3RaisesOnMismatch() throws { + let model = try Self.makeTinyMistral3() + let tokens = MLXArray([Int32(1), 10, 2]).expandedDimensions(axis: 0) + let pixels = MLXRandom.normal([1, 3, 16, 16]).asType(.float32) + let input = LMInput( + text: .init(tokens: tokens), + image: .init(pixels: pixels, frames: [.init(1, 16, 16)])) + + #expect(throws: VLMError.self) { + _ = try model.prepare( + input, cache: try model.newCache(parameters: nil), state: nil, + prefill: .init(stepSize: 512)) + } + } + + private static func makeTinyLFM2VL() throws -> LFM2VL { + let json = """ + { + "model_type": "lfm2-vl", + "downsample_factor": 1, + "projector_hidden_size": 32, + "projector_use_layernorm": false, + "text_config": { + "model_type": "lfm2", + "hidden_size": 32, + "num_hidden_layers": 2, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "vocab_size": 500 + }, + "vision_config": { + "model_type": "siglip2_navit", + "hidden_size": 32, + "intermediate_size": 64, + "num_hidden_layers": 1, + "num_attention_heads": 2, + "patch_size": 8, + "image_size": 32 + } + } + """ + let config = try JSONDecoder().decode( + LFM2VLConfiguration.self, from: Data(json.utf8)) + return withRandomState(MLXRandom.RandomState(seed: 42)) { + LFM2VL(config) + } + } + + @Test("LFM2VL raises rather than aborting when the counts disagree") + func lfm2vlRaisesOnMismatch() throws { + let model = try Self.makeTinyLFM2VL() + let tokens = MLXArray([Int32(1), 396, 2]).expandedDimensions(axis: 0) + let pixels = MLXRandom.normal([1, 4, 3 * 8 * 8]).asType(.float32) + let input = LMInput( + text: .init(tokens: tokens), + image: .init(pixels: pixels, frames: [.init(1, 2, 2)])) + + #expect(throws: VLMError.self) { + _ = try model.prepare( + input, cache: try model.newCache(parameters: nil), state: nil, + prefill: .init(stepSize: 512)) + } + } +} diff --git a/skills/mlx-swift-lm/SKILL.md b/skills/mlx-swift-lm/SKILL.md index 395afa3187..c2256c3754 100644 --- a/skills/mlx-swift-lm/SKILL.md +++ b/skills/mlx-swift-lm/SKILL.md @@ -63,14 +63,16 @@ MLXEmbedders - Embedding models and pooling utilities ### LLM Chat (Simplest API) ```swift +import Foundation import MLXLLM import MLXLMCommon -import MLXLMHuggingFace // from swift-huggingface-mlx -import MLXLMTokenizers // from swift-tokenizers-mlx +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace // HubClient (used by the macros) +import Tokenizers // AutoTokenizer (used by the tokenizer-loader macro) let modelContainer = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Qwen3-4B-4bit") ) @@ -87,14 +89,16 @@ for try await chunk in session.streamResponse(to: "Explain structured concurrenc ### VLM with Image ```swift +import Foundation import MLXVLM import MLXLMCommon -import MLXLMHuggingFace // from swift-huggingface-mlx -import MLXLMTokenizers // from swift-tokenizers-mlx +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace +import Tokenizers let modelContainer = try await VLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Qwen2-VL-2B-Instruct-4bit") ) @@ -111,23 +115,28 @@ let response = try await session.respond( ### Embeddings ```swift +import Foundation +import MLX import MLXEmbedders -import MLXEmbeddersHuggingFace // from swift-huggingface-mlx -import MLXLMTokenizers // from swift-tokenizers-mlx +import MLXLMCommon +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace +import Tokenizers -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), +let container = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: ModelConfiguration(id: "mlx-community/bge-small-en-v1.5-mlx") ) -let embeddings = await container.perform { model, tokenizer, pooler in - let tokens = tokenizer.encode(text: "Hello world") +let embeddings = await container.perform { context in + let tokens = context.tokenizer.encode(text: "Hello world") let input = MLXArray(tokens).expandedDimensions(axis: 0) - let output = model(input) - let pooled = pooler(output, normalize: true) + let output = context.model( + input, positionIds: nil, tokenTypeIds: nil, attentionMask: nil) + let pooled = context.pooling(output, normalize: true) eval(pooled) - return pooled + return pooled.asArray(Float.self) // MLXArray is not Sendable; convert before returning } ``` @@ -304,7 +313,7 @@ let response = try await session.respond(to: "What happens in this video?", vide ```swift let images: [UserInput.Image] = [.url(url1), .url(url2)] -let response = try await session.respond(to: "Compare these two images", images: images, videos: []) +let response = try await session.respond(to: "Compare these two images", images: images, videos: [], audios: []) ``` ### VLM-Specific Processing @@ -366,7 +375,7 @@ for await item in stream { - `ModelContainer` is `Sendable` and thread-safe. - `ChatSession` is not thread-safe; use one session per task/flow. -- `MLXArray` is not `Sendable`; keep it inside one isolation domain or use `SendableBox` transfer patterns. +- `MLXArray` is not `Sendable`; keep it inside one isolation domain, or `eval` and convert to a Sendable value (e.g. `asArray(Float.self)`) before crossing isolation boundaries. ### Memory Management diff --git a/skills/mlx-swift-lm/references/concurrency.md b/skills/mlx-swift-lm/references/concurrency.md index 24d4d757d5..1587405b2d 100644 --- a/skills/mlx-swift-lm/references/concurrency.md +++ b/skills/mlx-swift-lm/references/concurrency.md @@ -16,6 +16,13 @@ mlx-swift-lm uses Swift concurrency with specialized utilities to handle the uni | `ModelContainer` | Thread-safe model wrapper (uses SerialAccessContainer) | | `ChatSession` | NOT thread-safe (single task only) | +> **Note:** `SerialAccessContainer`, `SendableBox`, and `AsyncMutex` are **internal** +> (`package`/`private`) implementation details — they are not part of the public API and +> cannot be referenced from a consuming module. `ModelContainer`/`EmbedderModelContainer` +> already use them internally; for your own code, prefer those wrappers or reproduce the +> pattern with your own type. The snippets below are illustrative of the pattern, not calls +> you can make against the framework. + ## SerialAccessContainer Provides exclusive access to state across `async` calls: @@ -129,8 +136,8 @@ public final class ModelContainer: Sendable { ```swift // Multiple tasks can call perform() safely let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), id: "mlx-community/Qwen3-4B-4bit" ) @@ -316,7 +323,7 @@ asyncEval(nextToken) // Starts computation, doesn't wait eval(result) // Waits for completion // Stream synchronize -Stream().synchronize() // Wait for all pending operations +Stream.defaultStream.synchronize() // Wait for all pending operations ``` ## Task Cancellation Best Practices diff --git a/skills/mlx-swift-lm/references/embeddings.md b/skills/mlx-swift-lm/references/embeddings.md index bf81529ffc..599dfc73f4 100644 --- a/skills/mlx-swift-lm/references/embeddings.md +++ b/skills/mlx-swift-lm/references/embeddings.md @@ -7,8 +7,8 @@ The Embedders library provides text embedding models for semantic search, RAG, c **Files:** - `Libraries/MLXEmbedders/EmbeddingModel.swift` - `Libraries/MLXEmbedders/Pooling.swift` -- `Libraries/MLXEmbedders/Models.swift` -- `Libraries/MLXEmbedders/Load.swift` +- `Libraries/MLXEmbedders/ModelFactory.swift` +- `Libraries/MLXEmbedders/EmbedderModelContainer.swift` - `Libraries/MLXEmbedders/Models/Bert.swift` - `Libraries/MLXEmbedders/Models/NomicBert.swift` @@ -17,8 +17,11 @@ The Embedders library provides text embedding models for semantic search, RAG, c | Type | Purpose | |------|---------| | `EmbeddingModel` | Protocol for embedding models | -| `ModelContainer` | Thread-safe embedding model wrapper | -| `ModelConfiguration` | Model ID and settings | +| `EmbedderModelFactory` | Loads embedder models/containers (use `.shared`) | +| `EmbedderModelContainer` | Thread-safe embedder wrapper; `perform` hands you an `EmbedderModelContext` | +| `EmbedderModelContext` | Holds `configuration`, `model`, `tokenizer`, `pooling` | +| `EmbedderRegistry` | Registry of pre-registered embedder `ModelConfiguration`s | +| `ModelConfiguration` | Model ID and settings (from `MLXLMCommon`) | | `Pooling` | Pooling strategies for embeddings | | `Pooling.Strategy` | mean, cls, first, last, max, none | | `EmbeddingModelOutput` | Hidden states and pooled output | @@ -48,12 +51,18 @@ The Embedders library provides text embedding models for semantic search, RAG, c ### Using Pre-registered Configuration ```swift +import Foundation +import MLX import MLXEmbedders - -let config = ModelConfiguration.bge_small -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) +import MLXLMCommon +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace +import Tokenizers + +let config = EmbedderRegistry.bge_small +let container = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config ) ``` @@ -62,9 +71,9 @@ let container = try await loadModelContainer( ```swift let config = ModelConfiguration(id: "BAAI/bge-small-en-v1.5") -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), +let container = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config ) ``` @@ -72,18 +81,18 @@ let container = try await loadModelContainer( ### From Local Directory ```swift -let container = try await loadModelContainer( +let container = try await EmbedderModelFactory.shared.loadContainer( from: localModelURL, - using: TokenizersLoader() + using: #huggingFaceTokenizerLoader() ) ``` ### With Progress Tracking ```swift -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), +let container = try await EmbedderModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config ) { progress in print("Download progress: \(progress.fractionCompleted)") @@ -95,21 +104,23 @@ let container = try await loadModelContainer( ### Basic Usage ```swift -let container: ModelContainer = ... +let container: EmbedderModelContainer = ... -let embedding = await container.perform { model, tokenizer, pooler in +let embedding = await container.perform { context in // Encode text - let tokens = tokenizer.encode(text: "Hello world") + let tokens = context.tokenizer.encode(text: "Hello world") let input = MLXArray(tokens).expandedDimensions(axis: 0) // Get model output - let output = model(input) + let output = context.model( + input, positionIds: nil, tokenTypeIds: nil, attentionMask: nil) // Pool to single vector - let pooled = pooler(output, normalize: true) + let pooled = context.pooling(output, normalize: true) eval(pooled) - return pooled + // MLXArray is not Sendable; convert before returning from perform + return pooled.asArray(Float.self) } ``` @@ -118,9 +129,9 @@ let embedding = await container.perform { model, tokenizer, pooler in ```swift let texts = ["First text", "Second text", "Third text"] -let embeddings = await container.perform { model, tokenizer, pooler in +let embeddings = await container.perform { context in // Encode all texts - let tokensList = texts.map { tokenizer.encode(text: $0) } + let tokensList = texts.map { context.tokenizer.encode(text: $0) } let maxLen = tokensList.map { $0.count }.max() ?? 0 // Pad to same length @@ -133,17 +144,19 @@ let embeddings = await container.perform { model, tokenizer, pooler in Array(repeating: 0.0, count: padding.count)) } - let input = MLXArray(padded) - let attentionMask = MLXArray(mask) + let input = MLXArray(padded.flatMap { $0 }, [padded.count, maxLen]) + let attentionMask = MLXArray(mask.flatMap { $0 }, [mask.count, maxLen]) // Forward pass - let output = model(input, attentionMask: attentionMask) + let output = context.model( + input, positionIds: nil, tokenTypeIds: nil, attentionMask: attentionMask) // Pool - let pooled = pooler(output, mask: attentionMask, normalize: true) + let pooled = context.pooling(output, mask: attentionMask, normalize: true) eval(pooled) - return pooled + // MLXArray is not Sendable; convert to a Sendable value before returning + return pooled.map { $0.asArray(Float.self) } } ``` @@ -165,14 +178,15 @@ public enum Strategy { ### Custom Pooling ```swift -// Create custom pooler +// Create a custom pooler let pooler = Pooling(strategy: .mean, dimension: 384) - -// Or from configuration file -let pooler = loadPooling(modelDirectory: modelDir) -// Reads from 1_Pooling/config.json ``` +The factory loads the model's own pooling automatically (from `1_Pooling/config.json`, +falling back to the model's built-in strategy), exposed as `context.pooling`. The +`loadPooling(modelDirectory:model:)` helper that does this is module-internal — use +`context.pooling` rather than calling it directly. + ### Pooling Options ```swift @@ -187,22 +201,27 @@ let pooled = pooler( ## EmbeddingModel Protocol ```swift -public protocol EmbeddingModel: Module { +public protocol EmbeddingModel: BaseLanguageModel { var vocabularySize: Int { get } + /// Pooling strategy declared by the model (default: nil). + var poolingStrategy: Pooling.Strategy? { get } + + /// Max position embeddings, or nil for length-agnostic encodings (e.g. RoPE). + /// Inputs longer than this are truncated internally with a warning. + var maxPositionEmbeddings: Int? { get } + func callAsFunction( _ inputs: MLXArray, positionIds: MLXArray?, tokenTypeIds: MLXArray?, attentionMask: MLXArray? ) -> EmbeddingModelOutput - - func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] } public struct EmbeddingModelOutput { - let hiddenStates: MLXArray? // [batch, seq_len, hidden] - let pooledOutput: MLXArray? // [batch, hidden] (CLS pooling) + public let hiddenStates: MLXArray? // [batch, seq_len, hidden] + public let pooledOutput: MLXArray? // [batch, hidden] (CLS pooling) } ``` @@ -257,31 +276,40 @@ print("Similarity: \(similarity)") // ~0.85 ## Model Configuration +Embedders reuse `MLXLMCommon.ModelConfiguration` (embedding-irrelevant properties such as +`extraEOSTokens` are simply ignored): + ```swift public struct ModelConfiguration: Sendable { public enum Identifier: Sendable { - case id(String) // HuggingFace ID - case directory(URL) // Local path + case id(String, revision: String = "main") // HuggingFace ID + case directory(URL) // Local path } public var id: Identifier - public var name: String - public let tokenizerId: String? // Alternate tokenizer - public let overrideTokenizer: String? // Override tokenizer class + public var name: String { get } // repo id or path-based name + public let tokenizerSource: TokenizerSource? // load tokenizer from a different source + // ...LLM/VLM-specific fields (defaultPrompt, extraEOSTokens, ...) are ignored by embedders } ``` ### Registry +Pre-registered embedders live on `EmbedderRegistry`; lookups go through +`EmbedderRegistry.shared`: + ```swift -// Get registered model -let config = await ModelConfiguration.configuration(id: "bge-small") +// Pre-registered configuration +let config = EmbedderRegistry.bge_small + +// Get a registered model by id +let configByID = EmbedderRegistry.shared.configuration(id: "BAAI/bge-small-en-v1.5") // List all models -let models = await ModelConfiguration.models +let models = EmbedderRegistry.shared.models -// Register custom model -await ModelConfiguration.register(configurations: [myConfig]) +// Register custom models +EmbedderRegistry.shared.register(configurations: [myConfig]) ``` ## Supported Architectures diff --git a/skills/mlx-swift-lm/references/generation.md b/skills/mlx-swift-lm/references/generation.md index 1457c26ceb..36e4c2d9c0 100644 --- a/skills/mlx-swift-lm/references/generation.md +++ b/skills/mlx-swift-lm/references/generation.md @@ -22,10 +22,16 @@ Primary implementation lives in `Libraries/MLXLMCommon/Evaluate.swift`. ## Decoded Text/Tool Streaming ```swift +import Foundation import MLXLLM import MLXLMCommon +import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader +import HuggingFace +import Tokenizers let context = try await LLMModelFactory.shared.load( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Qwen3-4B-4bit") ) @@ -40,6 +46,8 @@ for await event in stream { print(text, terminator: "") case .toolCall(let call): print("\nTool requested: \(call.function.name)") + case .rejectedToolCall(let rejected): + print("\nRejected tool call: \(rejected.reason)") case .info(let info): print("\nstop=\(info.stopReason) tok/s=\(info.tokensPerSecond)") } diff --git a/skills/mlx-swift-lm/references/kv-cache.md b/skills/mlx-swift-lm/references/kv-cache.md index 98a0ef3b47..58fa6e7902 100644 --- a/skills/mlx-swift-lm/references/kv-cache.md +++ b/skills/mlx-swift-lm/references/kv-cache.md @@ -132,8 +132,11 @@ case .ignored: break // attention exists but stayed unbounded for layer in status.layers { print(layer.path, layer.kind, layer.capacitySource as Any, - layer.state, layer.resolvedStrategy as Any) + layer.state, layer.resolvedStrategy as Any, layer.memoryBytes) } + +// Allocated bytes across all layers (zero until generation fills the cache) +print(status.memoryBytes) ``` Hybrid attention / state-space models (Qwen3.5, Jamba, LFM2, Falcon-H1, …) diff --git a/skills/mlx-swift-lm/references/lora-adapters.md b/skills/mlx-swift-lm/references/lora-adapters.md index 250917940c..a928bae215 100644 --- a/skills/mlx-swift-lm/references/lora-adapters.md +++ b/skills/mlx-swift-lm/references/lora-adapters.md @@ -237,8 +237,8 @@ public protocol LoRALayer: Module { ```swift // Load base model let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Llama-3.2-3B-Instruct-4bit") ) diff --git a/skills/mlx-swift-lm/references/model-container.md b/skills/mlx-swift-lm/references/model-container.md index 4cba423f14..ac04ba0610 100644 --- a/skills/mlx-swift-lm/references/model-container.md +++ b/skills/mlx-swift-lm/references/model-container.md @@ -25,23 +25,24 @@ ```swift // Via factory (recommended) let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Qwen3-4B-4bit") ) -// With custom hub (from MLXLMHuggingFace) -let hub = HubClient(token: "hf_...") -let container = try await LLMModelFactory.shared.loadContainer( - from: hub, - using: TokenizersLoader(), +// With a custom hub client (auth token, custom endpoint, custom cache). +// HubClient comes from the HuggingFace module; wrap it with #hubDownloader(_:). +let hub = HubClient(host: HubClient.defaultHost, bearerToken: "hf_...") +let privateContainer = try await LLMModelFactory.shared.loadContainer( + from: #hubDownloader(hub), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "private/model") ) // With progress tracking -let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), +let trackedContainer = try await LLMModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config, progressHandler: { progress in print("Downloaded: \(progress.fractionCompleted)") @@ -82,20 +83,23 @@ let lmInput = try await container.prepare(input: userInput) // Generate with streaming let stream = try await container.generate(input: lmInput, parameters: params) -// Generate with wired-memory coordination +// Generate with wired-memory coordination. generate() consumes its LMInput, +// so prepare a new one for each call. +let ticketInput = try await container.prepare(input: UserInput(prompt: "Hello")) let ticket = WiredSumPolicy().ticket(size: estimatedBytes, kind: .active) let streamWithTicket = try await container.generate( - input: lmInput, + input: ticketInput, parameters: params, wiredMemoryTicket: ticket ) // Encode/decode let tokens = await container.encode("Hello world") -let text = await container.decode(tokens: [1, 2, 3]) +let text = await container.decode(tokenIds: [1, 2, 3]) -// Apply chat template -let tokens = try await container.applyChatTemplate(messages: [ +// Apply chat template (on the tokenizer; the container method is deprecated) +let tokenizer = await container.tokenizer +let promptTokens = try tokenizer.applyChatTemplate(messages: [ ["role": "user", "content": "Hello"] ]) ``` @@ -160,10 +164,9 @@ let config = ModelConfiguration( | Property | Type | Description | |----------|------|-------------| -| `id` | `Identifier` | `.id(String)` or `.directory(URL)` | +| `id` | `Identifier` | `.id(String, revision:)` or `.directory(URL)` | | `name` | `String` | Human-readable name | -| `tokenizerId` | `String?` | Pull tokenizer from different repo | -| `overrideTokenizer` | `String?` | Force tokenizer class | +| `tokenizerSource` | `TokenizerSource?` | Load tokenizer from a different source: `.id(String, revision:)` (remote) or `.directory(URL)` (local); `nil` = same as model | | `defaultPrompt` | `String` | Default prompt for testing | | `extraEOSTokens` | `Set` | Additional stop tokens (as strings) | | `eosTokenIds` | `Set` | EOS token IDs (loaded from config) | @@ -179,8 +182,8 @@ let factory = LLMModelFactory.shared // Load container let container = try await factory.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: LLMRegistry.llama3_2_3B_4bit ) @@ -197,8 +200,8 @@ let customFactory = LLMModelFactory( let factory = VLMModelFactory.shared let container = try await factory.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: VLMRegistry.qwen2VL2BInstruct4Bit ) ``` @@ -249,7 +252,8 @@ Map `model_type` from config.json to model initializers: // Download location let resolved = try await resolve( configuration: configuration, - from: HubClient.default, + from: #hubDownloader(), + useLatest: false, progressHandler: { _ in } ) let modelDir = resolved.modelDirectory diff --git a/skills/mlx-swift-lm/references/model-porting.md b/skills/mlx-swift-lm/references/model-porting.md index cd2b1c30d0..e770512376 100644 --- a/skills/mlx-swift-lm/references/model-porting.md +++ b/skills/mlx-swift-lm/references/model-porting.md @@ -406,8 +406,8 @@ and already runs on the adapter and quantization paths. ```swift let modelContainer = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: ModelConfiguration(id: "mlx-community/YourModel-4bit") ) diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index cd4c065b3e..4698b8ec0d 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -95,7 +95,7 @@ LLMRegistry.glm4_9b_4bit // mlx-community/GLM-4-9B-0414-4bit | `exaone4` | EXAONE 4 | | `olmo2`, `olmo3`, `olmoe` | OLMo | | `falcon_h1` | Falcon H1 | -| `jamba_3b` | Jamba | +| `jamba` | Jamba | | `apertus` | Apertus | | `nanochat` | NanoChat | | `nemotron_h` | Nemotron H | @@ -151,19 +151,19 @@ Models not in registries can be loaded by ID: // Any mlx-community model let config = ModelConfiguration(id: "mlx-community/SomeModel-4bit") let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config ) // Specific revision -let config = ModelConfiguration( +let revisionConfig = ModelConfiguration( id: "mlx-community/Model", revision: "v1.0" ) // Local model -let config = ModelConfiguration( +let localConfig = ModelConfiguration( directory: URL(filePath: "/path/to/model") ) ``` @@ -211,32 +211,35 @@ let config = ModelConfiguration( ### Tokenizer Overrides ```swift -// Override tokenizer class +// Use the tokenizer from a different model (remote id or local directory) let config = ModelConfiguration( - id: "...", - overrideTokenizer: "PreTrainedTokenizer" + id: "model-without-tokenizer", + tokenizerSource: .id("different-model-with-tokenizer") ) -// Use tokenizer from different model -let config = ModelConfiguration( +// From a local tokenizer directory +let localTokenizerConfig = ModelConfiguration( id: "model-without-tokenizer", - tokenizerId: "different-model-with-tokenizer" + tokenizerSource: .directory(URL(filePath: "/path/to/tokenizer")) ) ``` +`overrideTokenizer` is gone: the tokenizer *class* is no longer selected by +`ModelConfiguration`. Tokenizer construction is owned by the `TokenizerLoader` passed to +the factory, so supply a custom `TokenizerLoader` instead — see +[tokenizer-chat.md](tokenizer-chat.md#unrecognized-tokenizer-classes). + ## Adding New Model Types Extend the type registry for new architectures: ```swift -// Custom model type -LLMTypeRegistry.shared.register( - modelType: "custom_model", - creator: { configData in - let config = try JSONDecoder().decode(CustomConfig.self, from: configData) - return CustomModel(config) - } -) +// Custom model type — ModelTypeRegistry is an actor, so the call is `await`ed. +// The first parameter is unlabeled and the method is `registerModelType(_:creator:)`. +await LLMTypeRegistry.shared.registerModelType("custom_model") { configData in + let config = try JSONDecoder().decode(CustomConfig.self, from: configData) + return CustomModel(config) +} ``` ## Checking Supported Types diff --git a/skills/mlx-swift-lm/references/tokenizer-chat.md b/skills/mlx-swift-lm/references/tokenizer-chat.md index e85609cb33..498a7e2280 100644 --- a/skills/mlx-swift-lm/references/tokenizer-chat.md +++ b/skills/mlx-swift-lm/references/tokenizer-chat.md @@ -28,8 +28,8 @@ Tokenizers are loaded automatically by model factories: ```swift let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: config ) let tokenizer = await container.tokenizer @@ -37,12 +37,12 @@ let tokenizer = await container.tokenizer ### Manual Loading -Tokenizer loading is handled by the `TokenizerLoader` protocol. Each integration -package provides a concrete loader: +Tokenizer loading is handled by the `TokenizerLoader` protocol. The `MLXHuggingFace` +`#huggingFaceTokenizerLoader()` macro provides a concrete loader backed by Swift +Transformers' `AutoTokenizer`: ```swift -// Using TokenizersLoader from MLXLMTokenizers (swift-tokenizers-mlx) -let loader = TokenizersLoader() +let loader = #huggingFaceTokenizerLoader() let tokenizer = try await loader.load(from: modelDirectory) ``` @@ -55,7 +55,7 @@ let tokenizer = try await loader.load(from: modelDirectory) let tokens: [Int] = tokenizer.encode(text: "Hello, world!") // Decode tokens to text -let text: String = tokenizer.decode(tokens: tokens) +let text: String = tokenizer.decode(tokenIds: tokens) ``` ### Chat Template @@ -276,20 +276,43 @@ if let chunk = detokenizer.next() { // nil means waiting for more tokens ``` -## Tokenizer Replacement Registry +## Unrecognized Tokenizer Classes -Override tokenizer classes for compatibility: +The `replacementTokenizers` dictionary is gone. Tokenizer construction now belongs +entirely to the `TokenizerLoader` you pass to the factory, so there is no +mlx-swift-lm-side override table. + +`#huggingFaceTokenizerLoader()` delegates to `Tokenizers.AutoTokenizer`, which maps the +`tokenizer_class` from `tokenizer_config.json` onto its own built-in implementations. For +an unknown class it throws `TokenizerError.unsupportedTokenizer`. It falls back to a BPE +tokenizer only when called with `strict: false`. To load such a model, write your own +`TokenizerLoader`. This one falls back to BPE: ```swift -// Built-in replacements -// "Qwen2Tokenizer" -> "PreTrainedTokenizer" -// "InternLM2Tokenizer" -> "PreTrainedTokenizer" -// etc. +import Foundation +import MLXLLM +import MLXLMCommon +import MLXHuggingFace +import HuggingFace +import Tokenizers + +struct BPEFallbackTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer { + // strict: false falls back to BPE for unknown tokenizer classes + let upstream = try await AutoTokenizer.from(modelFolder: directory, strict: false) + return #adaptHuggingFaceTokenizer(upstream) + } +} -// Add custom replacement -replacementTokenizers["CustomTokenizer"] = "PreTrainedTokenizer" +let container = try await LLMModelFactory.shared.loadContainer( + from: #hubDownloader(), + using: BPEFallbackTokenizerLoader(), + configuration: config +) ``` +The same hook lets you plug in a completely different tokenizer implementation. + ## Deprecated Patterns ### TokenIterator with prompt MLXArray diff --git a/skills/mlx-swift-lm/references/tool-calling.md b/skills/mlx-swift-lm/references/tool-calling.md index 4f54cc6dff..292ce46a5d 100644 --- a/skills/mlx-swift-lm/references/tool-calling.md +++ b/skills/mlx-swift-lm/references/tool-calling.md @@ -29,13 +29,18 @@ mlx-swift-lm supports function calling / tool use with multiple model-specific f | Format | Models | Example Output | |--------|--------|----------------| | `.json` | Llama, Qwen, most models | `{"name":"f","arguments":{...}}` | -| `.lfm2` | LFM2 | `<\|tool_call_start\|>{"name":"f",...}<\|tool_call_end\|>` | +| `.lfm2` | LFM2 | `<\|tool_call_start\|>[func(arg='value')]<\|tool_call_end\|>` | | `.xmlFunction` | Nemotron, Qwen3 Coder, Qwen3 Next | `v` | | `.qwen35` | Qwen 3.5 | Same `` frame as `.xmlFunction`, but also accepts a framed Qwen/Hermes JSON payload (`{"name":"f","arguments":{...}}`) that Qwen 3.5 sporadically emits instead of XML. Bare (unframed) JSON is not recovered. | | `.glm4` | GLM4 | `funckv` | -| `.gemma` | Gemma | `call:name{key:value}` | +| `.gemma` | Gemma | `call:name{key:value}` | +| `.gemma4` | Gemma4 | `<\|tool_call>call:name{key:<\|"\|>value<\|"\|>}` | | `.kimiK2` | Kimi K2 | `functions.name:0<\|tool_call_argument_begin\|>{...}` | | `.minimaxM2` | MiniMax M2 | `v` | +| `.atem` | Muse Glimmer (Onyx ATEM) | `...` | +| `.mistral` | Mistral3 | `[TOOL_CALLS]get_weather [ARGS]{"location":"Tokyo"}` | +| `.llama3` | Llama 3 | `<\|python_tag\|>{"name":"func","parameters":{...}}` | +| `.gptOSS` | GPT-OSS | Full Harmony protocol, not a JSON dialect: `<\|channel\|>commentary to=functions.get_weather<\|message\|>{...}<\|call\|>` | ## Defining Tools diff --git a/skills/mlx-swift-lm/references/training.md b/skills/mlx-swift-lm/references/training.md index eea755267b..72b2268578 100644 --- a/skills/mlx-swift-lm/references/training.md +++ b/skills/mlx-swift-lm/references/training.md @@ -63,19 +63,23 @@ adapter structure. ### 1. Load Model ```swift +import Foundation import MLXLLM import MLXLMCommon - -// Load base model -let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) +import MLXHuggingFace +import HuggingFace +import Tokenizers + +// Load base model. Training needs direct access to the model, so use +// load(...), which returns a ModelContext, instead of loadContainer(...). +let context = try await LLMModelFactory.shared.load( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Llama-3.2-3B-Instruct-4bit") ) -// Extract model and tokenizer for training -let model = await container.perform { $0.model } -let tokenizer = await container.tokenizer +let model = context.model +let tokenizer = context.tokenizer ``` ### 2. Apply LoRA Layers @@ -360,22 +364,25 @@ Not currently implemented in Swift - use smaller models or reduce batch size. import Foundation import MLXLLM import MLXLMCommon +import MLXHuggingFace +import HuggingFace +import Tokenizers import MLXOptimizers func trainAdapter() async throws { // Load model - let container = try await LLMModelFactory.shared.loadContainer( - from: HubClient.default, - using: TokenizersLoader(), + let context = try await LLMModelFactory.shared.load( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), configuration: .init(id: "mlx-community/Llama-3.2-1B-Instruct-4bit") ) - let model = await container.perform { SendableBox($0.model) }.consume() - let tokenizer = await container.tokenizer + let model = context.model + let tokenizer = context.tokenizer // Apply LoRA let adapter = try LoRAContainer.from( - model: model as! LanguageModel, + model: model, configuration: LoRAConfiguration( numLayers: 8, loraParameters: .init(rank: 8) @@ -383,8 +390,9 @@ func trainAdapter() async throws { ) // Load data - let trainData = try loadData(name: "train") - let validData = try loadData(name: "valid") + let dataDirectory = URL(filePath: "data") + let trainData = try loadLoRAData(directory: dataDirectory, name: "train") + let validData = try loadLoRAData(directory: dataDirectory, name: "valid") // Train let optimizer = Adam(learningRate: 1e-5) diff --git a/skills/mlx-swift-lm/references/wired-memory.md b/skills/mlx-swift-lm/references/wired-memory.md index 72e95af31d..e7b380aed1 100644 --- a/skills/mlx-swift-lm/references/wired-memory.md +++ b/skills/mlx-swift-lm/references/wired-memory.md @@ -64,8 +64,12 @@ Use `WiredMemoryUtils.tune(...)` to measure real runtime costs and then size pol ### Text-only Measurement ```swift -let context = try await LLMModelFactory.shared.load(configuration: config) -let parameters = GenerateParameters(maxTokens: 128, prefillStepSize: 512) +let context = try await LLMModelFactory.shared.load( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), + configuration: config +) +let parameters = GenerateParameters(maxTokens: 128, prefill: .init(stepSize: 512)) let measurement = try await WiredMemoryUtils.tune( context: context,