From b5760e28f0b1cb4db0571600e4b345fe40dfd492 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 18 Oct 2026 11:21:32 +0400 Subject: [PATCH 01/13] Keep frozen input embeddings in file-backed storage --- Libraries/MLXEmbedders/ModelFactory.swift | 6 +- Libraries/MLXLLM/LLMModelFactory.swift | 6 +- Libraries/MLXLLM/Models/Llama.swift | 3 +- Libraries/MLXLLM/Models/Phi3.swift | 3 +- Libraries/MLXLLM/Models/PhiMoE.swift | 4 +- Libraries/MLXLLM/Models/Qwen2.swift | 4 +- Libraries/MLXLLM/Models/Qwen3.swift | 4 +- Libraries/MLXLLM/Models/Qwen35.swift | 10 +- Libraries/MLXLLM/Models/Qwen3MoE.swift | 5 +- .../MLXLMCommon/CheckpointTensorStorage.swift | 226 ++++++++ .../MLXLMCommon/Documentation.docc/porting.md | 2 +- .../MLXLMCommon/Documentation.docc/using.md | 34 ++ Libraries/MLXLMCommon/Downloader.swift | 7 +- .../MLXLMCommon/FileBackedEmbedding.swift | 202 ++++++++ Libraries/MLXLMCommon/Load.swift | 58 ++- .../MLXLMCommon/MTPDrafterModelFactory.swift | 6 +- .../MLXLMCommon/ModelConfiguration.swift | 14 +- Libraries/MLXLMCommon/ModelConversion.swift | 2 +- Libraries/MLXVLM/VLMModelFactory.swift | 6 +- .../MLXLMTests/FileBackedEmbeddingTests.swift | 489 ++++++++++++++++++ 20 files changed, 1058 insertions(+), 33 deletions(-) create mode 100644 Libraries/MLXLMCommon/CheckpointTensorStorage.swift create mode 100644 Libraries/MLXLMCommon/FileBackedEmbedding.swift create mode 100644 Tests/MLXLMTests/FileBackedEmbeddingTests.swift diff --git a/Libraries/MLXEmbedders/ModelFactory.swift b/Libraries/MLXEmbedders/ModelFactory.swift index 5909ca4453..8f99aa11f6 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 @@ -258,7 +259,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 e826de9914..8339c1dd76 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -827,7 +827,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 @@ -854,7 +855,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/Llama.swift b/Libraries/MLXLLM/Models/Llama.swift index 0993784c76..d0c92b48a4 100644 --- a/Libraries/MLXLLM/Models/Llama.swift +++ b/Libraries/MLXLLM/Models/Llama.swift @@ -150,7 +150,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 eea18aad5a..747d5a44f4 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 a3b5242d2a..a97809e261 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] diff --git a/Libraries/MLXLLM/Models/Qwen2.swift b/Libraries/MLXLLM/Models/Qwen2.swift index 27916338ca..6120cb699a 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] diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index 11fa159911..c0617c3e6c 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -163,7 +163,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] diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 882309929c..859fecc592 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -1107,7 +1107,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] @@ -1307,7 +1311,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] diff --git a/Libraries/MLXLLM/Models/Qwen3MoE.swift b/Libraries/MLXLLM/Models/Qwen3MoE.swift index 06b131bfd5..6e3dbad240 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] diff --git a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift new file mode 100644 index 0000000000..65aca91923 --- /dev/null +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -0,0 +1,226 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +#if canImport(Darwin) +import Cmlx +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 maximumLength: Int + private let mappedAddresses = OSAllocatedUnfairLock(initialState: Set()) + + init(url: URL, maximumLength: Int) 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.maximumLength = maximumLength + } + + 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) } + } + + func array(for array: MLXArray, span: SafetensorSpan) throws -> MLXArray? { + // Keep larger scalar views aligned on runtimes with typed item reads. + guard unchanged(checkPath: false), + span.byteOffset.isMultiple(of: Int64(MemoryLayout.alignment)) + else { return nil } + let page = Int(getpagesize()) + 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) } + let alignedOffset = span.byteOffset / Int64(page) * Int64(page) + let offset = Int(span.byteOffset - alignedOffset) + let (extent, overflow) = array.nbytes.addingReportingOverflow(offset + page - 1) + guard !overflow else { throw POSIXError(.EOVERFLOW) } + let pageCount = extent / page + guard pageCount * page / array.itemSize <= Int32.max, + pageCount * page <= maximumLength + else { + throw POSIXError(.EOVERFLOW) + } + let length = pageCount * page + guard + let pointer = mmap( + nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, + handle.fileDescriptor, off_t(alignedOffset)), + pointer != MAP_FAILED + else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + _ = madvise(pointer, length, MADV_RANDOM) + let storage = MLXArray( + rawPointer: pointer, [pageCount, page / array.itemSize], dtype: array.dtype + ) { + munmap(pointer, length) + } + guard + mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) + == UnsafeRawPointer(pointer) + else { return nil } + let result = asStrided( + storage, array.shape, offset: offset / array.itemSize, stream: .cpu) + eval(result) + let address = UInt(bitPattern: pointer) + UInt(offset) + 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] + + init?( + model: BaseLanguageModel, policy: EmbeddingStoragePolicy, urls: [URL], + quantization: BaseConfiguration.PerLayerQuantization? = nil + ) { + #if canImport(Darwin) + guard policy == .automatic, + let provider = model as? any InputOnlyEmbeddingsProviding, + !provider.inputOnlyEmbeddings.isEmpty + else { return nil } + let maximumLength = GPU.deviceInfo().maxBufferSize + guard maximumLength > 0 else { return nil } + var locations: [String: Mapping] = [:] + do { + for url in urls { + let file = try File(url: url, maximumLength: maximumLength) + 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 } + var context = mlx_array_new() + guard mlx_array_set(&context, value.ctx) == 0 else { + mlx_array_free(context) + continue + } + let snapshot = MLXArray(context) + 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 627e788869..0c7b30508c 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/porting.md +++ b/Libraries/MLXLMCommon/Documentation.docc/porting.md @@ -315,7 +315,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 84c9544294..a685f4681c 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -29,6 +29,40 @@ 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 + +The loader can keep frozen input-only embedding tables in file-backed storage. +CPU row gathers read only the tokens in the input. Quantized tables use the existing +GPU dequantization. Floating tables keep their dtype. Models declare these tables with +``InputOnlyEmbeddingsProviding``. +Tied output tables, custom embedding classes, and unsupported quantization modes stay resident. + +``EmbeddingStoragePolicy/automatic`` is the default. The loader maps unchanged tables from the +original checkpoint when the tensor offset is a multiple of eight bytes and the buffer +fits the runtime's limits. +Known input tables are mapped before their data is read. Renamed tables can use the same +mapping after checkpoint preparation. Keep checkpoint contents unchanged while the model +is in use. + +Unaligned or transformed tables use aligned temporary storage. This path writes each +table once per load and requires temporary disk space. The file name is removed at creation; +its disk blocks are released with the final tensor. A backing-store failure retains normal +storage. Both paths request random-access paging to limit read-ahead for unused rows. The +operating system can reclaim unused clean pages under memory pressure. + +Use ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage: + +```swift +let configuration = ModelConfiguration( + id: "mlx-community/Qwen3.5-9B-4bit", + embeddingStorage: .resident) +``` + +MLX memory counters still include the full mapped buffer. Measure the process footprint +and system memory separately when checking the benefit. A wired-memory policy that covers +all MLX buffers can also make the full mapped table resident. File-backed storage does not +reduce the number of model parameters or their precision. + ## Downloaders and Tokenizers There are 3 general ways to select and use concrete Downloader and Tokenizer implementations: diff --git a/Libraries/MLXLMCommon/Downloader.swift b/Libraries/MLXLMCommon/Downloader.swift index fd50648031..9c73c4efc3 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 0000000000..ecddf1fb8a --- /dev/null +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -0,0 +1,202 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +#if canImport(Darwin) +import Cmlx +import Darwin +import os +#endif + +/// Storage for embedding tables during model loading. +public enum EmbeddingStoragePolicy: Sendable, Equatable { + /// File-back supported frozen, lookup-only tables on Apple platforms. + /// Other tables keep their normal storage. Temporary storage can be required. + case automatic + /// Keep all tables in normal MLX storage. + case resident +} + +/// 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 = Logger( + subsystem: "mlx-swift-lm", category: "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 +} + +#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) { + let page = Int(getpagesize()) + let (padded, overflow) = source.nbytes.addingReportingOverflow(page - 1) + guard source.nbytes > 0, !overflow else { throw POSIXError(.EINVAL) } + let pageCount = padded / page + let length = pageCount * page + guard length / source.itemSize <= Int32.max, + length <= GPU.deviceInfo().maxBufferSize + else { throw POSIXError(.EOVERFLOW) } + var path = Array(directory.appendingPathComponent("mlx-embedding-XXXXXX").path.utf8CString) + let descriptor = mkstemp(&path) + guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + defer { close(descriptor) } + guard unlink(path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + // 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(POSIXErrorCode(rawValue: errno) ?? .EIO) + } + let data = source.asData(access: .noCopyIfContiguous).data + try data.withUnsafeBytes { bytes in + guard let base = bytes.baseAddress else { throw POSIXError(.EINVAL) } + var position = 0 + while position < bytes.count { + let count = pwrite( + descriptor, base.advanced(by: position), + min(bytes.count - position, 8 * 1024 * 1024), + off_t(position) + ) + if count < 0 && errno == EINTR { continue } + guard count > 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + position += count + } + } + guard let pointer = mmap(nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, descriptor, 0), + pointer != MAP_FAILED + else { + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) + } + // Sparse lookups do not need read-ahead for neighboring rows. + _ = madvise(pointer, length, MADV_RANDOM) + let storage = MLXArray( + rawPointer: pointer, [pageCount, page / source.itemSize], dtype: source.dtype + ) { + munmap(pointer, length) + } + guard + mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) + == UnsafeRawPointer(pointer) + else { throw POSIXError(.ENOTSUP) } + let array = asStrided(storage, source.shape, stream: .cpu) + eval(array) + return array + } +} + +package final class FileBackedEmbedding: Embedding { + package override func callAsFunction(_ x: MLXArray) -> MLXArray { + weight.take(x, axis: 0, stream: .cpu) + } +} + +package final class FileBackedQuantizedEmbedding: QuantizedEmbedding { + package override func callAsFunction(_ x: MLXArray) -> MLXArray { + let indices = x.flattened() + return dequantized( + weight.take(indices, axis: 0, stream: .cpu), + scales: scales.take(indices, axis: 0, stream: .cpu), + biases: biases.map { $0.take(indices, axis: 0, stream: .cpu) }, + 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 = .automatic, 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 == .automatic || 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 .automatic: + 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 .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 .automatic: + replacement = try FileBackedEmbedding(weight: backed(embedding.weight)) + case .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 model.update(modules: ModuleChildren.unflattened(replacements), verify: []) + } + return prepared.count +} + +#endif diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 61b4361487..a167cc3488 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) @@ -406,13 +424,19 @@ private func topLevelSafetensorURLs(in modelDirectory: URL) -> [URL] { /// 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. +/// +/// Automatic embedding storage moves supported frozen tables declared by +/// ``InputOnlyEmbeddingsProviding`` into file-backed storage. This keeps +/// unused rows reclaimable without changing tensor values. Set `embeddingStorage` +/// to ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. 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( @@ -427,19 +451,29 @@ public func loadWeights( of: model, urls: weightURLs, excluded: excludedComponents, loading: componentLoading, perLayerQuantization: perLayerQuantization) + model.excludedCheckpointNamespaces + 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. @@ -455,7 +489,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 @@ -467,7 +501,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 @@ -485,7 +520,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 85534fe94c..a150fe9618 100644 --- a/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift +++ b/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift @@ -128,13 +128,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 b2f76e940e..8c5690190b 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 3552145fde..4f1d22bee9 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/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 430e137329..673eb092ae 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -487,7 +487,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 let processorConfiguration: VLMProcessorConfiguration @@ -531,7 +532,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 0000000000..6cb9f6e2ff --- /dev/null +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -0,0 +1,489 @@ +// Copyright © 2026 Apple Inc. + +#if canImport(Darwin) +import Foundation +import MLX +import MLXLLM +import MLXNN +import XCTest + +@testable import MLXLMCommon + +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 func embedding(dtype: DType = .bfloat16, bits: Int = 4) -> QuantizedEmbedding { + let values = withRandomState(MLXRandom.RandomState(seed: 42)) { + MLXRandom.normal([257, 256]).asType(dtype) + } + return QuantizedEmbedding(weight: values, groupSize: 64, 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) + } + + 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) + 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) + 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) + XCTAssertTrue(type(of: dense.embedding) == QuantizedEmbedding.self) + } + + 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 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 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 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: .automatic, 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) + 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 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 testCheckpointMappingSelectsAlignedStorageAndPreservesAllBits() 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: .automatic, urls: [url])) + var checkpoint = try loadModelCheckpoint( + urls: [url], mappings: storage.mappings) + storage.record(checkpoint.weights) + let loadedWeight = try XCTUnwrap(checkpoint.weights["embedding.weight"]) + let retained = try storage.array(matching: loadedWeight) + XCTAssertEqual( + retained != nil, offset.isMultiple(of: MemoryLayout.alignment)) + let loadedAddress = loadedWeight.asData(access: .noCopy).data + .withUnsafeBytes { + $0.baseAddress.map(UInt.init(bitPattern:)) + } + if let retained { + let retainedAddress = retained.asData(access: .noCopy).data + .withUnsafeBytes { + $0.baseAddress.map(UInt.init(bitPattern:)) + } + XCTAssertEqual(loadedAddress, retainedAddress) + } + 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 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: .automatic, 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: .automatic, 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: .automatic, 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 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: .automatic, 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 From fa0ff31b45024a9f8280b831f5db3e17028b9339 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 18 Oct 2026 15:25:22 +0400 Subject: [PATCH 02/13] Cover Qwen3.5 VLM embedding storage --- .../MLXLMCommon/Documentation.docc/using.md | 41 ++----- .../MLXLMCommon/FileBackedEmbedding.swift | 4 +- Libraries/MLXLMCommon/Load.swift | 8 +- Libraries/MLXVLM/Models/Qwen35.swift | 6 +- .../MLXLMTests/FileBackedEmbeddingTests.swift | 106 +++++++++++++++++- 5 files changed, 127 insertions(+), 38 deletions(-) diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index a685f4681c..d88b33515f 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -31,37 +31,20 @@ print(try await session.respond(to: "How about a great place to eat?")) ## Embedding storage -The loader can keep frozen input-only embedding tables in file-backed storage. -CPU row gathers read only the tokens in the input. Quantized tables use the existing -GPU dequantization. Floating tables keep their dtype. Models declare these tables with -``InputOnlyEmbeddingsProviding``. -Tied output tables, custom embedding classes, and unsupported quantization modes stay resident. - -``EmbeddingStoragePolicy/automatic`` is the default. The loader maps unchanged tables from the -original checkpoint when the tensor offset is a multiple of eight bytes and the buffer -fits the runtime's limits. -Known input tables are mapped before their data is read. Renamed tables can use the same -mapping after checkpoint preparation. Keep checkpoint contents unchanged while the model -is in use. - -Unaligned or transformed tables use aligned temporary storage. This path writes each -table once per load and requires temporary disk space. The file name is removed at creation; -its disk blocks are released with the final tensor. A backing-store failure retains normal -storage. Both paths request random-access paging to limit read-ahead for unused rows. The -operating system can reclaim unused clean pages under memory pressure. - -Use ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage: +``EmbeddingStoragePolicy/automatic`` 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. -```swift -let configuration = ModelConfiguration( - id: "mlx-community/Qwen3.5-9B-4bit", - embeddingStorage: .resident) -``` +Compatible checkpoint tensors map directly. Other eligible tables use temporary files, +with one copy per load and additional disk space. Loading peak memory can remain unchanged. +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 memory counters still include the full mapped buffer. Measure the process footprint -and system memory separately when checking the benefit. A wired-memory policy that covers -all MLX buffers can also make the full mapped table resident. File-backed storage does not -reduce the number of model parameters or their precision. +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 diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index ecddf1fb8a..e412dd3fe7 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -12,8 +12,8 @@ import os /// Storage for embedding tables during model loading. public enum EmbeddingStoragePolicy: Sendable, Equatable { - /// File-back supported frozen, lookup-only tables on Apple platforms. - /// Other tables keep their normal storage. Temporary storage can be required. + /// File-back supported frozen input tables on Apple platforms; other tables stay resident. + /// Keep checkpoint contents unchanged while the model is in use. case automatic /// Keep all tables in normal MLX storage. case resident diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index a167cc3488..2422bc63bf 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -425,10 +425,10 @@ private func topLevelSafetensorURLs(in modelDirectory: URL) -> [URL] { /// that do not load now and of the model's ``BaseLanguageModel/excludedCheckpointNamespaces`` are /// not read. /// -/// Automatic embedding storage moves supported frozen tables declared by -/// ``InputOnlyEmbeddingsProviding`` into file-backed storage. This keeps -/// unused rows reclaimable without changing tensor values. Set `embeddingStorage` -/// to ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. +/// Supported frozen tables declared by ``InputOnlyEmbeddingsProviding`` use file-backed +/// storage by default. Select ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. +/// +/// - 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, diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index a55fe4e826..4c2d2e69c3 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -1641,7 +1641,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/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index 6cb9f6e2ff..d79afeb298 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -5,9 +5,11 @@ 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 { @@ -36,11 +38,13 @@ final class FileBackedEmbeddingTests: XCTestCase { private final class CustomEmbedding: QuantizedEmbedding {} - private func embedding(dtype: DType = .bfloat16, bits: Int = 4) -> QuantizedEmbedding { + 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: 64, bits: bits) + return QuantizedEmbedding(weight: values, groupSize: groupSize, bits: bits) } private func assertIdentical( @@ -178,6 +182,104 @@ final class FileBackedEmbeddingTests: XCTestCase { } } + 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.automatic, .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 == .automatic) + 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 == .automatic { + sequences.append(tokens) + } else { + XCTAssertEqual(tokens, sequences[index]) + } + } + } + } + } + func testCompiledLookupUsesCurrentIndices() throws { let original = embedding() let model = Model(original) From fa789972c229d09f8b30e551cf5898d89f7b08d5 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Mon, 19 Oct 2026 12:30:48 +0400 Subject: [PATCH 03/13] Cover Gemma 4 per-layer embedding storage --- Libraries/MLXLLM/Models/Gemma4.swift | 4 ++- Libraries/MLXLLM/Models/Gemma4Text.swift | 8 ++++- Libraries/MLXVLM/Models/Gemma4.swift | 15 +++++++-- .../MLXLMTests/FileBackedEmbeddingTests.swift | 31 +++++++++++++++++++ 4 files changed, 53 insertions(+), 5 deletions(-) diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift index 6bcc462d90..ad5a0236e2 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 } diff --git a/Libraries/MLXLLM/Models/Gemma4Text.swift b/Libraries/MLXLLM/Models/Gemma4Text.swift index 1697283697..b44c1f1a08 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] diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index b462cb2de5..1e902bbafb 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -1179,13 +1179,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] @@ -1355,7 +1360,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 @@ -1368,6 +1375,7 @@ public final class Gemma4: Module, VLMModel, KVCacheDimensionProvider, Suppresse public var vocabularySize: Int { config.vocabularySize } public var kvHeads: [Int] { languageModel.kvHeads } 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. @@ -1831,7 +1839,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? @@ -1843,6 +1851,7 @@ public final class Gemma4Unified: Module, VLMModel, KVCacheDimensionProvider, public var vocabularySize: Int { config.vocabularySize } public var kvHeads: [Int] { languageModel.kvHeads } 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/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index d79afeb298..ea97cdff08 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -141,6 +141,37 @@ final class FileBackedEmbeddingTests: XCTestCase { } } + 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( """ From 0e09d6e8d0b266c5c73d6d19de0ccaeceba3fe4f Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Mon, 9 Nov 2026 14:04:00 +0400 Subject: [PATCH 04/13] Keep row-sharded lookup tables in file-backed storage Some checkpoints split one very large lookup table by rows into many tensors, such as the 128-shard n-gram table of qwen4_exp. ShardedEmbedding holds the shards as normal embeddings, so a model can declare them input only and each shard maps from the checkpoint like any other table. A lookup takes indices into the whole table. For uniformly quantized shards it gathers packed rows from every shard and dequantizes once; on file-backed shards the gathers stay on the CPU stream. --- .../MLXLMCommon/Documentation.docc/using.md | 3 + Libraries/MLXLMCommon/ShardedEmbedding.swift | 101 ++++++++++++++++++ .../MLXLMTests/FileBackedEmbeddingTests.swift | 70 ++++++++++++ 3 files changed, 174 insertions(+) create mode 100644 Libraries/MLXLMCommon/ShardedEmbedding.swift diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index d88b33515f..d7e0ab3f22 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -40,6 +40,9 @@ Compatible checkpoint tensors map directly. Other eligible tables use temporary with one copy per load and additional disk space. Loading peak memory can remain unchanged. Select ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. +A table that a checkpoint splits by rows into several tensors can use ``ShardedEmbedding``. +List its ``ShardedEmbedding/shards`` as input-only tables, and each shard is stored the same way. + > Important: Do not rewrite or truncate checkpoint files while the model is in use. > Use ``EmbeddingStoragePolicy/resident`` if files must change in place. diff --git a/Libraries/MLXLMCommon/ShardedEmbedding.swift b/Libraries/MLXLMCommon/ShardedEmbedding.swift new file mode 100644 index 0000000000..3baea595f0 --- /dev/null +++ b/Libraries/MLXLMCommon/ShardedEmbedding.swift @@ -0,0 +1,101 @@ +// Copyright © 2026 Apple Inc. + +import MLX +import MLXNN + +/// A lookup table split by rows into consecutive shards. +/// +/// Checkpoints store some very large tables this way, one tensor per shard. Each shard +/// is a normal `Embedding`, so a model can list ``shards`` in +/// ``InputOnlyEmbeddingsProviding/inputOnlyEmbeddings`` to keep them in file-backed storage. +public final class ShardedEmbedding: Module, UnaryLayer { + @ModuleInfo(key: "shards") public var shards: [Embedding] + + public init(shards: [Embedding]) { + precondition(!shards.isEmpty, "ShardedEmbedding needs at least one shard") + _shards.wrappedValue = shards + super.init() + } + + public convenience init(rowCounts: [Int], dimensions: Int) { + self.init(shards: rowCounts.map { Embedding(embeddingCount: $0, dimensions: dimensions) }) + } + + /// Looks up rows by their index in the whole table. Indices must be in `0 ..< rowCount`. + /// + /// Each shard is read once per call, so the cost grows with shards times indices. + public func callAsFunction(_ x: MLXArray) -> MLXArray { + var starts: [Int32] = [] + var rowCount = 0 + for shard in shards { + starts.append(Int32(rowCount)) + rowCount += shard.weight.dim(0) + } + precondition(rowCount <= Int(Int32.max), "ShardedEmbedding has too many rows") + let indices = x.flattened().asType(.int32) + let startArray = MLXArray(starts) + let shardIndices = + (indices.expandedDimensions(axis: -1) .>= startArray).asType(.int32).sum(axis: -1) - 1 + let localIndices = indices - startArray.take(shardIndices, axis: 0) + + // Rows outside a shard clamp to its first or last row, then are masked out. + func select(stream: StreamOrDevice, _ rows: (Int, MLXArray) -> MLXArray) -> MLXArray { + var result: MLXArray? + for (index, shard) in shards.enumerated() { + let local = clip(localIndices, min: 0, max: shard.weight.dim(0) - 1, stream: stream) + let selected = rows(index, local) + if let current = result { + let mask = (shardIndices .== Int32(index)).reshaped( + [-1] + Array(repeating: 1, count: selected.ndim - 1)) + result = which(mask, selected, current, stream: stream) + } else { + result = selected + } + } + return result! + } + + let output: MLXArray + if let quantized = uniformQuantizedShards() { + // Gather packed rows from every shard, then dequantize once. + let stream = gathersOnCPU ? StreamOrDevice.cpu : .default + let first = quantized[0] + let weight = select(stream: stream) { + quantized[$0].weight.take($1, axis: 0, stream: stream) + } + let scales = select(stream: stream) { + quantized[$0].scales.take($1, axis: 0, stream: stream) + } + let biases = + first.biases == nil + ? nil + : select(stream: stream) { + quantized[$0].biases!.take($1, axis: 0, stream: stream) + } + output = dequantized( + weight, scales: scales, biases: biases, groupSize: first.groupSize, + bits: first.bits, mode: first.mode) + } else { + output = select(stream: .default) { shards[$0]($1) } + } + return output.reshaped(x.shape + [-1]) + } + + private func uniformQuantizedShards() -> [QuantizedEmbedding]? { + let quantized = shards.compactMap { $0 as? QuantizedEmbedding } + guard quantized.count == shards.count, let first = quantized.first else { return nil } + let uniform = quantized.allSatisfy { + $0.groupSize == first.groupSize && $0.bits == first.bits && $0.mode == first.mode + && $0.globalScale == nil && ($0.biases == nil) == (first.biases == nil) + } + return uniform ? quantized : nil + } + + private var gathersOnCPU: Bool { + #if canImport(Darwin) + return shards.allSatisfy { $0 is FileBackedQuantizedEmbedding } + #else + return false + #endif + } +} diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index ea97cdff08..8788102af4 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -36,6 +36,16 @@ final class FileBackedEmbeddingTests: XCTestCase { } } + private final class ShardedModel: Module, BaseLanguageModel, InputOnlyEmbeddingsProviding { + var inputOnlyEmbeddings: [Embedding] { table.shards } + @ModuleInfo(key: "table") var table: ShardedEmbedding + + init(_ table: ShardedEmbedding) { + _table.wrappedValue = table + super.init() + } + } + private final class CustomEmbedding: QuantizedEmbedding {} private func embedding( @@ -618,5 +628,65 @@ final class FileBackedEmbeddingTests: XCTestCase { assertIdentical(mapped, source) assertIdentical(mapped + 1, source + 1) } + + func testShardedTableMapsEveryShardAndMatchesOneTable() 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 rowCounts = [100, 57, 100] + let values = withRandomState(MLXRandom.RandomState(seed: 7)) { + MLXRandom.normal([257, 256]).asType(.bfloat16) + } + let quantization = BaseConfiguration.Quantization(groupSize: 64, bits: 8) + let reference = QuantizedEmbedding(weight: values, groupSize: 64, bits: 8) + var start = 0 + let source = ShardedModel( + ShardedEmbedding( + shards: rowCounts.map { count in + defer { start += count } + return QuantizedEmbedding( + weight: values[start ..< start + count], groupSize: 64, bits: 8) + })) + try save( + arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), url: url) + + func placeholder() -> ShardedModel { + ShardedModel(ShardedEmbedding(rowCounts: rowCounts, dimensions: 256)) + } + let storage = try XCTUnwrap( + CheckpointTensorStorage( + model: placeholder(), policy: .automatic, urls: [url], + quantization: .init(quantization: quantization, perLayerQuantization: [:]))) + XCTAssertEqual(storage.mappings.count, rowCounts.count * 3) + + let indices = [ + MLXArray(Int32(0)), MLXArray([0, 99, 100, 156, 157, 256, 100, 0]), + MLXArray([256, 157, 156, 99, 3, 200]).reshaped(2, 3), + ] + for policy in [EmbeddingStoragePolicy.automatic, .resident] { + let model = placeholder() + try loadWeights( + modelDirectory: directory, model: model, quantization: quantization, + embeddingStorage: policy) + for shard in model.table.shards { + XCTAssertEqual(shard is FileBackedQuantizedEmbedding, policy == .automatic) + } + for index in indices { + assertIdentical(model.table(index), reference(index)) + } + } + + let floating = ShardedModel( + ShardedEmbedding(shards: [ + Embedding(weight: values[..<100]), Embedding(weight: values[100...]), + ])) + floating.freeze() + XCTAssertEqual(try prepareEmbeddingStorage(in: floating, directory: directory), 2) + XCTAssertTrue(floating.table.shards.allSatisfy { $0 is FileBackedEmbedding }) + let index = MLXArray([0, 99, 100, 256]) + assertIdentical(floating.table(index), values.take(index, axis: 0)) + } } #endif From 1d4bdf6feeabd5c3055c0cf25a65310095d4cd15 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sat, 14 Nov 2026 03:31:44 +0100 Subject: [PATCH 05/13] Report file-backed embedding bytes in ModelMemory ModelMemory.model counted file-backed embedding tables as resident weights, although the system reads their pages on use and can reclaim them. Add ModelMemory.fileBacked, the bytes of model held in those tables, so callers can size wired-memory tickets and memory charts. Also log through MLXLogger, like the rest of the libraries since #702. --- .../Documentation.docc/wired-memory.md | 4 ++++ .../MLXLMCommon/FileBackedEmbedding.swift | 18 ++++++++++++--- Libraries/MLXLMCommon/ModelMemory.swift | 13 +++++++++-- .../MLXLMTests/FileBackedEmbeddingTests.swift | 22 +++++++++++++++++++ 4 files changed, 52 insertions(+), 5 deletions(-) diff --git a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md index 70ae239936..23e87bbe3f 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md +++ b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md @@ -29,6 +29,10 @@ let weightBytes = memory.total component loads on first use. The KV cache is not included; read ``KVCacheStatus/memoryBytes`` for it. +``ModelMemory/fileBacked`` 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. + 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/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index e412dd3fe7..62cee9ab87 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -7,7 +7,6 @@ import MLXNN #if canImport(Darwin) import Cmlx import Darwin -import os #endif /// Storage for embedding tables during model loading. @@ -25,8 +24,7 @@ public protocol InputOnlyEmbeddingsProviding: Module { } #if canImport(Darwin) -private let embeddingStorageLogger = Logger( - subsystem: "mlx-swift-lm", category: "embedding-storage") +private let embeddingStorageLogger = MLXLogger(label: "embedding-storage") #endif package func prepareEmbeddingStorage( @@ -48,6 +46,20 @@ package func prepareEmbeddingStorage( #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 +} + #if canImport(Darwin) /// Copy one array into page-aligned temporary storage. The mapping owns its disk blocks. diff --git a/Libraries/MLXLMCommon/ModelMemory.swift b/Libraries/MLXLMCommon/ModelMemory.swift index 4773f398a1..a23fe89018 100644 --- a/Libraries/MLXLMCommon/ModelMemory.swift +++ b/Libraries/MLXLMCommon/ModelMemory.swift @@ -33,15 +33,22 @@ 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 the resident share is usually smaller. See ``EmbeddingStoragePolicy``. + public let fileBacked: Int public init(model: Int) { self.model = model self.components = [] + self.fileBacked = 0 } - init(model: Int, components: [Component]) { + init(model: Int, components: [Component], fileBacked: Int) { self.model = model self.components = components + self.fileBacked = fileBacked } } @@ -86,7 +93,9 @@ extension BaseLanguageModel { totalBytes = currentBytes } } - return ModelMemory(model: model, components: breakdown) + return ModelMemory( + model: model, components: breakdown, + fileBacked: Memory.bufferSize(fileBackedEmbeddingArrays(in: self))) } } } diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index 8788102af4..e1698da4d0 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -438,6 +438,28 @@ final class FileBackedEmbeddingTests: XCTestCase { } } + 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) + XCTAssertTrue(backed.embedding is FileBackedQuantizedEmbedding) + let backedMemory = try backed.memory() + XCTAssertGreaterThan(backedMemory.fileBacked, 0) + XCTAssertEqual(backedMemory.fileBacked, backedMemory.model) + + let resident = Model(embedding()) + try loadWeights(modelDirectory: directory, model: resident, embeddingStorage: .resident) + let residentMemory = try resident.memory() + XCTAssertGreaterThan(residentMemory.model, 0) + XCTAssertEqual(residentMemory.fileBacked, 0) + } + func testOversizedBackingFailsBeforeReadingTheArray() throws { let array = MLXArray.zeros([131073, 16384], dtype: .uint8) let active = Memory.activeMemory From 5c288d9615d36f7ad779d4345eb7637bfeae78d1 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 15 Nov 2026 14:01:05 +0100 Subject: [PATCH 06/13] Copy misaligned tables straight from the checkpoint Only tables at 8-byte aligned offsets map in place, and MLX's safetensors writer does not pad its header: the packed table was misaligned in all 10 mlx-community checkpoints checked. The loader read those tables into memory and copied them to a temporary file afterwards, so the loading peak did not drop. Copy them from the checkpoint into the temporary file while loading instead, so the whole table is never in memory. Mapping and both copy paths now share one implementation. --- .../MLXLMCommon/CheckpointTensorStorage.swift | 66 +++---- .../MLXLMCommon/Documentation.docc/using.md | 5 +- .../MLXLMCommon/FileBackedEmbedding.swift | 164 +++++++++++++----- .../MLXLMTests/FileBackedEmbeddingTests.swift | 88 ++++++++-- 4 files changed, 213 insertions(+), 110 deletions(-) diff --git a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift index 65aca91923..21298391b2 100644 --- a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -17,10 +17,10 @@ package final class CheckpointTensorStorage { let handle: FileHandle let url: URL let status: stat - let maximumLength: Int + let directory: URL private let mappedAddresses = OSAllocatedUnfairLock(initialState: Set()) - init(url: URL, maximumLength: Int) throws { + init(url: URL, directory: URL) throws { let handle = try FileHandle(forReadingFrom: url) var status = stat() guard fstat(handle.fileDescriptor, &status) == 0, @@ -29,7 +29,7 @@ package final class CheckpointTensorStorage { self.handle = handle self.url = url self.status = status - self.maximumLength = maximumLength + self.directory = directory } deinit { try? handle.close() } @@ -55,48 +55,25 @@ package final class CheckpointTensorStorage { 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? { - // Keep larger scalar views aligned on runtimes with typed item reads. - guard unchanged(checkPath: false), - span.byteOffset.isMultiple(of: Int64(MemoryLayout.alignment)) - else { return nil } - let page = Int(getpagesize()) + 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) } - let alignedOffset = span.byteOffset / Int64(page) * Int64(page) - let offset = Int(span.byteOffset - alignedOffset) - let (extent, overflow) = array.nbytes.addingReportingOverflow(offset + page - 1) - guard !overflow else { throw POSIXError(.EOVERFLOW) } - let pageCount = extent / page - guard pageCount * page / array.itemSize <= Int32.max, - pageCount * page <= maximumLength - else { - throw POSIXError(.EOVERFLOW) - } - let length = pageCount * page - guard - let pointer = mmap( - nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, - handle.fileDescriptor, off_t(alignedOffset)), - pointer != MAP_FAILED - else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } - _ = madvise(pointer, length, MADV_RANDOM) - let storage = MLXArray( - rawPointer: pointer, [pageCount, page / array.itemSize], dtype: array.dtype - ) { - munmap(pointer, length) - } - guard - mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) - == UnsafeRawPointer(pointer) - else { return nil } - let result = asStrided( - storage, array.shape, offset: offset / array.itemSize, stream: .cpu) - eval(result) - let address = UInt(bitPattern: pointer) + UInt(offset) + // 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) + } + let address = UInt(bitPattern: mlx_array_data_uint8(result.ctx)) mappedAddresses.withLock { _ = $0.insert(address) } return result } @@ -130,21 +107,22 @@ package final class CheckpointTensorStorage { 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 + quantization: BaseConfiguration.PerLayerQuantization? = nil, + directory: URL = FileManager.default.temporaryDirectory ) { #if canImport(Darwin) guard policy == .automatic, let provider = model as? any InputOnlyEmbeddingsProviding, - !provider.inputOnlyEmbeddings.isEmpty + !provider.inputOnlyEmbeddings.isEmpty, + GPU.deviceInfo().maxBufferSize > 0 else { return nil } - let maximumLength = GPU.deviceInfo().maxBufferSize - guard maximumLength > 0 else { return nil } var locations: [String: Mapping] = [:] do { for url in urls { - let file = try File(url: url, maximumLength: maximumLength) + let file = try File(url: url, directory: directory) for span in try safetensorSpansInFileOrder(url: url) { locations[span.name] = Mapping(file: file, span: span) } diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index d7e0ab3f22..07dead7a90 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -36,8 +36,9 @@ file-backed storage so unused rows can be reclaimed. Models declare these tables ``InputOnlyEmbeddingsProviding``. Tensor values and precision are unchanged. Tied output tables, custom embeddings, and unsupported formats keep normal storage. -Compatible checkpoint tensors map directly. Other eligible tables use temporary files, -with one copy per load and additional disk space. Loading peak memory can remain unchanged. +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. A table that a checkpoint splits by rows into several tensors can use ``ShardedEmbedding``. diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index 62cee9ab87..f836150b79 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -65,58 +65,126 @@ func fileBackedEmbeddingArrays(in module: Module) -> [MLXArray] { /// 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) { - let page = Int(getpagesize()) - let (padded, overflow) = source.nbytes.addingReportingOverflow(page - 1) - guard source.nbytes > 0, !overflow else { throw POSIXError(.EINVAL) } - let pageCount = padded / page - let length = pageCount * page - guard length / source.itemSize <= Int32.max, - length <= GPU.deviceInfo().maxBufferSize - else { throw POSIXError(.EOVERFLOW) } - var path = Array(directory.appendingPathComponent("mlx-embedding-XXXXXX").path.utf8CString) - let descriptor = mkstemp(&path) - guard descriptor >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } - defer { close(descriptor) } - guard unlink(path) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } - // 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(POSIXErrorCode(rawValue: errno) ?? .EIO) - } - let data = source.asData(access: .noCopyIfContiguous).data - try data.withUnsafeBytes { bytes in - guard let base = bytes.baseAddress else { throw POSIXError(.EINVAL) } - var position = 0 - while position < bytes.count { - let count = pwrite( - descriptor, base.advanced(by: position), - min(bytes.count - position, 8 * 1024 * 1024), - off_t(position) - ) - if count < 0 && errno == EINTR { continue } - guard count > 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } - position += count + 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)) + } } } - guard let pointer = mmap(nil, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, descriptor, 0), - pointer != MAP_FAILED - else { - throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) + } +} + +/// 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 + mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) + == 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)) } - // Sparse lookups do not need read-ahead for neighboring rows. - _ = madvise(pointer, length, MADV_RANDOM) - let storage = MLXArray( - rawPointer: pointer, [pageCount, page / source.itemSize], dtype: source.dtype - ) { - munmap(pointer, length) + try transfer(length) { + pwrite(destination, buffer + $0, length - $0, off_t(copied + $0)) } - guard - mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) - == UnsafeRawPointer(pointer) - else { throw POSIXError(.ENOTSUP) } - let array = asStrided(storage, source.shape, stream: .cpu) - eval(array) - return array + 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) } } diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index e1698da4d0..d61e0f7aec 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -68,6 +68,12 @@ final class FileBackedEmbeddingTests: XCTestCase { 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) @@ -483,7 +489,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try rebased.write(to: url) } - func testCheckpointMappingSelectsAlignedStorageAndPreservesAllBits() throws { + func testCheckpointMappingBacksEveryOffsetAndPreservesAllBits() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent( UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) @@ -498,25 +504,15 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(embedding(dtype: dtype, bits: bits)) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url])) + model: model, policy: .automatic, 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"]) - let retained = try storage.array(matching: loadedWeight) - XCTAssertEqual( - retained != nil, offset.isMultiple(of: MemoryLayout.alignment)) - let loadedAddress = loadedWeight.asData(access: .noCopy).data - .withUnsafeBytes { - $0.baseAddress.map(UInt.init(bitPattern:)) - } - if let retained { - let retainedAddress = retained.asData(access: .noCopy).data - .withUnsafeBytes { - $0.baseAddress.map(UInt.init(bitPattern:)) - } - XCTAssertEqual(loadedAddress, retainedAddress) - } + // 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( @@ -561,6 +557,66 @@ final class FileBackedEmbeddingTests: XCTestCase { ["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: .automatic, 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) + 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: .automatic, 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) From a9c55d1171239f12e2dbf47990f417ebb1094411 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 15 Nov 2026 14:30:54 +0100 Subject: [PATCH 07/13] Remove the unused ShardedEmbedding No model in the repo uses it yet. It will return in a separate PR together with a model that needs row-sharded lookup tables, so this PR stays scoped to the embedding storage policy. --- .../MLXLMCommon/Documentation.docc/using.md | 3 - Libraries/MLXLMCommon/ShardedEmbedding.swift | 101 ------------------ .../MLXLMTests/FileBackedEmbeddingTests.swift | 70 ------------ 3 files changed, 174 deletions(-) delete mode 100644 Libraries/MLXLMCommon/ShardedEmbedding.swift diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index 07dead7a90..2c00abcb84 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -41,9 +41,6 @@ copied once per load from the checkpoint into temporary files, which use extra d Neither way loads the whole table into memory. Select ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. -A table that a checkpoint splits by rows into several tensors can use ``ShardedEmbedding``. -List its ``ShardedEmbedding/shards`` as input-only tables, and each shard is stored the same way. - > Important: Do not rewrite or truncate checkpoint files while the model is in use. > Use ``EmbeddingStoragePolicy/resident`` if files must change in place. diff --git a/Libraries/MLXLMCommon/ShardedEmbedding.swift b/Libraries/MLXLMCommon/ShardedEmbedding.swift deleted file mode 100644 index 3baea595f0..0000000000 --- a/Libraries/MLXLMCommon/ShardedEmbedding.swift +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright © 2026 Apple Inc. - -import MLX -import MLXNN - -/// A lookup table split by rows into consecutive shards. -/// -/// Checkpoints store some very large tables this way, one tensor per shard. Each shard -/// is a normal `Embedding`, so a model can list ``shards`` in -/// ``InputOnlyEmbeddingsProviding/inputOnlyEmbeddings`` to keep them in file-backed storage. -public final class ShardedEmbedding: Module, UnaryLayer { - @ModuleInfo(key: "shards") public var shards: [Embedding] - - public init(shards: [Embedding]) { - precondition(!shards.isEmpty, "ShardedEmbedding needs at least one shard") - _shards.wrappedValue = shards - super.init() - } - - public convenience init(rowCounts: [Int], dimensions: Int) { - self.init(shards: rowCounts.map { Embedding(embeddingCount: $0, dimensions: dimensions) }) - } - - /// Looks up rows by their index in the whole table. Indices must be in `0 ..< rowCount`. - /// - /// Each shard is read once per call, so the cost grows with shards times indices. - public func callAsFunction(_ x: MLXArray) -> MLXArray { - var starts: [Int32] = [] - var rowCount = 0 - for shard in shards { - starts.append(Int32(rowCount)) - rowCount += shard.weight.dim(0) - } - precondition(rowCount <= Int(Int32.max), "ShardedEmbedding has too many rows") - let indices = x.flattened().asType(.int32) - let startArray = MLXArray(starts) - let shardIndices = - (indices.expandedDimensions(axis: -1) .>= startArray).asType(.int32).sum(axis: -1) - 1 - let localIndices = indices - startArray.take(shardIndices, axis: 0) - - // Rows outside a shard clamp to its first or last row, then are masked out. - func select(stream: StreamOrDevice, _ rows: (Int, MLXArray) -> MLXArray) -> MLXArray { - var result: MLXArray? - for (index, shard) in shards.enumerated() { - let local = clip(localIndices, min: 0, max: shard.weight.dim(0) - 1, stream: stream) - let selected = rows(index, local) - if let current = result { - let mask = (shardIndices .== Int32(index)).reshaped( - [-1] + Array(repeating: 1, count: selected.ndim - 1)) - result = which(mask, selected, current, stream: stream) - } else { - result = selected - } - } - return result! - } - - let output: MLXArray - if let quantized = uniformQuantizedShards() { - // Gather packed rows from every shard, then dequantize once. - let stream = gathersOnCPU ? StreamOrDevice.cpu : .default - let first = quantized[0] - let weight = select(stream: stream) { - quantized[$0].weight.take($1, axis: 0, stream: stream) - } - let scales = select(stream: stream) { - quantized[$0].scales.take($1, axis: 0, stream: stream) - } - let biases = - first.biases == nil - ? nil - : select(stream: stream) { - quantized[$0].biases!.take($1, axis: 0, stream: stream) - } - output = dequantized( - weight, scales: scales, biases: biases, groupSize: first.groupSize, - bits: first.bits, mode: first.mode) - } else { - output = select(stream: .default) { shards[$0]($1) } - } - return output.reshaped(x.shape + [-1]) - } - - private func uniformQuantizedShards() -> [QuantizedEmbedding]? { - let quantized = shards.compactMap { $0 as? QuantizedEmbedding } - guard quantized.count == shards.count, let first = quantized.first else { return nil } - let uniform = quantized.allSatisfy { - $0.groupSize == first.groupSize && $0.bits == first.bits && $0.mode == first.mode - && $0.globalScale == nil && ($0.biases == nil) == (first.biases == nil) - } - return uniform ? quantized : nil - } - - private var gathersOnCPU: Bool { - #if canImport(Darwin) - return shards.allSatisfy { $0 is FileBackedQuantizedEmbedding } - #else - return false - #endif - } -} diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index d61e0f7aec..2baaab0aab 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -36,16 +36,6 @@ final class FileBackedEmbeddingTests: XCTestCase { } } - private final class ShardedModel: Module, BaseLanguageModel, InputOnlyEmbeddingsProviding { - var inputOnlyEmbeddings: [Embedding] { table.shards } - @ModuleInfo(key: "table") var table: ShardedEmbedding - - init(_ table: ShardedEmbedding) { - _table.wrappedValue = table - super.init() - } - } - private final class CustomEmbedding: QuantizedEmbedding {} private func embedding( @@ -706,65 +696,5 @@ final class FileBackedEmbeddingTests: XCTestCase { assertIdentical(mapped, source) assertIdentical(mapped + 1, source + 1) } - - func testShardedTableMapsEveryShardAndMatchesOneTable() 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 rowCounts = [100, 57, 100] - let values = withRandomState(MLXRandom.RandomState(seed: 7)) { - MLXRandom.normal([257, 256]).asType(.bfloat16) - } - let quantization = BaseConfiguration.Quantization(groupSize: 64, bits: 8) - let reference = QuantizedEmbedding(weight: values, groupSize: 64, bits: 8) - var start = 0 - let source = ShardedModel( - ShardedEmbedding( - shards: rowCounts.map { count in - defer { start += count } - return QuantizedEmbedding( - weight: values[start ..< start + count], groupSize: 64, bits: 8) - })) - try save( - arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), url: url) - - func placeholder() -> ShardedModel { - ShardedModel(ShardedEmbedding(rowCounts: rowCounts, dimensions: 256)) - } - let storage = try XCTUnwrap( - CheckpointTensorStorage( - model: placeholder(), policy: .automatic, urls: [url], - quantization: .init(quantization: quantization, perLayerQuantization: [:]))) - XCTAssertEqual(storage.mappings.count, rowCounts.count * 3) - - let indices = [ - MLXArray(Int32(0)), MLXArray([0, 99, 100, 156, 157, 256, 100, 0]), - MLXArray([256, 157, 156, 99, 3, 200]).reshaped(2, 3), - ] - for policy in [EmbeddingStoragePolicy.automatic, .resident] { - let model = placeholder() - try loadWeights( - modelDirectory: directory, model: model, quantization: quantization, - embeddingStorage: policy) - for shard in model.table.shards { - XCTAssertEqual(shard is FileBackedQuantizedEmbedding, policy == .automatic) - } - for index in indices { - assertIdentical(model.table(index), reference(index)) - } - } - - let floating = ShardedModel( - ShardedEmbedding(shards: [ - Embedding(weight: values[..<100]), Embedding(weight: values[100...]), - ])) - floating.freeze() - XCTAssertEqual(try prepareEmbeddingStorage(in: floating, directory: directory), 2) - XCTAssertTrue(floating.table.shards.allSatisfy { $0 is FileBackedEmbedding }) - let index = MLXArray([0, 99, 100, 256]) - assertIdentical(floating.table(index), values.take(index, axis: 0)) - } } #endif From 84544e8e9923db0f6376b8ea08f5ab8c44aa9af9 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 09:25:55 +0100 Subject: [PATCH 08/13] File-back embeddings only when the model does not fit File-backed tables must be read on the CPU: when the GPU reads a file-backed buffer, macOS pages in and wires the whole mapping (2 GB of 2 GB in a probe on an M6, with or without a residency set). The CPU read makes each forward pass wait for the GPU and back, a fixed ~0.17 ms per decoded token on an M6 whatever the model size. That is ~3% at 166 tok/s and more on fast models such as Gemma 4 E2B. A CPU read past the table also faults, where a GPU read returns undefined values. - `EmbeddingStoragePolicy.automatic` now resolves per load: `.fileBacked` when the checkpoint files are larger than `GPU.maxRecommendedWorkingSetBytes()`, else `.resident`. - Add `EmbeddingStoragePolicy.fileBacked` to request file-backed storage. - `FileBackedEmbedding` and `FileBackedQuantizedEmbedding` clamp indices on the CPU stream to `[-rows, rows - 1]` (`[0, rows - 1]` for unsigned ids), so negative indices still count from the end as in `take`. - Document the cost and the default in `using.md`. Models that fit keep the original GPU path and pay nothing. Models that do not fit trade the round trip for the memory they need to run at all. `MLX_METAL_FAST_SYNCH` would shorten the round trip, but mlx-swift 0.33 does not ship its fence kernels. --- .../MLXLMCommon/CheckpointTensorStorage.swift | 2 +- .../MLXLMCommon/Documentation.docc/using.md | 8 ++- .../MLXLMCommon/FileBackedEmbedding.swift | 38 +++++++--- Libraries/MLXLMCommon/Load.swift | 8 ++- .../MLXLMTests/FileBackedEmbeddingTests.swift | 71 ++++++++++++++----- 5 files changed, 97 insertions(+), 30 deletions(-) diff --git a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift index 21298391b2..d16bd02f30 100644 --- a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -114,7 +114,7 @@ package final class CheckpointTensorStorage { directory: URL = FileManager.default.temporaryDirectory ) { #if canImport(Darwin) - guard policy == .automatic, + guard policy == .fileBacked, let provider = model as? any InputOnlyEmbeddingsProviding, !provider.inputOnlyEmbeddings.isEmpty, GPU.deviceInfo().maxBufferSize > 0 diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index 2c00abcb84..417cd1613c 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -31,11 +31,17 @@ print(try await session.respond(to: "How about a great place to eat?")) ## Embedding storage -``EmbeddingStoragePolicy/automatic`` keeps supported frozen input-only tables in +``EmbeddingStoragePolicy/fileBacked`` 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. diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index f836150b79..d76fb59bf2 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -11,11 +11,22 @@ import Darwin /// Storage for embedding tables during model loading. public enum EmbeddingStoragePolicy: Sendable, Equatable { - /// File-back supported frozen input tables on Apple platforms; other tables stay resident. - /// Keep checkpoint contents unchanged while the model is in use. + /// ``fileBacked`` 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 fileBacked /// 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 .fileBacked + } } /// Embedding tables used only for lookup, never shared with a dense output projection. @@ -188,15 +199,22 @@ extension POSIXError { } } +/// `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) -> MLXArray { + let rows = table.dim(0) + return clip(x, min: x.dtype.isSignedInteger ? -rows : 0, max: rows - 1, stream: .cpu) +} + package final class FileBackedEmbedding: Embedding { package override func callAsFunction(_ x: MLXArray) -> MLXArray { - weight.take(x, axis: 0, stream: .cpu) + weight.take(rowIndices(x, in: weight), axis: 0, stream: .cpu) } } package final class FileBackedQuantizedEmbedding: QuantizedEmbedding { package override func callAsFunction(_ x: MLXArray) -> MLXArray { - let indices = x.flattened() + let indices = rowIndices(x.flattened(), in: weight) return dequantized( weight.take(indices, axis: 0, stream: .cpu), scales: scales.take(indices, axis: 0, stream: .cpu), @@ -221,7 +239,7 @@ func supportsFileBackedStorage(_ embedding: Embedding) -> Bool { /// Prepare embedding access after checkpoint parameters have been applied. @discardableResult package func prepareEmbeddingStorage( - in model: Module, policy: EmbeddingStoragePolicy = .automatic, directory: URL, + in model: Module, policy: EmbeddingStoragePolicy = .fileBacked, directory: URL, checkpoint: CheckpointTensorStorage? = nil ) throws -> Int { guard let provider = model as? any InputOnlyEmbeddingsProviding else { return 0 } @@ -232,7 +250,7 @@ package func prepareEmbeddingStorage( for (name, module) in model.namedModules() { guard !name.isEmpty, eligible.contains(ObjectIdentifier(module)), let embedding = module as? Embedding, supportsFileBackedStorage(embedding), - policy == .automatic || module is FileBackedEmbedding + policy == .fileBacked || module is FileBackedEmbedding || module is FileBackedQuantizedEmbedding else { continue } let identity = ObjectIdentifier(embedding) @@ -247,13 +265,13 @@ package func prepareEmbeddingStorage( let replacement: Embedding if let quantized = embedding as? QuantizedEmbedding { switch policy { - case .automatic: + case .fileBacked: 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 .resident: + case .automatic, .resident: replacement = QuantizedEmbedding( weight: quantized.weight, scales: quantized.scales, biases: quantized.biases, groupSize: quantized.groupSize, bits: quantized.bits, mode: quantized.mode, @@ -261,9 +279,9 @@ package func prepareEmbeddingStorage( } } else { switch policy { - case .automatic: + case .fileBacked: replacement = try FileBackedEmbedding(weight: backed(embedding.weight)) - case .resident: + case .automatic, .resident: replacement = Embedding(weight: embedding.weight) } } diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 2422bc63bf..b7ca440e43 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -426,7 +426,8 @@ private func topLevelSafetensorURLs(in modelDirectory: URL) -> [URL] { /// not read. /// /// Supported frozen tables declared by ``InputOnlyEmbeddingsProviding`` use file-backed -/// storage by default. Select ``EmbeddingStoragePolicy/resident`` to keep normal MLX storage. +/// storage when the checkpoint is larger than the recommended GPU working set. Select +/// ``EmbeddingStoragePolicy/fileBacked`` or ``EmbeddingStoragePolicy/resident`` to choose. /// /// - Important: Do not rewrite or truncate mapped checkpoint files while the model is in use. public func loadWeights( @@ -451,6 +452,11 @@ 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) diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index 2baaab0aab..94823833b1 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -74,7 +74,7 @@ final class FileBackedEmbeddingTests: XCTestCase { arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), url: directory.appendingPathComponent("model.safetensors")) let automatic = Model(embedding()) - try loadWeights(modelDirectory: directory, model: automatic) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .fileBacked) XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) assertIdentical( automatic.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) @@ -89,7 +89,7 @@ final class FileBackedEmbeddingTests: XCTestCase { 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) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .fileBacked) XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) XCTAssertFalse(automatic.embedding === firstEmbedding) assertIdentical( @@ -102,8 +102,45 @@ final class FileBackedEmbeddingTests: XCTestCase { 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) + try loadWeights(modelDirectory: directory, model: dense, embeddingStorage: .fileBacked) 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), .fileBacked) + XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: nil), .resident) + XCTAssertEqual( + EmbeddingStoragePolicy.fileBacked.resolved(checkpointBytes: 1, workingSetBytes: 8), + .fileBacked) + 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() { @@ -278,7 +315,7 @@ final class FileBackedEmbeddingTests: XCTestCase { metadata: ["format": "mlx"], url: directory.appendingPathComponent("model.safetensors")) var sequences: [[Int]] = [] - for policy in [EmbeddingStoragePolicy.automatic, .resident] { + for policy in [EmbeddingStoragePolicy.fileBacked, .resident] { let configuration = ModelConfiguration( directory: directory, embeddingStorage: policy ) @@ -298,7 +335,7 @@ final class FileBackedEmbeddingTests: XCTestCase { $0.0 == "language_model.model.embed_tokens" }?.1 as? Embedding) XCTAssertEqual( - table is FileBackedQuantizedEmbedding, !tied && policy == .automatic) + table is FileBackedQuantizedEmbedding, !tied && policy == .fileBacked) assertIdentical( table(MLXArray([0, 256, -1])), original(MLXArray([0, 256, -1]))) var iterator = try TokenIterator( @@ -307,7 +344,7 @@ final class FileBackedEmbeddingTests: XCTestCase { var tokens: [Int] = [] while let token = iterator.next() { tokens.append(token) } XCTAssertEqual(tokens.count, 4) - if policy == .automatic { + if policy == .fileBacked { sequences.append(tokens) } else { XCTAssertEqual(tokens, sequences[index]) @@ -420,13 +457,13 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) model.embedding.freeze() let storage = try XCTUnwrap( - CheckpointTensorStorage(model: model, policy: .automatic, urls: [url])) + CheckpointTensorStorage(model: model, policy: .fileBacked, 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) + try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .fileBacked) XCTAssertTrue(model.embedding is FileBackedEmbedding) assertIdentical(model.embedding.weight, source.embedding.weight) assertIdentical( @@ -443,7 +480,7 @@ final class FileBackedEmbeddingTests: XCTestCase { Model(embedding()), url: directory.appendingPathComponent("model.safetensors")) let backed = Model(embedding()) - try loadWeights(modelDirectory: directory, model: backed) + try loadWeights(modelDirectory: directory, model: backed, embeddingStorage: .fileBacked) XCTAssertTrue(backed.embedding is FileBackedQuantizedEmbedding) let backedMemory = try backed.memory() XCTAssertGreaterThan(backedMemory.fileBacked, 0) @@ -494,7 +531,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(embedding(dtype: dtype, bits: bits)) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url], + model: model, policy: .fileBacked, urls: [url], directory: directory)) var checkpoint = try loadModelCheckpoint( urls: [url], mappings: storage.mappings) @@ -563,7 +600,7 @@ final class FileBackedEmbeddingTests: XCTestCase { model.embedding.freeze() let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url], directory: directory)) + model: model, policy: .fileBacked, 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"]) @@ -574,7 +611,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try FileManager.default.contentsOfDirectory(atPath: directory.path), ["model.safetensors"]) - try loadWeights(modelDirectory: directory, model: model) + try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .fileBacked) XCTAssertTrue(model.embedding is FileBackedEmbedding) assertIdentical(model.embedding.weight, values) let indices = MLXArray([0, 4096, 8191, 8192, -1]) @@ -592,7 +629,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(embedding()) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url], + model: model, policy: .fileBacked, urls: [url], directory: directory.appendingPathComponent("missing"))) var checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) storage.record(checkpoint.weights) @@ -618,7 +655,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) guard let unknown = CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url]) + model: model, policy: .fileBacked, urls: [url]) else { throw XCTSkip("File-backed embeddings require a Metal device") } XCTAssertTrue(unknown.mappings.isEmpty) for mode in ["affine", "mxfp4"] { @@ -630,7 +667,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url], quantization: policy)) + model: model, policy: .fileBacked, urls: [url], quantization: policy)) XCTAssertEqual(storage.mappings.count, mode == "affine" ? 3 : 0) if mode == "affine" { var checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) @@ -657,7 +694,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try saveCheckpoint(model, url: url, offset: 0) guard let storage = CheckpointTensorStorage( - model: model, policy: .automatic, urls: [url]) + model: model, policy: .fileBacked, urls: [url]) else { throw XCTSkip("File-backed embeddings require a Metal device") } let checkpoint = try loadModelCheckpoint(urls: [url]) storage.record(checkpoint.weights) @@ -683,7 +720,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let url = directory.appendingPathComponent("model.safetensors") let model = Model(embedding()) try saveCheckpoint(model, url: url, offset: 0) - var storage = CheckpointTensorStorage(model: model, policy: .automatic, urls: [url]) + var storage = CheckpointTensorStorage(model: model, policy: .fileBacked, urls: [url]) guard storage != nil else { throw XCTSkip("File-backed embeddings require a Metal device") } From 3ee35de9ab1297e35b03dab6be76366be1b729de Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 09:25:55 +0100 Subject: [PATCH 09/13] Replace file-backed tables inside module arrays `prepareEmbeddingStorage` swapped the tables with one `update(modules:)` on the model. mlx-swift cannot update an array when its first elements have no entry, so a table under `layers.1` threw `unexpectedStructure` and every table kept normal storage. Qwen4 MoE keeps its 16 n-gram tables (11 GB at 4 bits) under `model.layers.1`. - Swap each table through its direct parent module, and give each changed array all its elements. - Test a table at index 1 of a table array inside a plain `let` layer array. --- .../MLXLMCommon/FileBackedEmbedding.swift | 33 ++++++++++++++++- .../MLXLMTests/FileBackedEmbeddingTests.swift | 37 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index d76fb59bf2..ce1c6ff4e6 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -292,9 +292,40 @@ package func prepareEmbeddingStorage( } if !replacements.isEmpty { defer { model.invalidateCompiledTraces() } - try model.update(modules: ModuleChildren.unflattened(replacements), verify: []) + 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/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index 94823833b1..d8ef6ee779 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -38,6 +38,25 @@ final class FileBackedEmbeddingTests: XCTestCase { 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 { @@ -228,6 +247,24 @@ final class FileBackedEmbeddingTests: XCTestCase { XCTAssertTrue(model.namedModules().contains { $0.1 === model.inputOnlyEmbeddings.first }) } + 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] { From 50e35e82465d98c928b69c32e7e11b38548c2323 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 09:51:09 +0100 Subject: [PATCH 10/13] Use only public MLX API for file-backed storage `CheckpointTensorStorage` and `FileBackedEmbedding` imported `Cmlx`, which mlx-swift does not export, for two things that its public API already does. - Read data addresses with `asData(access: .noCopy)` instead of `mlx_array_data_uint8`. - Take the second handle to a recorded checkpoint array with `reshaped(value.shape)` instead of `mlx_array_new` and `mlx_array_set`. Reshaping to the same shape returns the same array, so the handle shares its buffer. - Test that a recorded source survives an in-place update of the checkpoint array, which is why the second handle exists. No mlx-swift change is needed. --- .../MLXLMCommon/CheckpointTensorStorage.swift | 16 ++++++------- .../MLXLMCommon/FileBackedEmbedding.swift | 3 +-- .../MLXLMTests/FileBackedEmbeddingTests.swift | 23 +++++++++++++++++++ 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift index d16bd02f30..920a97df05 100644 --- a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -5,7 +5,6 @@ import MLX import MLXNN #if canImport(Darwin) -import Cmlx import Darwin import os #endif @@ -73,8 +72,11 @@ package final class CheckpointTensorStorage { like: array, copying: handle.fileDescriptor, offset: span.byteOffset, directory: directory) } - let address = UInt(bitPattern: mlx_array_data_uint8(result.ctx)) - mappedAddresses.withLock { _ = $0.insert(address) } + if let address = result.asData(access: .noCopy).data.withUnsafeBytes({ + $0.baseAddress.map(UInt.init(bitPattern:)) + }) { + mappedAddresses.withLock { _ = $0.insert(address) } + } return result } } @@ -167,12 +169,8 @@ package final class CheckpointTensorStorage { guard let location = locations[name], location.file.unchanged(checkPath: true), location.span.byteCount == value.nbytes else { continue } - var context = mlx_array_new() - guard mlx_array_set(&context, value.ctx) == 0 else { - mlx_array_free(context) - continue - } - let snapshot = MLXArray(context) + // 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 } diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index ce1c6ff4e6..c34bef86ab 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -5,7 +5,6 @@ import MLX import MLXNN #if canImport(Darwin) -import Cmlx import Darwin #endif @@ -119,7 +118,7 @@ func fileBackedArray( munmap(pointer, length) } guard - mlx_array_data_uint8(storage.ctx).map(UnsafeRawPointer.init) + storage.asData(access: .noCopy).data.withUnsafeBytes({ $0.baseAddress }) == UnsafeRawPointer(pointer) else { throw POSIXError(.ENOTSUP) } let array = asStrided( diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index d8ef6ee779..b95c10ee56 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -749,6 +749,29 @@ final class FileBackedEmbeddingTests: XCTestCase { 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: .fileBacked, 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) From 8a678f62c87d54f568862151630f1613bc7b080e Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 10:37:07 +0100 Subject: [PATCH 11/13] Read each file-backed table on its own CPU stream A file-backed row that is not in memory is read from disk on a page fault. All tables read on the one CPU stream, so the faults of a decode step ran one after another. Qwen4-35B-A3B reads 16 n-gram tables per token, which cost ~38 major faults and a ~3 ms GPU gap per token in a Metal System Trace on an M6 Mac mini (32 GB). - Give `FileBackedEmbedding` and `FileBackedQuantizedEmbedding` their own CPU stream. Each stream has its own thread, so the faults of different tables wait for the disk together. On new text, decode goes from 51-53 to 58-59 tok/s and warm prefill from ~197 to ~235 tok/s. With every row in memory, decode is 60.5 tok/s with either layout, so the extra streams cost nothing measurable. --- .../MLXLMCommon/FileBackedEmbedding.swift | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index c34bef86ab..533590450d 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -200,24 +200,32 @@ extension POSIXError { /// `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) -> MLXArray { +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: .cpu) + 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), axis: 0, stream: .cpu) + 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) + let indices = rowIndices(x.flattened(), in: weight, stream: stream) return dequantized( - weight.take(indices, axis: 0, stream: .cpu), - scales: scales.take(indices, axis: 0, stream: .cpu), - biases: biases.map { $0.take(indices, axis: 0, stream: .cpu) }, + 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]) } From 3da22dbb2ee08b6b34b2a9fbdfc3b04b3d8e2ba0 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 13:05:51 +0100 Subject: [PATCH 12/13] Rename fileBacked to backed and declare tables of newer models - `EmbeddingStoragePolicy.fileBacked` is now `.backed`, and `ModelMemory.fileBacked` is now `ModelMemory.backed`. - Inkling 2 and Ricursive declare `embed_tokens`. Both always have a separate `lm_head`. DiffusionGemma keeps normal storage, because self-conditioning multiplies by its token table. LFM3 ties its head by default, so it has no table to declare. --- Libraries/MLXLLM/Models/Ricursive.swift | 3 +- .../MLXLMCommon/CheckpointTensorStorage.swift | 2 +- .../MLXLMCommon/Documentation.docc/using.md | 2 +- .../Documentation.docc/wired-memory.md | 2 +- .../MLXLMCommon/FileBackedEmbedding.swift | 14 ++-- Libraries/MLXLMCommon/Load.swift | 2 +- Libraries/MLXLMCommon/ModelMemory.swift | 10 +-- Libraries/MLXVLM/Models/Inkling2.swift | 5 +- .../MLXLMTests/FileBackedEmbeddingTests.swift | 81 +++++++++++++------ 9 files changed, 79 insertions(+), 42 deletions(-) diff --git a/Libraries/MLXLLM/Models/Ricursive.swift b/Libraries/MLXLLM/Models/Ricursive.swift index 71d9cb67ad..bca77e2dd8 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 index 920a97df05..416b3a9f3b 100644 --- a/Libraries/MLXLMCommon/CheckpointTensorStorage.swift +++ b/Libraries/MLXLMCommon/CheckpointTensorStorage.swift @@ -116,7 +116,7 @@ package final class CheckpointTensorStorage { directory: URL = FileManager.default.temporaryDirectory ) { #if canImport(Darwin) - guard policy == .fileBacked, + guard policy == .backed, let provider = model as? any InputOnlyEmbeddingsProviding, !provider.inputOnlyEmbeddings.isEmpty, GPU.deviceInfo().maxBufferSize > 0 diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index 80809f679c..2aea6b7923 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -31,7 +31,7 @@ print(try await session.respond(to: "How about a great place to eat?")) ## Embedding storage -``EmbeddingStoragePolicy/fileBacked`` keeps supported frozen input-only tables in +``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. diff --git a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md index a424c1abb1..4bfedc6945 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md +++ b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md @@ -29,7 +29,7 @@ let weightBytes = memory.total component loads on first use. The KV cache is not included; read ``KVCacheStatus/memoryBytes`` for it. -``ModelMemory/fileBacked`` is the part of the model held in file-backed embedding tables. The +``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. diff --git a/Libraries/MLXLMCommon/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index 533590450d..d71e97a445 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -10,13 +10,13 @@ import Darwin /// Storage for embedding tables during model loading. public enum EmbeddingStoragePolicy: Sendable, Equatable { - /// ``fileBacked`` when the checkpoint files are larger than the GPU working set that + /// ``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 fileBacked + case backed /// Keep all tables in normal MLX storage. case resident @@ -24,7 +24,7 @@ public enum EmbeddingStoragePolicy: Sendable, Equatable { func resolved(checkpointBytes: Int, workingSetBytes: Int?) -> EmbeddingStoragePolicy { guard self == .automatic else { return self } guard let workingSetBytes, checkpointBytes > workingSetBytes else { return .resident } - return .fileBacked + return .backed } } @@ -246,7 +246,7 @@ func supportsFileBackedStorage(_ embedding: Embedding) -> Bool { /// Prepare embedding access after checkpoint parameters have been applied. @discardableResult package func prepareEmbeddingStorage( - in model: Module, policy: EmbeddingStoragePolicy = .fileBacked, directory: URL, + in model: Module, policy: EmbeddingStoragePolicy = .backed, directory: URL, checkpoint: CheckpointTensorStorage? = nil ) throws -> Int { guard let provider = model as? any InputOnlyEmbeddingsProviding else { return 0 } @@ -257,7 +257,7 @@ package func prepareEmbeddingStorage( for (name, module) in model.namedModules() { guard !name.isEmpty, eligible.contains(ObjectIdentifier(module)), let embedding = module as? Embedding, supportsFileBackedStorage(embedding), - policy == .fileBacked || module is FileBackedEmbedding + policy == .backed || module is FileBackedEmbedding || module is FileBackedQuantizedEmbedding else { continue } let identity = ObjectIdentifier(embedding) @@ -272,7 +272,7 @@ package func prepareEmbeddingStorage( let replacement: Embedding if let quantized = embedding as? QuantizedEmbedding { switch policy { - case .fileBacked: + case .backed: replacement = try FileBackedQuantizedEmbedding( weight: backed(quantized.weight), scales: backed(quantized.scales), biases: quantized.biases.map(backed), @@ -286,7 +286,7 @@ package func prepareEmbeddingStorage( } } else { switch policy { - case .fileBacked: + case .backed: replacement = try FileBackedEmbedding(weight: backed(embedding.weight)) case .automatic, .resident: replacement = Embedding(weight: embedding.weight) diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 0c751b6c8f..4f85f3b526 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -434,7 +434,7 @@ func contentsOfModelDirectory( /// /// Supported frozen tables declared by ``InputOnlyEmbeddingsProviding`` use file-backed /// storage when the checkpoint is larger than the recommended GPU working set. Select -/// ``EmbeddingStoragePolicy/fileBacked`` or ``EmbeddingStoragePolicy/resident`` to choose. +/// ``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( diff --git a/Libraries/MLXLMCommon/ModelMemory.swift b/Libraries/MLXLMCommon/ModelMemory.swift index a23fe89018..03c17e72be 100644 --- a/Libraries/MLXLMCommon/ModelMemory.swift +++ b/Libraries/MLXLMCommon/ModelMemory.swift @@ -37,18 +37,18 @@ public struct ModelMemory: Sendable, Equatable { /// /// The system reads these pages when a lookup uses them and can reclaim them later, /// so the resident share is usually smaller. See ``EmbeddingStoragePolicy``. - public let fileBacked: Int + public let backed: Int public init(model: Int) { self.model = model self.components = [] - self.fileBacked = 0 + self.backed = 0 } - init(model: Int, components: [Component], fileBacked: Int) { + init(model: Int, components: [Component], backed: Int) { self.model = model self.components = components - self.fileBacked = fileBacked + self.backed = backed } } @@ -95,7 +95,7 @@ extension BaseLanguageModel { } return ModelMemory( model: model, components: breakdown, - fileBacked: Memory.bufferSize(fileBackedEmbeddingArrays(in: self))) + backed: Memory.bufferSize(fileBackedEmbeddingArrays(in: self))) } } } diff --git a/Libraries/MLXVLM/Models/Inkling2.swift b/Libraries/MLXVLM/Models/Inkling2.swift index 00defc9c2b..be86300cc7 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/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index b95c10ee56..3a2677d240 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -93,7 +93,7 @@ final class FileBackedEmbeddingTests: XCTestCase { arrays: Dictionary(uniqueKeysWithValues: source.parameters().flattened()), url: directory.appendingPathComponent("model.safetensors")) let automatic = Model(embedding()) - try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .fileBacked) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .backed) XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) assertIdentical( automatic.embedding(MLXArray([0, 256])), source.embedding(MLXArray([0, 256]))) @@ -108,7 +108,7 @@ final class FileBackedEmbeddingTests: XCTestCase { 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: .fileBacked) + try loadWeights(modelDirectory: directory, model: automatic, embeddingStorage: .backed) XCTAssertTrue(automatic.embedding is FileBackedQuantizedEmbedding) XCTAssertFalse(automatic.embedding === firstEmbedding) assertIdentical( @@ -121,7 +121,7 @@ final class FileBackedEmbeddingTests: XCTestCase { 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: .fileBacked) + 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) @@ -131,11 +131,11 @@ final class FileBackedEmbeddingTests: XCTestCase { func testAutomaticStorageFileBacksOnlyCheckpointsLargerThanTheWorkingSet() { let automatic = EmbeddingStoragePolicy.automatic XCTAssertEqual(automatic.resolved(checkpointBytes: 8, workingSetBytes: 8), .resident) - XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: 8), .fileBacked) + XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: 8), .backed) XCTAssertEqual(automatic.resolved(checkpointBytes: 9, workingSetBytes: nil), .resident) XCTAssertEqual( - EmbeddingStoragePolicy.fileBacked.resolved(checkpointBytes: 1, workingSetBytes: 8), - .fileBacked) + EmbeddingStoragePolicy.backed.resolved(checkpointBytes: 1, workingSetBytes: 8), + .backed) XCTAssertEqual( EmbeddingStoragePolicy.resident.resolved(checkpointBytes: 9, workingSetBytes: 8), .resident) @@ -247,6 +247,39 @@ final class FileBackedEmbeddingTests: XCTestCase { 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([ @@ -352,7 +385,7 @@ final class FileBackedEmbeddingTests: XCTestCase { metadata: ["format": "mlx"], url: directory.appendingPathComponent("model.safetensors")) var sequences: [[Int]] = [] - for policy in [EmbeddingStoragePolicy.fileBacked, .resident] { + for policy in [EmbeddingStoragePolicy.backed, .resident] { let configuration = ModelConfiguration( directory: directory, embeddingStorage: policy ) @@ -372,7 +405,7 @@ final class FileBackedEmbeddingTests: XCTestCase { $0.0 == "language_model.model.embed_tokens" }?.1 as? Embedding) XCTAssertEqual( - table is FileBackedQuantizedEmbedding, !tied && policy == .fileBacked) + table is FileBackedQuantizedEmbedding, !tied && policy == .backed) assertIdentical( table(MLXArray([0, 256, -1])), original(MLXArray([0, 256, -1]))) var iterator = try TokenIterator( @@ -381,7 +414,7 @@ final class FileBackedEmbeddingTests: XCTestCase { var tokens: [Int] = [] while let token = iterator.next() { tokens.append(token) } XCTAssertEqual(tokens.count, 4) - if policy == .fileBacked { + if policy == .backed { sequences.append(tokens) } else { XCTAssertEqual(tokens, sequences[index]) @@ -494,13 +527,13 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) model.embedding.freeze() let storage = try XCTUnwrap( - CheckpointTensorStorage(model: model, policy: .fileBacked, urls: [url])) + 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: .fileBacked) + try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .backed) XCTAssertTrue(model.embedding is FileBackedEmbedding) assertIdentical(model.embedding.weight, source.embedding.weight) assertIdentical( @@ -517,17 +550,17 @@ final class FileBackedEmbeddingTests: XCTestCase { Model(embedding()), url: directory.appendingPathComponent("model.safetensors")) let backed = Model(embedding()) - try loadWeights(modelDirectory: directory, model: backed, embeddingStorage: .fileBacked) + try loadWeights(modelDirectory: directory, model: backed, embeddingStorage: .backed) XCTAssertTrue(backed.embedding is FileBackedQuantizedEmbedding) let backedMemory = try backed.memory() - XCTAssertGreaterThan(backedMemory.fileBacked, 0) - XCTAssertEqual(backedMemory.fileBacked, backedMemory.model) + XCTAssertGreaterThan(backedMemory.backed, 0) + XCTAssertEqual(backedMemory.backed, backedMemory.model) let resident = Model(embedding()) try loadWeights(modelDirectory: directory, model: resident, embeddingStorage: .resident) let residentMemory = try resident.memory() XCTAssertGreaterThan(residentMemory.model, 0) - XCTAssertEqual(residentMemory.fileBacked, 0) + XCTAssertEqual(residentMemory.backed, 0) } func testOversizedBackingFailsBeforeReadingTheArray() throws { @@ -568,7 +601,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(embedding(dtype: dtype, bits: bits)) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url], + model: model, policy: .backed, urls: [url], directory: directory)) var checkpoint = try loadModelCheckpoint( urls: [url], mappings: storage.mappings) @@ -637,7 +670,7 @@ final class FileBackedEmbeddingTests: XCTestCase { model.embedding.freeze() let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url], directory: directory)) + 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"]) @@ -648,7 +681,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try FileManager.default.contentsOfDirectory(atPath: directory.path), ["model.safetensors"]) - try loadWeights(modelDirectory: directory, model: model, embeddingStorage: .fileBacked) + 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]) @@ -666,7 +699,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(embedding()) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url], + model: model, policy: .backed, urls: [url], directory: directory.appendingPathComponent("missing"))) var checkpoint = try loadModelCheckpoint(urls: [url], mappings: storage.mappings) storage.record(checkpoint.weights) @@ -692,7 +725,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) guard let unknown = CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url]) + 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"] { @@ -704,7 +737,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let model = Model(Embedding(embeddingCount: 257, dimensions: 256)) let storage = try XCTUnwrap( CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url], quantization: policy)) + 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) @@ -731,7 +764,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try saveCheckpoint(model, url: url, offset: 0) guard let storage = CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url]) + 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) @@ -759,7 +792,7 @@ final class FileBackedEmbeddingTests: XCTestCase { try saveCheckpoint(model, url: url, offset: 0) guard let storage = CheckpointTensorStorage( - model: model, policy: .fileBacked, urls: [url]) + 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) @@ -780,7 +813,7 @@ final class FileBackedEmbeddingTests: XCTestCase { let url = directory.appendingPathComponent("model.safetensors") let model = Model(embedding()) try saveCheckpoint(model, url: url, offset: 0) - var storage = CheckpointTensorStorage(model: model, policy: .fileBacked, urls: [url]) + var storage = CheckpointTensorStorage(model: model, policy: .backed, urls: [url]) guard storage != nil else { throw XCTSkip("File-backed embeddings require a Metal device") } From a229fa9d6fa6a494affc795088f43025d751b6e5 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sun, 6 Dec 2026 13:23:31 +0100 Subject: [PATCH 13/13] Report the bytes of file-backed tables paged in `ModelMemory.backed` is the size of the file-backed tables, not what is in memory: the system reads their pages on use and can reclaim them later. An app that charts model memory could not tell how much of a table a conversation had read. - Add `ModelMemory.paged`, the bytes of `backed` paged in when measured. `mincore` reports the pages of each table, one byte per page, and each buffer counts once. - Test it on an anonymous mapping, where only written pages are paged in, and after a lookup of every row of a loaded table. These are clean file pages, so they do not count in the process footprint, and another process that reads the same checkpoint shares them. --- .../Documentation.docc/wired-memory.md | 1 + .../MLXLMCommon/FileBackedEmbedding.swift | 25 +++++++++++++++++++ Libraries/MLXLMCommon/ModelMemory.swift | 16 +++++++++--- .../MLXLMTests/FileBackedEmbeddingTests.swift | 20 +++++++++++++++ 4 files changed, 58 insertions(+), 4 deletions(-) diff --git a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md index 4bfedc6945..6ecf7e9825 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md +++ b/Libraries/MLXLMCommon/Documentation.docc/wired-memory.md @@ -32,6 +32,7 @@ component loads on first use. The KV cache is not included; read ``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/FileBackedEmbedding.swift b/Libraries/MLXLMCommon/FileBackedEmbedding.swift index d71e97a445..fd920e23ab 100644 --- a/Libraries/MLXLMCommon/FileBackedEmbedding.swift +++ b/Libraries/MLXLMCommon/FileBackedEmbedding.swift @@ -70,6 +70,31 @@ func fileBackedEmbeddingArrays(in module: Module) -> [MLXArray] { #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. diff --git a/Libraries/MLXLMCommon/ModelMemory.swift b/Libraries/MLXLMCommon/ModelMemory.swift index 03c17e72be..a2cd2876fc 100644 --- a/Libraries/MLXLMCommon/ModelMemory.swift +++ b/Libraries/MLXLMCommon/ModelMemory.swift @@ -36,19 +36,26 @@ public struct ModelMemory: Sendable, Equatable { /// Bytes of ``model`` in file-backed embedding tables. /// /// The system reads these pages when a lookup uses them and can reclaim them later, - /// so the resident share is usually smaller. See ``EmbeddingStoragePolicy``. + /// 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], backed: Int) { + init(model: Int, components: [Component], backed: Int, paged: Int) { self.model = model self.components = components self.backed = backed + self.paged = paged } } @@ -93,9 +100,10 @@ extension BaseLanguageModel { totalBytes = currentBytes } } + let backed = fileBackedEmbeddingArrays(in: self) return ModelMemory( - model: model, components: breakdown, - backed: Memory.bufferSize(fileBackedEmbeddingArrays(in: self))) + model: model, components: breakdown, backed: Memory.bufferSize(backed), + paged: pagedBytes(of: backed)) } } } diff --git a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift index 3a2677d240..db8816e916 100644 --- a/Tests/MLXLMTests/FileBackedEmbeddingTests.swift +++ b/Tests/MLXLMTests/FileBackedEmbeddingTests.swift @@ -555,12 +555,32 @@ final class FileBackedEmbeddingTests: XCTestCase { 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 {