diff --git a/Libraries/MLXEmbedders/ModelFactory.swift b/Libraries/MLXEmbedders/ModelFactory.swift index b0d5d0999..46c5cdd2f 100644 --- a/Libraries/MLXEmbedders/ModelFactory.swift +++ b/Libraries/MLXEmbedders/ModelFactory.swift @@ -242,7 +242,8 @@ public final class EmbedderModelFactory: GenericModelFactory { modelDirectory: modelDirectory, model: model, perLayerQuantization: baseConfig.perLayerQuantization, weightFileSelection: configuration.weightFileSelection, - excludedComponents: configuration.excludedComponents) + excludedComponents: configuration.excludedComponents, + embeddingStorage: configuration.embeddingStorage) let tokenizer = try await tokenizerTask try model.validate(tokenizer: tokenizer) @@ -259,7 +260,8 @@ public final class EmbedderModelFactory: GenericModelFactory { extraEOSTokens: configuration.extraEOSTokens, stopStrings: configuration.stopStrings, eosTokenIds: configuration.eosTokenIds, - toolCallFormat: configuration.toolCallFormat) + toolCallFormat: configuration.toolCallFormat, + embeddingStorage: configuration.embeddingStorage) let pooling = loadPooling(modelDirectory: modelDirectory, model: model) diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index f111eb99a..d51bbd22b 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -837,7 +837,8 @@ public final class LLMModelFactory: GenericModelFactory { modelDirectory: modelDirectory, model: model, perLayerQuantization: baseConfig.perLayerQuantization, weightFileSelection: configuration.weightFileSelection, - excludedComponents: configuration.excludedComponents) + excludedComponents: configuration.excludedComponents, + embeddingStorage: configuration.embeddingStorage) let tokenizer = try await tokenizerTask @@ -866,7 +867,8 @@ public final class LLMModelFactory: GenericModelFactory { toolCallFormat: mutableConfiguration.toolCallFormat, reasoningConfig: mutableConfiguration.reasoningConfig, messageGenerator: mutableConfiguration.messageGenerator, - generationConfig: mutableConfiguration.generationConfig) + generationConfig: mutableConfiguration.generationConfig, + embeddingStorage: configuration.embeddingStorage) let processor = LLMUserInputProcessor( tokenizer: tokenizer, configuration: modelConfig, diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift index 51bbf0999..d9a0917a3 100644 --- a/Libraries/MLXLLM/Models/Gemma4.swift +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -45,7 +45,9 @@ public struct Gemma4Configuration: Codable, Sendable { // MARK: - Model -public class Gemma4Model: Module, LLMModel, KVCacheDimensionProvider { +public class Gemma4Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings } + public var vocabularySize: Int { languageModel.vocabularySize } public var kvHeads: [Int] { languageModel.kvHeads } public var kvCacheStart: KVCacheStart { .deferred } diff --git a/Libraries/MLXLLM/Models/Gemma4Text.swift b/Libraries/MLXLLM/Models/Gemma4Text.swift index db4e6a832..67575b8cb 100644 --- a/Libraries/MLXLLM/Models/Gemma4Text.swift +++ b/Libraries/MLXLLM/Models/Gemma4Text.swift @@ -840,7 +840,13 @@ private class Gemma4TextExperts: Module { // MARK: - Public Model -public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { +public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider, + InputOnlyEmbeddingsProviding +{ + public var inputOnlyEmbeddings: [Embedding] { + [model.embedTokensPerLayer].compactMap { $0 } + (lmHead == nil ? [] : [model.embedTokens]) + } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { .deferred } diff --git a/Libraries/MLXLLM/Models/Llama.swift b/Libraries/MLXLLM/Models/Llama.swift index aecfe1623..1fa6039bf 100644 --- a/Libraries/MLXLLM/Models/Llama.swift +++ b/Libraries/MLXLLM/Models/Llama.swift @@ -149,7 +149,8 @@ public class LlamaModelInner: Module { } /// Model for Llama and Mistral model types. -public class LlamaModel: Module, LLMModel, KVCacheDimensionProvider { +public class LlamaModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } public let vocabularySize: Int public let kvHeads: [Int] diff --git a/Libraries/MLXLLM/Models/Phi3.swift b/Libraries/MLXLLM/Models/Phi3.swift index 9bb7caff0..aa20bfe8c 100644 --- a/Libraries/MLXLLM/Models/Phi3.swift +++ b/Libraries/MLXLLM/Models/Phi3.swift @@ -180,7 +180,8 @@ public class Phi3ModelInner: Module { } } -public class Phi3Model: Module, LLMModel, KVCacheDimensionProvider { +public class Phi3Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } public let vocabularySize: Int public let kvHeads: [Int] diff --git a/Libraries/MLXLLM/Models/PhiMoE.swift b/Libraries/MLXLLM/Models/PhiMoE.swift index 1d3204a10..87d001cde 100644 --- a/Libraries/MLXLLM/Models/PhiMoE.swift +++ b/Libraries/MLXLLM/Models/PhiMoE.swift @@ -212,7 +212,9 @@ public class PhiMoEModelInner: Module { } } -public class PhiMoEModel: Module, LLMModel, KVCacheDimensionProvider { +public class PhiMoEModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { [model.embedTokens] } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { .deferred } diff --git a/Libraries/MLXLLM/Models/Qwen2.swift b/Libraries/MLXLLM/Models/Qwen2.swift index a79402a6b..7e70a5072 100644 --- a/Libraries/MLXLLM/Models/Qwen2.swift +++ b/Libraries/MLXLLM/Models/Qwen2.swift @@ -164,7 +164,9 @@ public class Qwen2ModelInner: Module { } } -public class Qwen2Model: Module, LLMModel, KVCacheDimensionProvider { +public class Qwen2Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index daf6883da..aa5f16116 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -174,7 +174,9 @@ public class Qwen3ModelInner: Module { } } -public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider { +public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { .compressed(headDim: configuration.headDim) } diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 91c0c1e3f..16ee64e97 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -1282,7 +1282,11 @@ public class Qwen35TextModelInner: Module { } } -public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { +public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider, + InputOnlyEmbeddingsProviding +{ + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { @@ -1489,7 +1493,9 @@ extension Qwen35TextModel: SpeculativeCacheRewindModel { // MARK: - Top-level Model -public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider { +public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { languageModel.kvCacheStart } diff --git a/Libraries/MLXLLM/Models/Qwen3MoE.swift b/Libraries/MLXLLM/Models/Qwen3MoE.swift index 877f30afb..bd318fb42 100644 --- a/Libraries/MLXLLM/Models/Qwen3MoE.swift +++ b/Libraries/MLXLLM/Models/Qwen3MoE.swift @@ -229,7 +229,10 @@ public class Qwen3MoEModelInner: Module { } } -public class Qwen3MoEModel: Module, LLMModel, KVCacheDimensionProvider { +public class Qwen3MoEModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding +{ + public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] } + public let vocabularySize: Int public let kvHeads: [Int] public var kvCacheStart: KVCacheStart { .compressed(headDim: configuration.headDim) } diff --git a/Libraries/MLXLLM/Models/Ricursive.swift b/Libraries/MLXLLM/Models/Ricursive.swift index 71d9cb67a..bca77e2dd 100644 --- a/Libraries/MLXLLM/Models/Ricursive.swift +++ b/Libraries/MLXLLM/Models/Ricursive.swift @@ -380,8 +380,9 @@ private final class RicursiveBackbone: Module { } } -public final class RicursiveModel: Module, LLMModel { +public final class RicursiveModel: Module, LLMModel, InputOnlyEmbeddingsProviding { public let vocabularySize: Int + public var inputOnlyEmbeddings: [Embedding] { [model.embedTokens] } public let configuration: RicursiveConfiguration @ModuleInfo fileprivate var model: RicursiveBackbone diff --git a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift new file mode 100644 index 000000000..416b3a9f3 --- /dev/null +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -0,0 +1,202 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +#if canImport(Darwin) +import Darwin +import os +#endif + +/// Keep source buffers alive while checkpoint preparation can rename or replace arrays. +package final class CheckpointTensorStorage { + #if canImport(Darwin) + fileprivate final class File: Sendable { + let handle: FileHandle + let url: URL + let status: stat + let directory: URL + private let mappedAddresses = OSAllocatedUnfairLock(initialState: Set()) + + init(url: URL, directory: URL) throws { + let handle = try FileHandle(forReadingFrom: url) + var status = stat() + guard fstat(handle.fileDescriptor, &status) == 0, + status.st_mode & S_IFMT == S_IFREG + else { throw POSIXError(.EINVAL) } + self.handle = handle + self.url = url + self.status = status + self.directory = directory + } + + deinit { try? handle.close() } + + func matches(_ current: stat) -> Bool { + status.st_dev == current.st_dev && status.st_ino == current.st_ino + && status.st_size == current.st_size + && status.st_mtimespec.tv_sec == current.st_mtimespec.tv_sec + && status.st_mtimespec.tv_nsec == current.st_mtimespec.tv_nsec + && status.st_ctimespec.tv_sec == current.st_ctimespec.tv_sec + && status.st_ctimespec.tv_nsec == current.st_ctimespec.tv_nsec + } + + func unchanged(checkPath: Bool) -> Bool { + var current = stat() + guard fstat(handle.fileDescriptor, ¤t) == 0, matches(current) else { + return false + } + return !checkPath || (stat(url.path, ¤t) == 0 && matches(current)) + } + + func containsMappedAddress(_ address: UInt) -> Bool { + mappedAddresses.withLock { $0.contains(address) } + } + + /// The tensor in file-backed storage, or nil if the file changed. + func array(for array: MLXArray, span: SafetensorSpan) throws -> MLXArray? { + guard unchanged(checkPath: false) else { return nil } + guard span.byteOffset >= 0, span.byteCount > 0, + span.byteCount == array.nbytes, + span.byteOffset <= status.st_size, + span.byteCount <= status.st_size - span.byteOffset + else { throw POSIXError(.EINVAL) } + // Typed reads need aligned views, so tensors at other offsets are copied first. + let result = + if span.byteOffset.isMultiple(of: Int64(MemoryLayout.alignment)) { + try fileBackedArray( + like: array, mapping: handle.fileDescriptor, offset: span.byteOffset) + } else { + try fileBackedArray( + like: array, copying: handle.fileDescriptor, offset: span.byteOffset, + directory: directory) + } + if let address = result.asData(access: .noCopy).data.withUnsafeBytes({ + $0.baseAddress.map(UInt.init(bitPattern:)) + }) { + mappedAddresses.withLock { _ = $0.insert(address) } + } + return result + } + } + + private struct Source { + let snapshot: MLXArray + let strides: [Int] + let location: Mapping + } + + private let locations: [String: Mapping] + private let vocabularySizes: Set + private var sources: [UInt: Source] = [:] + #endif + + package struct Mapping: Sendable { + #if canImport(Darwin) + fileprivate let file: File + fileprivate let span: SafetensorSpan + #endif + + func array(for array: MLXArray) throws -> MLXArray? { + #if canImport(Darwin) + return try file.array(for: array, span: span) + #else + return nil + #endif + } + } + + let mappings: [String: Mapping] + + /// Tensors that cannot map in place are copied into unlinked files in `directory`. + init?( + model: BaseLanguageModel, policy: EmbeddingStoragePolicy, urls: [URL], + quantization: BaseConfiguration.PerLayerQuantization? = nil, + directory: URL = FileManager.default.temporaryDirectory + ) { + #if canImport(Darwin) + guard policy == .backed, + let provider = model as? any InputOnlyEmbeddingsProviding, + !provider.inputOnlyEmbeddings.isEmpty, + GPU.deviceInfo().maxBufferSize > 0 + else { return nil } + var locations: [String: Mapping] = [:] + do { + for url in urls { + let file = try File(url: url, directory: directory) + for span in try safetensorSpansInFileOrder(url: url) { + locations[span.name] = Mapping(file: file, span: span) + } + guard file.unchanged(checkPath: true) else { return nil } + } + } catch { return nil } + self.locations = locations + self.vocabularySizes = Set(provider.inputOnlyEmbeddings.map { $0.weight.dim(0) }) + let eligible = Set(provider.inputOnlyEmbeddings.map(ObjectIdentifier.init)) + var mappings: [String: Mapping] = [:] + for (name, module) in model.namedModules() where eligible.contains(ObjectIdentifier(module)) + { + guard let embedding = module as? Embedding else { continue } + let parameters: [String] + if embedding is QuantizedEmbedding { + guard supportsFileBackedStorage(embedding) else { continue } + parameters = ["weight", "scales", "biases"] + } else if let settings = quantization?.quantization(layer: name) { + guard type(of: embedding) == Embedding.self, + settings.mode == .affine, locations["\(name).scales"] != nil + else { continue } + parameters = ["weight", "scales", "biases"] + } else { + guard supportsFileBackedStorage(embedding) else { continue } + parameters = ["weight"] + } + for parameter in parameters { + let path = "\(name).\(parameter)" + mappings[path] = locations[path] + } + } + self.mappings = mappings + #else + return nil + #endif + } + + func record(_ weights: [String: MLXArray]) { + #if canImport(Darwin) + for (name, value) in weights where value.ndim == 2 && vocabularySizes.contains(value.dim(0)) + { + guard let location = locations[name], location.file.unchanged(checkPath: true), + location.span.byteCount == value.nbytes + else { continue } + // A second handle to the same array, which preparation cannot update in place. + let snapshot = value.reshaped(value.shape) + let data = snapshot.asData(access: .noCopy) + data.data.withUnsafeBytes { bytes in + guard let pointer = bytes.baseAddress else { return } + sources[UInt(bitPattern: pointer)] = Source( + snapshot: snapshot, strides: data.strides, location: location) + } + } + #endif + } + + #if canImport(Darwin) + func array(matching array: MLXArray) throws -> MLXArray? { + let data = array.asData(access: .noCopy) + let source = data.data.withUnsafeBytes { bytes -> Source? in + guard let pointer = bytes.baseAddress else { return nil } + return sources[UInt(bitPattern: pointer)] + } + guard let source, source.snapshot.shape == array.shape, + source.snapshot.dtype == array.dtype, source.strides == data.strides, + source.location.file.unchanged(checkPath: false) + else { return nil } + let address = data.data.withUnsafeBytes { $0.baseAddress.map(UInt.init(bitPattern:)) } + if let address, source.location.file.containsMappedAddress(address) { + return source.snapshot + } + return try source.location.array(for: array) + } + #endif +} diff --git a/Libraries/MLXLMCommon/Documentation.docc/porting.md b/Libraries/MLXLMCommon/Documentation.docc/porting.md index 98ae64932..cf08db2e3 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/porting.md +++ b/Libraries/MLXLMCommon/Documentation.docc/porting.md @@ -317,7 +317,7 @@ public init(dimensions: Int, eps: Float = 1e-5) { } ``` -Note that the weight is given an initial value and shape based on the parameters to the initializer. In typical inference use, these values will be replaced when the weights are loaded (``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:)-fqoy``). +Note that the weight is given an initial value and shape based on the parameters to the initializer. In typical inference use, these values will be replaced when the weights are loaded (``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:embeddingStorage:)-7iyka``). * Note: If the property names in Python don't make good Swift names, you can use the `@ParameterInfo` property wrapper to specify the key: `@ParameterInfo(key: "some_weight") var weight: MLXArray` diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index a42fe0b6c..2aea6b792 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -29,6 +29,30 @@ print(try await session.respond(to: "What are two things to see in San Francisco print(try await session.respond(to: "How about a great place to eat?")) ``` +## Embedding storage + +``EmbeddingStoragePolicy/backed`` keeps supported frozen input-only tables in +file-backed storage so unused rows can be reclaimed. Models declare these tables with +``InputOnlyEmbeddingsProviding``. Tensor values and precision are unchanged. +Tied output tables, custom embeddings, and unsupported formats keep normal storage. + +The CPU reads the rows, because a GPU read makes the whole table resident. Each forward +pass then waits once for the CPU. On an M6 this adds about 0.17 ms to each decoded token. +``EmbeddingStoragePolicy/automatic``, the default, file-backs the tables only when the +checkpoint files are larger than `GPU.maxRecommendedWorkingSetBytes()`. Models that fit +keep normal storage and do not pay this cost. + +Tables at 8-byte aligned file offsets map straight from the checkpoint. Other tables are +copied once per load from the checkpoint into temporary files, which use extra disk space. +Neither way loads the whole table into memory. +Select ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. + +> Important: Do not rewrite or truncate checkpoint files while the model is in use. +> Use ``EmbeddingStoragePolicy/resident`` if files must change in place. + +MLX allocation counters include the full mapped table. Wiring all MLX buffers can keep +all its pages resident, even when the process footprint is lower. + ## Downloaders and Tokenizers There are 3 general ways to select and use concrete Downloader and Tokenizer implementations: diff --git a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md index 6d590c4ba..6ecf7e982 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md +++ b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md @@ -29,6 +29,11 @@ let weightBytes = memory.total component loads on first use. The KV cache is not included; read ``KVCacheStatus/memoryBytes`` for it. +``ModelMemory/backed`` is the part of the model held in file-backed embedding tables. The +system reads those pages on use and can reclaim them. ``ModelMemory/total`` includes them, so +subtract them from a ticket that should cover only resident weights. +``ModelMemory/paged`` is the part of those tables paged in when measured. + Summing `nbytes` across the parameter arrays gives a similar number from array metadata alone, but it can count a shared buffer more than once and misses on-demand components: diff --git a/Libraries/MLXLMCommon/Downloader.swift b/Libraries/MLXLMCommon/Downloader.swift index fd5064803..9c73c4efc 100644 --- a/Libraries/MLXLMCommon/Downloader.swift +++ b/Libraries/MLXLMCommon/Downloader.swift @@ -91,6 +91,9 @@ public struct ResolvedModelConfiguration: Sendable { /// - ``ModelConfiguration/excludedComponents`` public var excludedComponents: Set + /// Storage for supported frozen, lookup-only embedding tables. + public var embeddingStorage: EmbeddingStoragePolicy + public init( modelDirectory: URL, tokenizerDirectory: URL, @@ -104,7 +107,8 @@ public struct ResolvedModelConfiguration: Sendable { messageGenerator: (any MessageGenerator)? = nil, generationConfig: GenerationConfigFile? = nil, weightFileSelection: WeightFileSelection = .automatic, - excludedComponents: Set = [] + excludedComponents: Set = [], + embeddingStorage: EmbeddingStoragePolicy = .automatic ) { self.modelDirectory = modelDirectory self.tokenizerDirectory = tokenizerDirectory @@ -119,6 +123,7 @@ public struct ResolvedModelConfiguration: Sendable { self.generationConfig = generationConfig self.weightFileSelection = weightFileSelection self.excludedComponents = excludedComponents + self.embeddingStorage = embeddingStorage } } diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift new file mode 100644 index 000000000..fd920e23a --- /dev/null +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -0,0 +1,363 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +#if canImport(Darwin) +import Darwin +#endif + +/// Storage for embedding tables during model loading. +public enum EmbeddingStoragePolicy: Sendable, Equatable { + /// ``backed`` when the checkpoint files are larger than the GPU working set that + /// Metal recommends, else ``resident``. + case automatic + /// File-back supported frozen input tables on Apple platforms; other tables stay resident. + /// Each forward pass then reads the rows on the CPU, which adds one CPU-GPU + /// synchronization. Keep checkpoint contents unchanged while the model is in use. + case backed + /// Keep all tables in normal MLX storage. + case resident + + /// The policy for a checkpoint of `checkpointBytes`, with ``automatic`` resolved. + func resolved(checkpointBytes: Int, workingSetBytes: Int?) -> EmbeddingStoragePolicy { + guard self == .automatic else { return self } + guard let workingSetBytes, checkpointBytes > workingSetBytes else { return .resident } + return .backed + } +} + +/// Embedding tables used only for lookup, never shared with a dense output projection. +public protocol InputOnlyEmbeddingsProviding: Module { + var inputOnlyEmbeddings: [Embedding] { get } +} + +#if canImport(Darwin) +private let embeddingStorageLogger = MLXLogger(label: "embedding-storage") +#endif + +package func prepareEmbeddingStorage( + in model: BaseLanguageModel, policy: EmbeddingStoragePolicy, + checkpoint: CheckpointTensorStorage? = nil +) -> Int { + #if canImport(Darwin) + do { + return try prepareEmbeddingStorage( + in: model, policy: policy, directory: FileManager.default.temporaryDirectory, + checkpoint: checkpoint) + } catch { + embeddingStorageLogger.warning( + "Could not prepare embedding storage: \(String(describing: error))") + return 0 + } + #else + return 0 + #endif +} + +/// The arrays of the file-backed embedding tables in `module`. +func fileBackedEmbeddingArrays(in module: Module) -> [MLXArray] { + #if canImport(Darwin) + return module.namedModules().flatMap { _, module -> [MLXArray] in + guard module is FileBackedEmbedding || module is FileBackedQuantizedEmbedding else { + return [] + } + return module.parameters().flattened().map(\.1) + } + #else + return [] + #endif +} + +/// The bytes of the pages of `arrays` that are paged in. Each buffer counts once. +func pagedBytes(of arrays: [MLXArray]) -> Int { + #if canImport(Darwin) + let page = Int(getpagesize()) + var counted = Set() + var pages = 0 + for array in arrays { + array.asData(access: .noCopy).data.withUnsafeBytes { bytes in + guard let base = bytes.baseAddress, !bytes.isEmpty else { return } + let start = UInt(bitPattern: base) / UInt(page) * UInt(page) + guard counted.insert(start).inserted else { return } + let length = Int(UInt(bitPattern: base) - start) + bytes.count + var status = [CChar](repeating: 0, count: (length + page - 1) / page) + guard mincore(UnsafeRawPointer(bitPattern: start), length, &status) == 0 else { + return + } + pages += status.count { Int32($0) & MINCORE_INCORE != 0 } + } + } + return pages * page + #else + return 0 + #endif +} + +#if canImport(Darwin) + +/// Copy one array into page-aligned temporary storage. The mapping owns its disk blocks. +package func fileBackedArray(_ source: MLXArray, directory: URL) throws -> MLXArray { + try withExtendedLifetime(source) { + try temporaryFileArray(like: source, directory: directory) { descriptor in + let data = source.asData(access: .noCopyIfContiguous).data + try data.withUnsafeBytes { bytes in + guard let base = bytes.baseAddress else { throw POSIXError(.EINVAL) } + try transfer(bytes.count) { + pwrite(descriptor, base + $0, min(bytes.count - $0, chunkSize), off_t($0)) + } + } + } + } +} + +/// Copy the bytes of an array shaped like `template` at `offset` in `descriptor` into +/// page-aligned temporary storage, one chunk at a time. +func fileBackedArray( + like template: MLXArray, copying descriptor: Int32, offset: Int64, directory: URL +) throws -> MLXArray { + try temporaryFileArray(like: template, directory: directory) { + try copyFileBytes(template.nbytes, from: descriptor, at: offset, to: $0) + } +} + +/// Map the bytes of an array shaped like `template` at `offset` in `descriptor`. The offset +/// must be a multiple of the element size. The array owns the private mapping. +func fileBackedArray( + like template: MLXArray, mapping descriptor: Int32, offset: Int64 +) throws -> MLXArray { + let page = Int(getpagesize()) + let leading = Int(offset % Int64(page)) + let length = try mappingLength(of: template, leading: leading) + guard + let pointer = mmap( + nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, descriptor, offset - Int64(leading)), + pointer != MAP_FAILED + else { throw POSIXError.lastError } + // Sparse lookups do not need read-ahead for neighboring rows. + _ = madvise(pointer, length, MADV_RANDOM) + let storage = MLXArray( + rawPointer: pointer, [length / page, page / template.itemSize], dtype: template.dtype + ) { + munmap(pointer, length) + } + guard + storage.asData(access: .noCopy).data.withUnsafeBytes({ $0.baseAddress }) + == UnsafeRawPointer(pointer) + else { throw POSIXError(.ENOTSUP) } + let array = asStrided( + storage, template.shape, offset: leading / template.itemSize, stream: .cpu) + eval(array) + return array +} + +// Bytes per read or write. Smaller chunks made cold loads measurably slower. +private let chunkSize = 32 * 1024 * 1024 + +/// The page-rounded length of a mapping that holds `template` after `leading` bytes. +private func mappingLength(of template: MLXArray, leading: Int) throws -> Int { + guard template.nbytes > 0 else { throw POSIXError(.EINVAL) } + let page = Int(getpagesize()) + let (extent, overflow) = template.nbytes.addingReportingOverflow(leading + page - 1) + let length = extent / page * page + guard !overflow, length / template.itemSize <= Int32.max, + length <= GPU.deviceInfo().maxBufferSize + else { throw POSIXError(.EOVERFLOW) } + return length +} + +/// An array shaped like `template` in an unlinked temporary file that `fill` writes. +private func temporaryFileArray( + like template: MLXArray, directory: URL, fill: (Int32) throws -> Void +) throws -> MLXArray { + let length = try mappingLength(of: template, leading: 0) + var path = Array(directory.appendingPathComponent("mlx-embedding-XXXXXX").path.utf8CString) + let descriptor = mkstemp(&path) + guard descriptor >= 0 else { throw POSIXError.lastError } + defer { close(descriptor) } + guard unlink(path) == 0 else { throw POSIXError.lastError } + // Do not fill the file cache with rows that inference may never read. + _ = fcntl(descriptor, F_NOCACHE, 1) + guard ftruncate(descriptor, off_t(length)) == 0 else { throw POSIXError.lastError } + try fill(descriptor) + return try fileBackedArray(like: template, mapping: descriptor, offset: 0) +} + +/// Copy `count` bytes at `offset` in `source` to the start of `destination`. +private func copyFileBytes( + _ count: Int, from source: Int32, at offset: Int64, to destination: Int32 +) throws { + // Page alignment lets the writes bypass the file cache. + let buffer = UnsafeMutableRawPointer.allocate( + byteCount: min(chunkSize, count), alignment: Int(getpagesize())) + defer { buffer.deallocate() } + var copied = 0 + while copied < count { + let length = min(chunkSize, count - copied) + try transfer(length) { + pread(source, buffer + $0, length - $0, offset + Int64(copied + $0)) + } + try transfer(length) { + pwrite(destination, buffer + $0, length - $0, off_t(copied + $0)) + } + copied += length + } +} + +/// Call `step` with the bytes done so far until `count` bytes are done. +private func transfer(_ count: Int, _ step: (Int) -> Int) throws { + var done = 0 + while done < count { + let result = step(done) + if result < 0 && errno == EINTR { continue } + guard result > 0 else { throw result < 0 ? POSIXError.lastError : POSIXError(.EIO) } + done += result + } +} + +extension POSIXError { + /// The error for the current `errno`. + fileprivate static var lastError: POSIXError { + POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) + } +} + +/// `x` clamped to the rows of `table`; negative indices still count from the end, as in +/// `take`. A CPU read past a mapping faults, where a GPU read returns undefined values. +private func rowIndices(_ x: MLXArray, in table: MLXArray, stream: MLX.Stream) -> MLXArray { + let rows = table.dim(0) + return clip( + x, min: x.dtype.isSignedInteger ? -rows : 0, max: rows - 1, stream: .stream(stream)) +} + +// Each table reads its rows on its own CPU stream, which has its own thread. A row not in +// memory is a page fault, so the reads of different tables wait for the disk together. + +package final class FileBackedEmbedding: Embedding { + private let stream = MLX.Stream(.cpu) + + package override func callAsFunction(_ x: MLXArray) -> MLXArray { + weight.take(rowIndices(x, in: weight, stream: stream), axis: 0, stream: .stream(stream)) + } +} + +package final class FileBackedQuantizedEmbedding: QuantizedEmbedding { + private let stream = MLX.Stream(.cpu) + + package override func callAsFunction(_ x: MLXArray) -> MLXArray { + let indices = rowIndices(x.flattened(), in: weight, stream: stream) + return dequantized( + weight.take(indices, axis: 0, stream: .stream(stream)), + scales: scales.take(indices, axis: 0, stream: .stream(stream)), + biases: biases.map { $0.take(indices, axis: 0, stream: .stream(stream)) }, + groupSize: groupSize, bits: bits, mode: mode + ).reshaped(x.shape + [-1]) + } +} + +func supportsFileBackedStorage(_ embedding: Embedding) -> Bool { + guard embedding.trainableParameters().flattened().isEmpty else { return false } + if let quantized = embedding as? QuantizedEmbedding { + guard + type(of: embedding) == QuantizedEmbedding.self + || embedding is FileBackedQuantizedEmbedding + else { return false } + return quantized.mode == .affine && quantized.globalScale == nil + } + return type(of: embedding) == Embedding.self || embedding is FileBackedEmbedding +} + +/// Prepare embedding access after checkpoint parameters have been applied. +@discardableResult +package func prepareEmbeddingStorage( + in model: Module, policy: EmbeddingStoragePolicy = .backed, directory: URL, + checkpoint: CheckpointTensorStorage? = nil +) throws -> Int { + guard let provider = model as? any InputOnlyEmbeddingsProviding else { return 0 } + let eligible = Set(provider.inputOnlyEmbeddings.map(ObjectIdentifier.init)) + guard !eligible.isEmpty else { return 0 } + var replacements: [(String, Module)] = [] + var prepared: [ObjectIdentifier: Embedding] = [:] + for (name, module) in model.namedModules() { + guard !name.isEmpty, eligible.contains(ObjectIdentifier(module)), + let embedding = module as? Embedding, supportsFileBackedStorage(embedding), + policy == .backed || module is FileBackedEmbedding + || module is FileBackedQuantizedEmbedding + else { continue } + let identity = ObjectIdentifier(embedding) + if let replacement = prepared[identity] { + replacements.append((name, replacement)) + continue + } + func backed(_ array: MLXArray) throws -> MLXArray { + if let mapped = try? checkpoint?.array(matching: array) { return mapped } + return try fileBackedArray(array, directory: directory) + } + let replacement: Embedding + if let quantized = embedding as? QuantizedEmbedding { + switch policy { + case .backed: + replacement = try FileBackedQuantizedEmbedding( + weight: backed(quantized.weight), scales: backed(quantized.scales), + biases: quantized.biases.map(backed), + groupSize: quantized.groupSize, bits: quantized.bits, mode: quantized.mode, + globalScale: quantized.globalScale) + case .automatic, .resident: + replacement = QuantizedEmbedding( + weight: quantized.weight, scales: quantized.scales, biases: quantized.biases, + groupSize: quantized.groupSize, bits: quantized.bits, mode: quantized.mode, + globalScale: quantized.globalScale) + } + } else { + switch policy { + case .backed: + replacement = try FileBackedEmbedding(weight: backed(embedding.weight)) + case .automatic, .resident: + replacement = Embedding(weight: embedding.weight) + } + } + replacement.freeze() + replacement.train(embedding.training) + prepared[identity] = replacement + replacements.append((name, replacement)) + } + if !replacements.isEmpty { + defer { model.invalidateCompiledTraces() } + try replaceModules(replacements, in: model) + } + return prepared.count +} + +/// Replace each named module through its parent. `update(modules:)` cannot leave out the +/// first elements of an array, so each changed array gets all its elements. +private func replaceModules(_ replacements: [(String, Module)], in model: Module) throws { + let modules = Dictionary(model.namedModules(), uniquingKeysWith: { first, _ in first }) + var children: [String: [String: Module]] = [:] + for (name, module) in replacements { + var path = name.split(separator: ".").map(String.init) + var relative: [String] = [] + repeat { + relative.insert(path.removeLast(), at: 0) + } while !path.isEmpty && modules[path.joined(separator: ".")] == nil + children[path.joined(separator: "."), default: [:]][relative.joined(separator: ".")] = + module + } + for (parent, updates) in children { + guard let parentModule = parent.isEmpty ? model : modules[parent] else { + throw POSIXError(.ENOENT) + } + var entries = updates + for key in Set(updates.keys.compactMap { $0.split(separator: ".").first }) { + let prefix = parent.isEmpty ? String(key) : "\(parent).\(key)" + var index = 0 + while let sibling = modules["\(prefix).\(index)"] { + entries["\(key).\(index)"] = entries["\(key).\(index)"] ?? sibling + index += 1 + } + } + try parentModule.update(modules: ModuleChildren.unflattened(Array(entries)), verify: []) + } +} + +#endif diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 6b79617a4..4f85f3b52 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -18,9 +18,10 @@ import MLXNN // loader's own reads. /// One tensor's byte range in a safetensors file, from the file's own header. -struct SafetensorSpan { +struct SafetensorSpan: Sendable { let name: String let byteCount: Int64 + let byteOffset: Int64 } /// The tensors of the safetensors file at `url`, ordered by their position in the file. @@ -54,14 +55,19 @@ func safetensorSpansInFileOrder(url: URL) throws -> [SafetensorSpan] { let offsets = entry["data_offsets"] as? [Any], offsets.count == 2, let begin = (offsets[0] as? NSNumber)?.int64Value, let end = (offsets[1] as? NSNumber)?.int64Value, - end >= begin + begin >= 0, end >= begin, + end <= Int64.max - Int64(headerLength) - 8 else { throw Malformed() } spans.append((name, begin, end - begin)) } spans.sort { $0.begin < $1.begin } - return spans.map { SafetensorSpan(name: $0.name, byteCount: $0.byteCount) } + return spans.map { + SafetensorSpan( + name: $0.name, byteCount: $0.byteCount, + byteOffset: Int64(headerLength) + 8 + $0.begin) + } } /// Contiguous index ranges of `byteCounts` whose byte totals are balanced around @@ -163,15 +169,21 @@ func loadWeightArrays(urls: [URL]) throws -> ( /// Tensors under `excludedNamespaces` are never read. A file that holds only excluded tensors /// still supplies its metadata. -func loadModelCheckpoint(urls: [URL], excludedNamespaces: [String] = []) throws +func loadModelCheckpoint( + urls: [URL], excludedNamespaces: [String] = [], + mappings: [String: CheckpointTensorStorage.Mapping] = [:] +) throws -> ModelCheckpoint { let exclusions = CheckpointNameMapping(excludedNamespaces.map { .excludePrefix($0) }) - return try loadModelCheckpoint(urls: urls) { exclusions.mapName($0) != nil } + return try loadModelCheckpoint(urls: urls, mappings: mappings) { exclusions.mapName($0) != nil } } /// Only tensors whose names pass `isRead` are read. -func loadModelCheckpoint(urls: [URL], isRead: @escaping @Sendable (String) -> Bool) throws +func loadModelCheckpoint( + urls: [URL], mappings: [String: CheckpointTensorStorage.Mapping] = [:], + isRead: @escaping @Sendable (String) -> Bool +) throws -> ModelCheckpoint { struct WorkItem { @@ -242,6 +254,12 @@ func loadModelCheckpoint(urls: [URL], isRead: @escaping @Sendable (String) -> Bo selected = all.filter { isRead($0.key) } } + for (name, mapping) in mappings { + if let array = selected[name], let mapped = try? mapping.array(for: array) { + selected[name] = mapped + } + } + // force this range's I/O here, on this stream, in file-offset order if !selected.isEmpty { eval(Array(selected.values)) } state.merge(file: item.file, weights: selected, metadata: metadata) @@ -413,13 +431,20 @@ func contentsOfModelDirectory( /// needs them, unless `componentLoading` is ``ComponentLoading/immediate``. Tensors of components /// that do not load now and of the model's ``BaseLanguageModel/excludedCheckpointNamespaces`` are /// not read. +/// +/// Supported frozen tables declared by ``InputOnlyEmbeddingsProviding`` use file-backed +/// storage when the checkpoint is larger than the recommended GPU working set. Select +/// ``EmbeddingStoragePolicy/backed`` or ``EmbeddingStoragePolicy/resident`` to choose. +/// +/// - Important: Do not rewrite or truncate mapped checkpoint files while the model is in use. public func loadWeights( modelDirectory: URL, model: BaseLanguageModel, quantization: BaseConfiguration.Quantization? = nil, perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil, weightFileSelection: WeightFileSelection = .automatic, excludedComponents: Set = [], - componentLoading: ComponentLoading = .onFirstUse + componentLoading: ComponentLoading = .onFirstUse, + embeddingStorage: EmbeddingStoragePolicy = .automatic ) throws { let additionalFiles = (model as? any AdditionalWeightFilesProviding)?.additionalWeightFiles let weightURLs = try safetensorWeightURLs( @@ -434,19 +459,34 @@ public func loadWeights( of: model, urls: weightURLs, excluded: excludedComponents, loading: componentLoading, perLayerQuantization: perLayerQuantization) + model.excludedCheckpointNamespaces + let embeddingStorage = embeddingStorage.resolved( + checkpointBytes: weightURLs.reduce(0) { + $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) + }, + workingSetBytes: GPU.maxRecommendedWorkingSetBytes()) + var checkpointStorage = CheckpointTensorStorage( + model: model, policy: embeddingStorage, urls: weightURLs, + quantization: perLayerQuantization) // The checkpoint goes out of scope before materialization, so tensors that preparation // replaces are freed by then. do { var checkpoint = try loadModelCheckpoint( - urls: weightURLs, excludedNamespaces: excludedNamespaces) + urls: weightURLs, excludedNamespaces: excludedNamespaces, + mappings: checkpointStorage?.mappings ?? [:]) + checkpointStorage?.record(checkpoint.weights) checkpoint.perLayerQuantization = perLayerQuantization checkpoint = try model.prepareCheckpoint(checkpoint) try applyCheckpoint(checkpoint, to: model) } + // Runs after the checkpoint is released, so old embedding buffers can be reclaimed. + let preparedEmbeddings = prepareEmbeddingStorage( + in: model, policy: embeddingStorage, checkpoint: checkpointStorage) + checkpointStorage = nil // Build derived inference-only state and realize the model while the loader // still has exclusive access. Forward passes must remain read-only. materializeModelForInference(model) + if preparedEmbeddings > 0 { Memory.clearCache() } } /// Quantize the layers `checkpoint` has scales for, then update `module` with strict validation. @@ -462,7 +502,7 @@ func applyCheckpoint(_ checkpoint: ModelCheckpoint, to module: Module) throws { } /// Async variant of -/// ``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:)-858j8``. +/// ``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:embeddingStorage:)-1uqs8``. /// /// Loading blocks its thread on file I/O and fans out with `DispatchQueue.concurrentPerform`. /// Swift concurrency's cooperative threads must never block, so this overload runs the load @@ -474,7 +514,8 @@ public func loadWeights( perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil, weightFileSelection: WeightFileSelection = .automatic, excludedComponents: Set = [], - componentLoading: ComponentLoading = .onFirstUse + componentLoading: ComponentLoading = .onFirstUse, + embeddingStorage: EmbeddingStoragePolicy = .automatic ) async throws { let model = SendableBox(model) let progress = ModelLoadProgressScope.reporter @@ -492,7 +533,8 @@ public func loadWeights( perLayerQuantization: perLayerQuantization, weightFileSelection: weightFileSelection, excludedComponents: excludedComponents, - componentLoading: componentLoading) + componentLoading: componentLoading, + embeddingStorage: embeddingStorage) } } }) diff --git a/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift b/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift index f3f1ffce4..c16dc918e 100644 --- a/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift +++ b/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift @@ -151,13 +151,15 @@ public final class MTPDrafterModelFactory: GenericModelFactory { modelDirectory: modelDirectory, model: model, perLayerQuantization: baseConfig.perLayerQuantization, weightFileSelection: configuration.weightFileSelection, - excludedComponents: configuration.excludedComponents + excludedComponents: configuration.excludedComponents, + embeddingStorage: configuration.embeddingStorage ) let modelConfig = ModelConfiguration( directory: modelDirectory, tokenizerSource: nil, - defaultPrompt: "" + defaultPrompt: "", + embeddingStorage: configuration.embeddingStorage ) return MTPDrafterContext(configuration: modelConfig, model: model) } diff --git a/Libraries/MLXLMCommon/ModelConfiguration.swift b/Libraries/MLXLMCommon/ModelConfiguration.swift index b2f76e940..8c5690190 100644 --- a/Libraries/MLXLMCommon/ModelConfiguration.swift +++ b/Libraries/MLXLMCommon/ModelConfiguration.swift @@ -148,6 +148,9 @@ public struct ModelConfiguration: Sendable { /// ``ModelComponentsProviding``. public var excludedComponents: Set = [] + /// Storage for supported frozen, lookup-only embedding tables. + public var embeddingStorage: EmbeddingStoragePolicy = .automatic + /// Overrides the ``MessageGenerator`` the model would otherwise supply. /// /// A model class is shared by every checkpoint of its model type, so a fine-tune that @@ -170,7 +173,8 @@ public struct ModelConfiguration: Sendable { toolCallFormat: ToolCallFormat? = nil, reasoningConfig: ReasoningConfig? = nil, messageGenerator: (any MessageGenerator)? = nil, - generationConfig: GenerationConfigFile? = nil + generationConfig: GenerationConfigFile? = nil, + embeddingStorage: EmbeddingStoragePolicy = .automatic ) { self.id = .id(id, revision: revision) self.modelSubdirectory = modelSubdirectory @@ -183,6 +187,7 @@ public struct ModelConfiguration: Sendable { self.reasoningConfig = reasoningConfig self.messageGenerator = messageGenerator self.generationConfig = generationConfig + self.embeddingStorage = embeddingStorage } public init( @@ -195,7 +200,8 @@ public struct ModelConfiguration: Sendable { toolCallFormat: ToolCallFormat? = nil, reasoningConfig: ReasoningConfig? = nil, messageGenerator: (any MessageGenerator)? = nil, - generationConfig: GenerationConfigFile? = nil + generationConfig: GenerationConfigFile? = nil, + embeddingStorage: EmbeddingStoragePolicy = .automatic ) { self.id = .directory(directory) self.modelSubdirectory = modelSubdirectory @@ -208,6 +214,7 @@ public struct ModelConfiguration: Sendable { self.reasoningConfig = reasoningConfig self.messageGenerator = messageGenerator self.generationConfig = generationConfig + self.embeddingStorage = embeddingStorage } /// Maps this configuration's behavioral properties into a @@ -231,7 +238,7 @@ public struct ModelConfiguration: Sendable { messageGenerator: messageGenerator, generationConfig: generationConfig, weightFileSelection: weightFileSelection, - excludedComponents: excludedComponents) + excludedComponents: excludedComponents, embeddingStorage: embeddingStorage) } /// Validated, canonical repository-relative model directory. @@ -287,6 +294,7 @@ extension ModelConfiguration: Equatable { && lhs.weightFileSelection == rhs.weightFileSelection && lhs.excludedComponents == rhs.excludedComponents && lhs.generationConfig == rhs.generationConfig + && lhs.embeddingStorage == rhs.embeddingStorage && sameMessageGenerator(lhs.messageGenerator, rhs.messageGenerator) } diff --git a/Libraries/MLXLMCommon/ModelConversion.swift b/Libraries/MLXLMCommon/ModelConversion.swift index c08b6d788..5b966c226 100644 --- a/Libraries/MLXLMCommon/ModelConversion.swift +++ b/Libraries/MLXLMCommon/ModelConversion.swift @@ -218,7 +218,7 @@ public enum ModelConversionError: LocalizedError, Equatable { /// Quantize and save an already-instantiated model from a compatible safetensors directory. /// /// The function loads safetensors weights, runs the model's sanitizer through -/// ``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:)-858j8``, applies quantization, +/// ``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:embeddingStorage:)-1uqs8``, applies quantization, /// writes safetensors shards and an index, copies tokenizer/config sidecar files, and updates /// `config.json` with the requested quantization block. public func convert( diff --git a/Libraries/MLXLMCommon/ModelMemory.swift b/Libraries/MLXLMCommon/ModelMemory.swift index 4773f398a..a2cd2876f 100644 --- a/Libraries/MLXLMCommon/ModelMemory.swift +++ b/Libraries/MLXLMCommon/ModelMemory.swift @@ -33,15 +33,29 @@ public struct ModelMemory: Sendable, Equatable { public let components: [Component] /// Total bytes attributed to the model and its loaded components. public var total: Int { model + components.reduce(0) { $0 + $1.bytes } } + /// Bytes of ``model`` in file-backed embedding tables. + /// + /// The system reads these pages when a lookup uses them and can reclaim them later, + /// so ``paged`` is usually smaller. See ``EmbeddingStoragePolicy``. + public let backed: Int + /// Bytes of ``backed`` paged in when measured. + /// + /// These pages are clean file pages, so the system can reclaim them under memory + /// pressure. Another process that reads the same checkpoint shares them. + public let paged: Int public init(model: Int) { self.model = model self.components = [] + self.backed = 0 + self.paged = 0 } - init(model: Int, components: [Component]) { + init(model: Int, components: [Component], backed: Int, paged: Int) { self.model = model self.components = components + self.backed = backed + self.paged = paged } } @@ -86,7 +100,10 @@ extension BaseLanguageModel { totalBytes = currentBytes } } - return ModelMemory(model: model, components: breakdown) + let backed = fileBackedEmbeddingArrays(in: self) + return ModelMemory( + model: model, components: breakdown, backed: Memory.bufferSize(backed), + paged: pagedBytes(of: backed)) } } } diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index d50a4524d..6b92b17e2 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -1201,13 +1201,18 @@ final class Gemma4TextBackbone: Module { /// Module-internal — also consumed by `Gemma4Assistant.swift` (the MTP drafter /// reaches `embed_tokens` / `embed_scale` / `config.layer_types` through this). -final class Gemma4TextLanguageModel: Module, KVCacheDimensionProvider { +final class Gemma4TextLanguageModel: Module, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding +{ let config: Gemma4TextConfiguration let finalLogitSoftcapping: Float? @ModuleInfo(key: "model") var model: Gemma4TextBackbone @ModuleInfo(key: "lm_head") var lmHead: Linear? + var inputOnlyEmbeddings: [Embedding] { + [model.embedTokensPerLayer].compactMap { $0 } + (lmHead == nil ? [] : [model.embedTokens]) + } + var kvHeads: [Int] { (0 ..< config.hiddenLayers).map { idx in let layerType = config.layerTypes[idx] @@ -1378,7 +1383,9 @@ package typealias Gemma4MultimodalEmbedder = MLXLMCommon.Gemma4MultimodalEmbedde // MARK: - Model -public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider, SuppressedTokensProviding { +public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider, SuppressedTokensProviding, + InputOnlyEmbeddingsProviding +{ @ModuleInfo(key: "vision_tower") private var visionTower: Gemma4VisionModel /// Module-internal — also reached by `Gemma4Assistant.swift` (drafter `bind()` /// walks here to cache the target's input embeddings, embed scale, and @@ -1392,6 +1399,7 @@ public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider, Suppresse public var kvHeads: [Int] { languageModel.kvHeads } public var kvCacheStart: KVCacheStart { .deferred } public var loraLayers: [Module] { languageModel.model.layers } + public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings } /// Final-norm hidden states of the text decoder for `input`, `(B, L, hiddenSize)`: the /// tensor the LM head consumes, built as `prepare` builds it, without the head or a cache. @@ -1857,7 +1865,7 @@ private final class Gemma4UnifiedVisionEmbedder: Module { } public final class Gemma4Unified: Module, VLMModel, KVCacheDimensionProvider, - SuppressedTokensProviding + SuppressedTokensProviding, InputOnlyEmbeddingsProviding { @ModuleInfo(key: "language_model") private var languageModel: Gemma4TextLanguageModel @ModuleInfo(key: "vision_embedder") private var visionEmbedder: Gemma4UnifiedVisionEmbedder? @@ -1870,6 +1878,7 @@ public final class Gemma4Unified: Module, VLMModel, KVCacheDimensionProvider, public var kvHeads: [Int] { languageModel.kvHeads } public var kvCacheStart: KVCacheStart { .deferred } public var loraLayers: [Module] { languageModel.model.layers } + public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings } /// Final-norm hidden states of the text decoder for `input`, `(B, L, hiddenSize)`: the /// tensor the LM head consumes, built as `prepare` builds it, without the head or a cache. diff --git a/Libraries/MLXVLM/Models/Inkling2.swift b/Libraries/MLXVLM/Models/Inkling2.swift index 00defc9c2..be86300cc 100644 --- a/Libraries/MLXVLM/Models/Inkling2.swift +++ b/Libraries/MLXVLM/Models/Inkling2.swift @@ -1902,7 +1902,9 @@ private final class Inkling2Vision: Module { /// Inkling 2 Mini and Inkling 2 Small: a multimodal mixture-of-experts model whose text stack /// can run its middle layers several times per token. -public final class Inkling2: Module, VLMModel, KVCacheDimensionProvider { +public final class Inkling2: Module, VLMModel, KVCacheDimensionProvider, + InputOnlyEmbeddingsProviding +{ @ModuleInfo(key: "language_model") private var languageModel: Inkling2TextModel @ModuleInfo(key: "vision_tower") private var visionTower: Inkling2VisionModel? @ModuleInfo(key: "lm_head") private var lmHead: Linear @@ -1927,6 +1929,7 @@ public final class Inkling2: Module, VLMModel, KVCacheDimensionProvider { return text.layerVisits.map { text.isSliding($0) ? text.slidingKVHeads : text.kvHeads } } public var kvCacheStart: KVCacheStart { .deferred } + public var inputOnlyEmbeddings: [Embedding] { [languageModel.embedTokens] } public init(_ config: Inkling2Configuration) { self.config = config diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index 02ab3cdaf..5152fd876 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -1632,7 +1632,11 @@ private final class Qwen35Vision: Module { } } -public class Qwen35: Module, VLMModel { +public class Qwen35: Module, VLMModel, InputOnlyEmbeddingsProviding { + public var inputOnlyEmbeddings: [Embedding] { + languageModel.lmHead == nil ? [] : [languageModel.model.embedTokens] + } + @ModuleInfo(key: "vision_tower") private var visionModel: Qwen3VLVision.VisionModel? @ModuleInfo(key: "language_model") var languageModel: Qwen35Language.LanguageModel diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 8f5c56248..fe1d1d5ca 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -507,7 +507,8 @@ public final class VLMModelFactory: GenericModelFactory { modelDirectory: modelDirectory, model: model, perLayerQuantization: baseConfig.perLayerQuantization, weightFileSelection: configuration.weightFileSelection, - excludedComponents: configuration.excludedComponents) + excludedComponents: configuration.excludedComponents, + embeddingStorage: configuration.embeddingStorage) let tokenizer = try await tokenizerTask try model.validate(tokenizer: tokenizer) @@ -552,7 +553,8 @@ public final class VLMModelFactory: GenericModelFactory { toolCallFormat: mutableConfiguration.toolCallFormat, reasoningConfig: mutableConfiguration.reasoningConfig, messageGenerator: mutableConfiguration.messageGenerator, - generationConfig: mutableConfiguration.generationConfig) + generationConfig: mutableConfiguration.generationConfig, + embeddingStorage: configuration.embeddingStorage) return .init( configuration: modelConfig, model: model, processor: processor, diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift new file mode 100644 index 000000000..db8816e91 --- /dev/null +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -0,0 +1,850 @@ +// Copyright © 2026 Apple Inc. + +#if canImport(Darwin) +import Foundation +import MLX +import MLXLLM +import MLXNN +import MLXScriptedLM +import XCTest + +@testable import MLXLMCommon +@testable import MLXVLM + +final class FileBackedEmbeddingTests: XCTestCase { + private final class Model: Module, BaseLanguageModel, InputOnlyEmbeddingsProviding { + let lookupOnly: Bool + var inputOnlyEmbeddings: [Embedding] { lookupOnly ? [embedding] : [] } + @ModuleInfo(key: "embedding") var embedding: Embedding + + init(_ embedding: Embedding, lookupOnly: Bool = true) { + self.lookupOnly = lookupOnly + _embedding.wrappedValue = embedding + super.init() + } + } + + private final class AliasedModel: Module, InputOnlyEmbeddingsProviding { + var inputOnlyEmbeddings: [Embedding] { [first] } + @ModuleInfo(key: "first") var first: Embedding + @ModuleInfo(key: "second") var second: Embedding + + init(_ embedding: Embedding) { + _first.wrappedValue = embedding + _second.wrappedValue = embedding + super.init() + } + } + + private final class CustomEmbedding: QuantizedEmbedding {} + + private final class Layer: Module { + @ModuleInfo(key: "tables") var tables: [Embedding] + + init(_ tables: [Embedding]) { + _tables.wrappedValue = tables + super.init() + } + } + + private final class LayeredModel: Module, InputOnlyEmbeddingsProviding { + var inputOnlyEmbeddings: [Embedding] { [layers[1].tables[1]] } + let layers: [Layer] + + init(_ layers: [Layer]) { + self.layers = layers + super.init() + } + } + + private func embedding( + dtype: DType = .bfloat16, bits: Int = 4, groupSize: Int = 64 + ) -> QuantizedEmbedding { + let values = withRandomState(MLXRandom.RandomState(seed: 42)) { + MLXRandom.normal([257, 256]).asType(dtype) + } + return QuantizedEmbedding(weight: values, groupSize: groupSize, bits: bits) + } + + private func assertIdentical( + _ actual: MLXArray, _ expected: MLXArray, + file: StaticString = #filePath, line: UInt = #line + ) { + XCTAssertEqual(actual.dtype, expected.dtype, file: file, line: line) + XCTAssertEqual(actual.shape, expected.shape, file: file, line: line) + XCTAssertEqual( + actual.asData(access: .copy).data, expected.asData(access: .copy).data, + file: file, line: line) + } + + private func address(of array: MLXArray) -> UInt? { + array.asData(access: .noCopy).data.withUnsafeBytes { + $0.baseAddress.map(UInt.init(bitPattern:)) + } + } + + func testLoaderSelectsDeclaredSparseTablesAndHonorsResidentOverride() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let source = Model(embedding()) + try save( + arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), + url: directory.appendingPathComponent("model.safetensors")) + let automatic = Model(embedding()) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .backed) + XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) + assertIdentical( + automatic.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) + let firstEmbedding = automatic.embedding + let firstOutput = firstEmbedding(MLXArray([0, 256])).asData(access: .copy).data + source.apply { $0.dtype.isFloatingPoint ? $0 * 2 : $0 } + let replacement = directory.appendingPathComponent("replacement.safetensors") + try save( + arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), + url: replacement) + let original = directory.appendingPathComponent("model.safetensors") + try FileManager.default.removeItem(at: original) + try FileManager.default.moveItem(at: replacement, to: original) + XCTAssertEqual(firstEmbedding(MLXArray([0, 256])).asData(access: .copy).data, firstOutput) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .backed) + XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) + XCTAssertFalse(automatic.embedding === firstEmbedding) + assertIdentical( + automatic.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .resident) + XCTAssertTrue(type(of: automatic.embedding) == QuantizedEmbedding.self) + assertIdentical( + automatic.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) + let resident = Model(embedding()) + try loadWeights(modelDirectory: directory, model: resident, embeddingStorage: .resident) + XCTAssertTrue(type(of: resident.embedding) == QuantizedEmbedding.self) + let dense = Model(embedding(), lookupOnly: false) + try loadWeights(modelDirectory: directory, model: dense, embeddingStorage: .backed) + XCTAssertTrue(type(of: dense.embedding) == QuantizedEmbedding.self) + let fitting = Model(embedding()) + try loadWeights(modelDirectory: directory, model: fitting) + XCTAssertTrue(type(of: fitting.embedding) == QuantizedEmbedding.self) + } + + func testAutomaticStorageFileBacksOnlyCheckpointsLargerThanTheWorkingSet() { + let automatic = EmbeddingStoragePolicy.automatic + XCTAssertEqual(automatic.resolved(checkpointBytes: 8, workingSetBytes: 8), .resident) + XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: 8), .backed) + XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: nil), .resident) + XCTAssertEqual( + EmbeddingStoragePolicy.backed.resolved(checkpointBytes: 1, workingSetBytes: 8), + .backed) + XCTAssertEqual( + EmbeddingStoragePolicy.resident.resolved(checkpointBytes: 9, workingSetBytes: 8), + .resident) + } + + func testFileBackedLookupsClampOutOfRangeRows() throws { + let directory = FileManager.default.temporaryDirectory + let source = embedding() + let quantized = try FileBackedQuantizedEmbedding( + weight: fileBackedArray(source.weight, directory: directory), + scales: fileBackedArray(source.scales, directory: directory), + biases: fileBackedArray(XCTUnwrap(source.biases), directory: directory), + groupSize: source.groupSize, bits: source.bits) + let dense = try FileBackedEmbedding( + weight: fileBackedArray(source.weight, directory: directory)) + let last = Int32(source.weight.dim(0) - 1) + let signed = MLXArray([last + 1, Int32.max, Int32.min, -1]) + let signedRows = MLXArray([last, last, -last - 1, -1]) + let unsigned = MLXArray([UInt32(last) + 1, UInt32.max]) + let unsignedRows = MLXArray([UInt32(last), UInt32(last)]) + assertIdentical(quantized(signed), source(signedRows)) + assertIdentical(quantized(unsigned), source(unsignedRows)) + assertIdentical(dense(signed), source.weight.take(signedRows, axis: 0)) + assertIdentical(dense(unsigned), source.weight.take(unsignedRows, axis: 0)) + } + + func testStoragePolicySurvivesConfigurationResolution() { + let directory = FileManager.default.temporaryDirectory + let configuration = ModelConfiguration(id: "test/model", embeddingStorage: .resident) + let resolved = configuration.resolved( + modelDirectory: directory, tokenizerDirectory: directory) + XCTAssertEqual(resolved.embeddingStorage, .resident) + XCTAssertEqual(ModelConfiguration(directory: directory).embeddingStorage, .automatic) + XCTAssertNotEqual(configuration, ModelConfiguration(id: "test/model")) + } + + func testModelsDeclareOnlyUntiedInputEmbeddings() throws { + for tied in [false, true] { + let data = Data( + """ + {"model_type":"qwen3_5","hidden_size":256,"num_hidden_layers":1,"intermediate_size":512, + "num_attention_heads":4,"num_key_value_heads":2,"head_dim":64, + "rms_norm_eps":0.000001,"vocab_size":257,"full_attention_interval":1, + "num_experts":2,"num_experts_per_tok":1,"decoder_sparse_step":1, + "mlp_only_layers":[],"moe_intermediate_size":256, + "max_position_embeddings":1024,"original_max_position_embeddings":1024, + "tie_word_embeddings":\(tied)} + """.utf8) + let decoder = JSONDecoder() + let models: [any InputOnlyEmbeddingsProviding] = [ + LlamaModel(try decoder.decode(LlamaConfiguration.self, from: data)), + Qwen2Model(try decoder.decode(Qwen2Configuration.self, from: data)), + Qwen3Model(try decoder.decode(Qwen3Configuration.self, from: data)), + Qwen3MoEModel(try decoder.decode(Qwen3MoEConfiguration.self, from: data)), + Phi3Model(try decoder.decode(Phi3Configuration.self, from: data)), + Qwen35TextModel(try decoder.decode(Qwen35TextConfiguration.self, from: data)), + Qwen35Model(try decoder.decode(Qwen35Configuration.self, from: data)), + ] + for model in models { + XCTAssertEqual(model.inputOnlyEmbeddings.count, tied ? 0 : 1) + if let input = model.inputOnlyEmbeddings.first { + XCTAssertTrue(model.namedModules().contains { $0.1 === input }) + } + } + } + } + + func testGemma4DeclaresPerLayerAndUntiedInputTables() throws { + for tied in [false, true] { + let data = Data( + """ + {"model_type":"gemma4_text","hidden_size":8,"num_hidden_layers":2, + "intermediate_size":16,"num_attention_heads":2,"num_key_value_heads":1, + "head_dim":4,"global_head_dim":4,"vocab_size":12,"vocab_size_per_layer_input":12, + "hidden_size_per_layer_input":4,"num_kv_shared_layers":0,"sliding_window":8, + "sliding_window_pattern":1,"max_position_embeddings":32,"rms_norm_eps":0.000001, + "rope_traditional":false,"use_double_wide_mlp":false,"enable_moe_block":false, + "attention_k_eq_v":false,"layer_types":["full_attention","full_attention"], + "rope_parameters":{},"tie_word_embeddings":\(tied)} + """.utf8) + let decoder = JSONDecoder() + let text = Gemma4TextModel( + try decoder.decode(MLXLLM.Gemma4TextConfiguration.self, from: data)) + let vision = Gemma4TextLanguageModel( + try decoder.decode(MLXVLM.Gemma4TextConfiguration.self, from: data)) + let models: [any InputOnlyEmbeddingsProviding] = [text, vision] + for model in models { + let names = model.inputOnlyEmbeddings.compactMap { embedding in + model.namedModules().first { $0.1 === embedding }?.0 + } + let expected = + ["model.embed_tokens_per_layer"] + (tied ? [] : ["model.embed_tokens"]) + XCTAssertEqual(Set(names), Set(expected)) + XCTAssertEqual(names.count, expected.count) + } + } + } + + func testPhiMoEDeclaresItsInputTable() throws { + let data = Data( + """ + {"model_type":"phimoe","vocab_size":257,"hidden_size":256,"intermediate_size":512, + "num_hidden_layers":1,"num_attention_heads":4,"num_key_value_heads":2, + "max_position_embeddings":1024,"original_max_position_embeddings":1024, + "rms_norm_eps":0.000001,"num_local_experts":2,"num_experts_per_tok":1,"rope_theta":10000} + """.utf8) + let model = PhiMoEModel(try JSONDecoder().decode(PhiMoEConfiguration.self, from: data)) + XCTAssertEqual(model.inputOnlyEmbeddings.count, 1) + XCTAssertTrue(model.namedModules().contains { $0.1 === model.inputOnlyEmbeddings.first }) + } + + func testInkling2AndRicursiveDeclareTheirTokenTables() throws { + let decoder = JSONDecoder() + let models: [(any InputOnlyEmbeddingsProviding, String)] = [ + ( + Inkling2( + try decoder.decode( + Inkling2Configuration.self, from: Data(Inkling2ModelTests.tinyJSON.utf8))), + "language_model.embed_tokens" + ), + ( + RicursiveModel( + try decoder.decode( + RicursiveConfiguration.self, + from: Data(RicursiveReferenceValues.configuration.utf8))), + "model.embed_tokens" + ), + ] + for (model, name) in models { + let original = try XCTUnwrap(model.inputOnlyEmbeddings.first) + XCTAssertEqual(model.inputOnlyEmbeddings.count, 1) + XCTAssertTrue(model.namedModules().first { $0.0 == name }?.1 === original) + model.freeze() + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory), 1) + let table = try XCTUnwrap(model.inputOnlyEmbeddings.first) + XCTAssertTrue(table is FileBackedEmbedding) + XCTAssertTrue(model.namedModules().first { $0.0 == name }?.1 === table) + let indices = MLXArray([0, 5, -1]) + assertIdentical(table(indices), original(indices)) + } + } + + func testTablesInsideModuleArraysAreReplacedInPlace() throws { + let source = embedding() + let model = LayeredModel([ + Layer([embedding(), embedding()]), Layer([embedding(), source, embedding()]), + ]) + let unchanged = model.layers.map { $0.tables.map(ObjectIdentifier.init) } + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory), 1) + XCTAssertTrue(model.layers[1].tables[1] is FileBackedQuantizedEmbedding) + XCTAssertEqual(model.layers[0].tables.map(ObjectIdentifier.init), unchanged[0]) + XCTAssertEqual( + [0, 2].map { ObjectIdentifier(model.layers[1].tables[$0]) }, + [unchanged[1][0], unchanged[1][2]]) + let indices = MLXArray([0, 256, -1]) + assertIdentical(model.layers[1].tables[1](indices), source(indices)) + } + + func testLookupAndLinearProjectionPreserveAllBits() throws { + let directory = FileManager.default.temporaryDirectory + for dtype in [DType.float16, .bfloat16, .float32] { + for bits in [2, 3, 4, 5, 6, 8] { + let original = embedding(dtype: dtype, bits: bits) + let model = Model(original) + model.train(false) + XCTAssertEqual(try prepareEmbeddingStorage(in: model, directory: directory), 1) + XCTAssertFalse(model.embedding.training) + XCTAssertTrue(model.embedding.trainableParameters().flattened().isEmpty) + for indices in [ + MLXArray(Int32(0)), MLXArray([0, 256, 19, 19, -1, -257]), + MLXArray([0, 256, 19, 19, 17, 4]).reshaped(2, 3), + ] { + assertIdentical(model.embedding(indices), original(indices)) + } + let input = original(MLXArray([0, 1])) + assertIdentical(model.embedding.asLinear(input), original.asLinear(input)) + for (name, value) in original.parameters().flattened() { + let copied = Dictionary( + uniqueKeysWithValues: model.embedding.parameters().flattened()) + let actual = try XCTUnwrap(copied[name]) + assertIdentical(actual, value) + } + } + } + } + + func testAdditionalAffineGroupSizesPreserveAllBits() throws { + for groupSize in [32, 128] { + for dtype in [DType.float16, .bfloat16, .float32] { + for bits in [2, 3, 4, 5, 6, 8] { + let original = embedding(dtype: dtype, bits: bits, groupSize: groupSize) + let model = Model(original) + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory) + let replacement = try XCTUnwrap(model.embedding as? QuantizedEmbedding) + XCTAssertEqual(replacement.groupSize, groupSize) + assertIdentical( + replacement(MLXArray([0, 256, -1])), original(MLXArray([0, 256, -1]))) + for (name, expected) in original.parameters().flattened() { + let actual = Dictionary( + uniqueKeysWithValues: replacement.parameters().flattened()) + assertIdentical(try XCTUnwrap(actual[name]), expected) + } + } + } + } + } + + private struct TestTokenizerLoader: TokenizerLoader { + func load(from directory: URL) async throws -> any Tokenizer { PseudoWordTokenizer() } + } + + func testQwen35FactoriesApplyStoragePolicyOnlyToUntiedInputTables() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + for tied in [false, true] { + let config = Data( + """ + {"model_type":"qwen3_5", "quantization":{"group_size":32,"bits":4}, + "text_config":{"model_type":"qwen3_5_text","hidden_size":256, + "num_hidden_layers":1,"intermediate_size":512,"num_attention_heads":4, + "num_key_value_heads":2,"head_dim":64,"vocab_size":257,"full_attention_interval":1, + "tie_word_embeddings":\(tied),"rope_parameters":{"type":"default", + "mrope_section":[8,12,12],"partial_rotary_factor":1.0,"rope_theta":100000}}, + "vision_config":{"model_type":"qwen3_5","depth":1,"hidden_size":32, + "intermediate_size":64,"out_hidden_size":256,"num_heads":4,"patch_size":2, + "spatial_merge_size":2,"temporal_patch_size":1,"num_position_embeddings":16}} + """.utf8) + try config.write(to: directory.appendingPathComponent("config.json")) + let decoded = try JSONDecoder().decode(MLXVLM.Qwen35Configuration.self, from: config) + let source = withRandomState(MLXRandom.RandomState(seed: 42)) { Qwen35(decoded) } + source.update(parameters: source.parameters().mapValues { $0.asType(.bfloat16) }) + let original = QuantizedEmbedding( + weight: source.languageModel.model.embedTokens.weight, groupSize: 32, bits: 4) + try source.update( + modules: ModuleChildren.unflattened([ + ("language_model.model.embed_tokens", original) + ]), verify: []) + try save( + arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), + metadata: ["format": "mlx"], + url: directory.appendingPathComponent("model.safetensors")) + var sequences: [[Int]] = [] + for policy in [EmbeddingStoragePolicy.backed, .resident] { + let configuration = ModelConfiguration( + directory: directory, embeddingStorage: policy + ) + .resolved(modelDirectory: directory, tokenizerDirectory: directory) + let text = try await LLMModelFactory.shared._load( + configuration: configuration, tokenizerLoader: TestTokenizerLoader()) + let vision = try await VLMModelFactory.shared._load( + configuration: configuration, tokenizerLoader: TestTokenizerLoader()) + XCTAssertTrue(text.model is Qwen35Model) + XCTAssertTrue(vision.model is Qwen35) + for (index, context) in [text, vision].enumerated() { + XCTAssertEqual(context.configuration.embeddingStorage, policy) + let provider = try XCTUnwrap(context.model as? any InputOnlyEmbeddingsProviding) + XCTAssertEqual(provider.inputOnlyEmbeddings.count, tied ? 0 : 1) + let table = try XCTUnwrap( + context.model.namedModules().first { + $0.0 == "language_model.model.embed_tokens" + }?.1 as? Embedding) + XCTAssertEqual( + table is FileBackedQuantizedEmbedding, !tied && policy == .backed) + assertIdentical( + table(MLXArray([0, 256, -1])), original(MLXArray([0, 256, -1]))) + var iterator = try TokenIterator( + input: LMInput(tokens: MLXArray([1, 17, 24])), model: context.model, + parameters: GenerateParameters(maxTokens: 4, temperature: 0)) + var tokens: [Int] = [] + while let token = iterator.next() { tokens.append(token) } + XCTAssertEqual(tokens.count, 4) + if policy == .backed { + sequences.append(tokens) + } else { + XCTAssertEqual(tokens, sequences[index]) + } + } + } + } + } + + func testCompiledLookupUsesCurrentIndices() throws { + let original = embedding() + let model = Model(original) + try prepareEmbeddingStorage(in: model, directory: FileManager.default.temporaryDirectory) + let lookup = CompiledTrace { model, arguments in + [model.embedding(arguments[0])] + } + for indices in [MLXArray([0, 256]), MLXArray([19, 19]), MLXArray([-1, 17])] { + assertIdentical(lookup(model, indices), original(indices)) + } + } + + func testSharedModulesStayShared() throws { + let model = AliasedModel(embedding()) + let directory = FileManager.default.temporaryDirectory + XCTAssertEqual(try prepareEmbeddingStorage(in: model, directory: directory), 1) + XCTAssertTrue(model.first === model.second) + } + + func testTrainableAndCustomEmbeddingsAreUnchanged() throws { + let trainable = embedding() + trainable.unfreeze() + let model = Model(trainable) + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory), 0) + XCTAssertTrue(model.embedding === trainable) + let custom = CustomEmbedding( + weight: trainable.weight, scales: trainable.scales, biases: trainable.biases, + groupSize: trainable.groupSize, bits: trainable.bits) + custom.freeze() + let customModel = Model(custom) + XCTAssertEqual( + try prepareEmbeddingStorage( + in: customModel, directory: FileManager.default.temporaryDirectory), 0) + XCTAssertTrue(customModel.embedding === custom) + } + + func testFailureKeepsOriginalEmbedding() { + let original = embedding() + let model = Model(original) + let missing = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + XCTAssertThrowsError(try prepareEmbeddingStorage(in: model, directory: missing)) + XCTAssertTrue(model.embedding === original) + } + + func testNoncontiguousArraysAndTemporaryFileCleanup() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let source = MLXArray((0 ..< 35).map(Float.init)).reshaped(5, 7).T + let mapped = try fileBackedArray(source, directory: directory) + assertIdentical(mapped, source) + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty) + assertIdentical(mapped + 1, source + 1) + } + + func testFrozenFloatingTablesPreserveLookupAndParameters() throws { + for dtype in [DType.float16, .bfloat16, .float32] { + let original = Embedding( + weight: MLXArray((0 ..< 3 * 256).map { Float($0) / 256 }).reshaped(3, 256).asType( + dtype)) + original.freeze() + let model = Model(original) + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory), 1) + XCTAssertTrue(model.embedding is FileBackedEmbedding) + for indices in [MLXArray(Int32(0)), MLXArray([0, 2, 2, -1]).reshaped(2, 2)] { + assertIdentical(model.embedding(indices), original(indices)) + } + assertIdentical(model.embedding.weight, original.weight) + assertIdentical(model.embedding.weight + 1, original.weight + 1) + assertIdentical( + model.embedding.asLinear(original(MLXArray([0]))), + original.asLinear(original(MLXArray([0])))) + } + let trainable = Embedding(embeddingCount: 257, dimensions: 256) + let model = Model(trainable) + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: FileManager.default.temporaryDirectory), 0) + XCTAssertTrue(model.embedding === trainable) + } + + func testLoaderMapsFrozenFloatingTables() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + for dtype in [DType.float16, .bfloat16, .float32] { + let source = Model( + Embedding( + weight: MLXArray((0 ..< 257 * 256).map { Float($0) / 256 }).reshaped(257, 256) + .asType(dtype))) + source.embedding.freeze() + let url = directory.appendingPathComponent("model.safetensors") + try saveCheckpoint(source, url: url) + let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) + model.embedding.freeze() + let storage = try XCTUnwrap( + CheckpointTensorStorage(model: model, policy: .backed, urls: [url])) + XCTAssertEqual(storage.mappings.count, 1) + let checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + XCTAssertNotNil( + try storage.array(matching: XCTUnwrap(checkpoint.weights["embedding.weight"]))) + try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .backed) + XCTAssertTrue(model.embedding is FileBackedEmbedding) + assertIdentical(model.embedding.weight, source.embedding.weight) + assertIdentical( + model.embedding(MLXArray([0, 256, -1])), source.embedding(MLXArray([0, 256, -1]))) + } + } + + func testModelMemoryReportsFileBackedTables() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + try saveCheckpoint( + Model(embedding()), url: directory.appendingPathComponent("model.safetensors")) + + let backed = Model(embedding()) + try loadWeights(modelDirectory: directory, model: backed, embeddingStorage: .backed) + XCTAssertTrue(backed.embedding is FileBackedQuantizedEmbedding) + let backedMemory = try backed.memory() + XCTAssertGreaterThan(backedMemory.backed, 0) + XCTAssertEqual(backedMemory.backed, backedMemory.model) + XCTAssertLessThanOrEqual(backedMemory.paged, backedMemory.backed) + eval(backed.embedding(MLXArray(Int32(0) ..< 257))) + XCTAssertEqual(try backed.memory().paged, backedMemory.backed) + + let resident = Model(embedding()) + try loadWeights(modelDirectory: directory, model: resident, embeddingStorage: .resident) + let residentMemory = try resident.memory() + XCTAssertGreaterThan(residentMemory.model, 0) + XCTAssertEqual(residentMemory.backed, 0) + XCTAssertEqual(residentMemory.paged, 0) + } + + func testPagedBytesCountOnlyTouchedPages() throws { + let page = Int(getpagesize()) + let length = 8 * page + guard + let pointer = mmap(nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0), + pointer != MAP_FAILED + else { throw POSIXError(.ENOMEM) } + let array = MLXArray(rawPointer: pointer, [length], dtype: .uint8) { + munmap(pointer, length) + } + XCTAssertEqual(pagedBytes(of: [array]), 0) + pointer.storeBytes(of: 1, toByteOffset: 2 * page + 5, as: UInt8.self) + XCTAssertEqual(pagedBytes(of: [array, array]), page) + XCTAssertEqual(pagedBytes(of: [array[(page + 1)...]]), page) + } + + func testOversizedBackingFailsBeforeReadingTheArray() throws { + let array = MLXArray.zeros([131073, 16384], dtype: .uint8) + let active = Memory.activeMemory + XCTAssertThrowsError( + try fileBackedArray(array, directory: FileManager.default.temporaryDirectory)) + XCTAssertEqual(Memory.activeMemory, active) + } + + private func saveCheckpoint(_ model: Model, url: URL, offset: Int = 0) throws { + try save( + arrays: Dictionary(uniqueKeysWithValues: model.parameters().flattened()), url: url) + let original = try Data(contentsOf: url) + let count = original.prefix(8).withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) } + .littleEndian + let padding = (offset - Int((count + 8) % 8) + 8) % 8 + var headerLength = (count + UInt64(padding)).littleEndian + var rebased = withUnsafeBytes(of: &headerLength) { Data($0) } + rebased.append(original.subdata(in: 8 ..< (8 + Int(count)))) + rebased.append(Data(repeating: 32, count: padding)) + rebased.append(original.subdata(in: (8 + Int(count)) ..< original.count)) + try rebased.write(to: url) + } + + func testCheckpointMappingBacksEveryOffsetAndPreservesAllBits() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + for dtype in [DType.float16, .bfloat16, .float32] { + for bits in [2, 3, 4, 5, 6, 8] { + for offset in 0 ..< 8 { + try autoreleasepool { + let original = Model(embedding(dtype: dtype, bits: bits)) + try saveCheckpoint(original, url: url, offset: offset) + let model = Model(embedding(dtype: dtype, bits: bits)) + let storage = try XCTUnwrap( + CheckpointTensorStorage( + model: model, policy: .backed, urls: [url], + directory: directory)) + var checkpoint = try loadModelCheckpoint( + urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + let loadedWeight = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + // The loader already returns file-backed storage, mapped or copied. + let retained = try XCTUnwrap(storage.array(matching: loadedWeight)) + XCTAssertEqual(address(of: loadedWeight), address(of: retained)) + try applyCheckpoint(checkpoint, to: model) + checkpoint.weights.removeAll() + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: directory, checkpoint: storage), 1) + XCTAssertTrue(model.embedding is FileBackedQuantizedEmbedding) + for indices in [ + MLXArray(Int32(0)), MLXArray([0, 256, 19, 19, -1, -257]), + MLXArray([0, 256, 19, 19, 17, 4]).reshaped(2, 3), + ] { + assertIdentical(model.embedding(indices), original.embedding(indices)) + } + let actual = Dictionary( + uniqueKeysWithValues: model.embedding.parameters().flattened()) + for (name, expected) in original.embedding.parameters().flattened() { + let value = try XCTUnwrap(actual[name]) + assertIdentical(value, expected) + assertIdentical(value + 1, expected + 1) + assertIdentical( + value.view(dtype: .uint64) + MLXArray(UInt64(1)), + expected.view(dtype: .uint64) + MLXArray(UInt64(1))) + let remainder = value.asData(access: .noCopy).data.withUnsafeBytes { + $0.baseAddress.map { Int(UInt(bitPattern: $0) % 8) } + } + XCTAssertEqual(remainder, 0) + } + let input = original.embedding(MLXArray([0, 1])) + assertIdentical( + model.embedding.asLinear(input), original.embedding.asLinear(input)) + let lookup = CompiledTrace { model, arguments in + [model.embedding(arguments[0])] + } + for indices in [MLXArray([0, 256]), MLXArray([19, -1])] { + assertIdentical(lookup(model, indices), original.embedding(indices)) + } + } + } + } + } + XCTAssertEqual( + try FileManager.default.contentsOfDirectory(atPath: directory.path), + ["model.safetensors"]) + } + + func testLoaderCopiesMisalignedTablesFromTheCheckpoint() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + // More than one copy chunk, and the last tensor in the file, so the copy ends at its end. + let rows = 8193 + let values = MLXArray.arange(rows * 1024, dtype: .float32).reshaped(rows, 1024) + let source = Model(Embedding(weight: values)) + source.embedding.freeze() + try saveCheckpoint(source, url: url, offset: 3) + let model = Model(Embedding(embeddingCount: rows, dimensions: 1024)) + model.embedding.freeze() + let storage = try XCTUnwrap( + CheckpointTensorStorage( + model: model, policy: .backed, urls: [url], directory: directory)) + let checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + let loaded = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + let retained = try XCTUnwrap(storage.array(matching: loaded)) + XCTAssertEqual(address(of: loaded), address(of: retained)) + assertIdentical(loaded, values) + XCTAssertEqual( + try FileManager.default.contentsOfDirectory(atPath: directory.path), + ["model.safetensors"]) + + try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .backed) + XCTAssertTrue(model.embedding is FileBackedEmbedding) + assertIdentical(model.embedding.weight, values) + let indices = MLXArray([0, 4096, 8191, 8192, -1]) + assertIdentical(model.embedding(indices), values.take(indices, axis: 0)) + } + + func testFailedCopyLoadsTheTableAndBacksItAfterLoading() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let source = Model(embedding()) + try saveCheckpoint(source, url: url, offset: 3) + let model = Model(embedding()) + let storage = try XCTUnwrap( + CheckpointTensorStorage( + model: model, policy: .backed, urls: [url], + directory: directory.appendingPathComponent("missing"))) + var checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + let loaded = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + XCTAssertThrowsError(try storage.array(matching: loaded)) + try applyCheckpoint(checkpoint, to: model) + checkpoint.weights.removeAll() + XCTAssertEqual( + try prepareEmbeddingStorage(in: model, directory: directory, checkpoint: storage), 1) + XCTAssertTrue(model.embedding is FileBackedQuantizedEmbedding) + assertIdentical( + model.embedding(MLXArray([0, 256, -1])), source.embedding(MLXArray([0, 256, -1]))) + } + + func testEarlyMappingRequiresKnownAffineQuantization() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let source = Model(embedding()) + try saveCheckpoint(source, url: url, offset: 0) + let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) + guard + let unknown = CheckpointTensorStorage( + model: model, policy: .backed, urls: [url]) + else { throw XCTSkip("File-backed embeddings require a Metal device") } + XCTAssertTrue(unknown.mappings.isEmpty) + for mode in ["affine", "mxfp4"] { + let quantization = try JSONDecoder().decode( + BaseConfiguration.Quantization.self, + from: Data("{\"group_size\":64,\"bits\":4,\"mode\":\"\(mode)\"}".utf8)) + let policy = BaseConfiguration.PerLayerQuantization( + quantization: quantization, perLayerQuantization: [:]) + let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) + let storage = try XCTUnwrap( + CheckpointTensorStorage( + model: model, policy: .backed, urls: [url], quantization: policy)) + XCTAssertEqual(storage.mappings.count, mode == "affine" ? 3 : 0) + if mode == "affine" { + var checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + checkpoint.perLayerQuantization = policy + try applyCheckpoint(checkpoint, to: model) + XCTAssertEqual( + try prepareEmbeddingStorage( + in: model, directory: directory.appendingPathComponent("missing"), + checkpoint: storage), 1) + assertIdentical( + model.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) + } + } + } + + func testCheckpointStorageMatchesRenamesAndRejectsChangedSources() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let model = Model(embedding()) + try saveCheckpoint(model, url: url, offset: 0) + guard + let storage = CheckpointTensorStorage( + model: model, policy: .backed, urls: [url]) + else { throw XCTSkip("File-backed embeddings require a Metal device") } + let checkpoint = try loadModelCheckpoint(urls: [url]) + storage.record(checkpoint.weights) + let renamed = try checkpoint.mapNames { + $0.replacingOccurrences(of: "embedding", with: "renamed") + } + let source = try XCTUnwrap(renamed.weights["renamed.weight"]) + let mapped = try XCTUnwrap(try storage.array(matching: source)) + assertIdentical(mapped, source) + XCTAssertNil(try storage.array(matching: source + 1)) + let handle = try FileHandle(forWritingTo: url) + try handle.seekToEnd() + try handle.write(contentsOf: Data([0])) + try handle.close() + XCTAssertNil(try storage.array(matching: source)) + } + + func testRecordedSourcesSurviveInPlaceUpdates() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let model = Model(embedding()) + try saveCheckpoint(model, url: url, offset: 0) + guard + let storage = CheckpointTensorStorage( + model: model, policy: .backed, urls: [url]) + else { throw XCTSkip("File-backed embeddings require a Metal device") } + let checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + let loaded = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + let parameter = MLXArray.zeros(loaded.shape, dtype: loaded.dtype) + parameter._updateInternal(loaded) + let expected = loaded.asData(access: .copy).data + loaded._updateInternal(MLXArray.zeros(loaded.shape, dtype: loaded.dtype)) + let mapped = try XCTUnwrap(try storage.array(matching: parameter)) + XCTAssertEqual(mapped.asData(access: .copy).data, expected) + } + + func testCheckpointMappingSurvivesClosingAndUnlinkingSource() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("model.safetensors") + let model = Model(embedding()) + try saveCheckpoint(model, url: url, offset: 0) + var storage = CheckpointTensorStorage(model: model, policy: .backed, urls: [url]) + guard storage != nil else { + throw XCTSkip("File-backed embeddings require a Metal device") + } + let checkpoint = try loadModelCheckpoint(urls: [url]) + storage?.record(checkpoint.weights) + let source = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + let mapped = try XCTUnwrap(try storage?.array(matching: source)) + storage = nil + try FileManager.default.removeItem(at: url) + assertIdentical(mapped, source) + assertIdentical(mapped + 1, source + 1) + } +} +#endif