Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions Libraries/MLXEmbedders/ModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ public final class EmbedderModelFactory: GenericModelFactory {
modelDirectory: modelDirectory, model: model,
perLayerQuantization: baseConfig.perLayerQuantization,
weightFileSelection: configuration.weightFileSelection,
excludedComponents: configuration.excludedComponents)
excludedComponents: configuration.excludedComponents,
embeddingStorage: configuration.embeddingStorage)

let tokenizer = try await tokenizerTask
try model.validate(tokenizer: tokenizer)
Expand All @@ -259,7 +260,8 @@ public final class EmbedderModelFactory: GenericModelFactory {
extraEOSTokens: configuration.extraEOSTokens,
stopStrings: configuration.stopStrings,
eosTokenIds: configuration.eosTokenIds,
toolCallFormat: configuration.toolCallFormat)
toolCallFormat: configuration.toolCallFormat,
embeddingStorage: configuration.embeddingStorage)

let pooling = loadPooling(modelDirectory: modelDirectory, model: model)

Expand Down
6 changes: 4 additions & 2 deletions Libraries/MLXLLM/LLMModelFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,8 @@ public final class LLMModelFactory: GenericModelFactory {
modelDirectory: modelDirectory, model: model,
perLayerQuantization: baseConfig.perLayerQuantization,
weightFileSelection: configuration.weightFileSelection,
excludedComponents: configuration.excludedComponents)
excludedComponents: configuration.excludedComponents,
embeddingStorage: configuration.embeddingStorage)

let tokenizer = try await tokenizerTask

Expand Down Expand Up @@ -866,7 +867,8 @@ public final class LLMModelFactory: GenericModelFactory {
toolCallFormat: mutableConfiguration.toolCallFormat,
reasoningConfig: mutableConfiguration.reasoningConfig,
messageGenerator: mutableConfiguration.messageGenerator,
generationConfig: mutableConfiguration.generationConfig)
generationConfig: mutableConfiguration.generationConfig,
embeddingStorage: configuration.embeddingStorage)

let processor = LLMUserInputProcessor(
tokenizer: tokenizer, configuration: modelConfig,
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ public struct Gemma4Configuration: Codable, Sendable {

// MARK: - Model

public class Gemma4Model: Module, LLMModel, KVCacheDimensionProvider {
public class Gemma4Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings }

public var vocabularySize: Int { languageModel.vocabularySize }
public var kvHeads: [Int] { languageModel.kvHeads }
public var kvCacheStart: KVCacheStart { .deferred }
Expand Down
8 changes: 7 additions & 1 deletion Libraries/MLXLLM/Models/Gemma4Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,13 @@ private class Gemma4TextExperts: Module {

// MARK: - Public Model

public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider {
public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider,
InputOnlyEmbeddingsProviding
{
public var inputOnlyEmbeddings: [Embedding] {
[model.embedTokensPerLayer].compactMap { $0 } + (lmHead == nil ? [] : [model.embedTokens])
}

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart { .deferred }
Expand Down
3 changes: 2 additions & 1 deletion Libraries/MLXLLM/Models/Llama.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ public class LlamaModelInner: Module {
}

/// Model for Llama and Mistral model types.
public class LlamaModel: Module, LLMModel, KVCacheDimensionProvider {
public class LlamaModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
Expand Down
3 changes: 2 additions & 1 deletion Libraries/MLXLLM/Models/Phi3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/PhiMoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,9 @@ public class PhiMoEModelInner: Module {
}
}

public class PhiMoEModel: Module, LLMModel, KVCacheDimensionProvider {
public class PhiMoEModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart { .deferred }
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/Qwen2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,9 @@ public class Qwen2ModelInner: Module {
}
}

public class Qwen2Model: Module, LLMModel, KVCacheDimensionProvider {
public class Qwen2Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart {
Expand Down
4 changes: 3 additions & 1 deletion Libraries/MLXLLM/Models/Qwen3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,9 @@ public class Qwen3ModelInner: Module {
}
}

public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider {
public class Qwen3Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart { .compressed(headDim: configuration.headDim) }
Expand Down
10 changes: 8 additions & 2 deletions Libraries/MLXLLM/Models/Qwen35.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1282,7 +1282,11 @@ public class Qwen35TextModelInner: Module {
}
}

public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider {
public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider,
InputOnlyEmbeddingsProviding
{
public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart {
Expand Down Expand Up @@ -1489,7 +1493,9 @@ extension Qwen35TextModel: SpeculativeCacheRewindModel {

// MARK: - Top-level Model

public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider {
public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding {
public var inputOnlyEmbeddings: [Embedding] { languageModel.inputOnlyEmbeddings }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart { languageModel.kvCacheStart }
Expand Down
5 changes: 4 additions & 1 deletion Libraries/MLXLLM/Models/Qwen3MoE.swift
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,10 @@ public class Qwen3MoEModelInner: Module {
}
}

public class Qwen3MoEModel: Module, LLMModel, KVCacheDimensionProvider {
public class Qwen3MoEModel: Module, LLMModel, KVCacheDimensionProvider, InputOnlyEmbeddingsProviding
{
public var inputOnlyEmbeddings: [Embedding] { lmHead == nil ? [] : [model.embedTokens] }

public let vocabularySize: Int
public let kvHeads: [Int]
public var kvCacheStart: KVCacheStart { .compressed(headDim: configuration.headDim) }
Expand Down
3 changes: 2 additions & 1 deletion Libraries/MLXLLM/Models/Ricursive.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
202 changes: 202 additions & 0 deletions Libraries/MLXLMCommon/CheckpointTensorStorage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX
import MLXNN

#if canImport(Darwin)
import Darwin
import os
#endif

/// Keep source buffers alive while checkpoint preparation can rename or replace arrays.
package final class CheckpointTensorStorage {
#if canImport(Darwin)
fileprivate final class File: Sendable {
let handle: FileHandle
let url: URL
let status: stat
let directory: URL
private let mappedAddresses = OSAllocatedUnfairLock(initialState: Set<UInt>())

init(url: URL, directory: URL) throws {
let handle = try FileHandle(forReadingFrom: url)
var status = stat()
guard fstat(handle.fileDescriptor, &status) == 0,
status.st_mode & S_IFMT == S_IFREG
else { throw POSIXError(.EINVAL) }
self.handle = handle
self.url = url
self.status = status
self.directory = directory
}

deinit { try? handle.close() }

func matches(_ current: stat) -> Bool {
status.st_dev == current.st_dev && status.st_ino == current.st_ino
&& status.st_size == current.st_size
&& status.st_mtimespec.tv_sec == current.st_mtimespec.tv_sec
&& status.st_mtimespec.tv_nsec == current.st_mtimespec.tv_nsec
&& status.st_ctimespec.tv_sec == current.st_ctimespec.tv_sec
&& status.st_ctimespec.tv_nsec == current.st_ctimespec.tv_nsec
}

func unchanged(checkPath: Bool) -> Bool {
var current = stat()
guard fstat(handle.fileDescriptor, &current) == 0, matches(current) else {
return false
}
return !checkPath || (stat(url.path, &current) == 0 && matches(current))
}

func containsMappedAddress(_ address: UInt) -> Bool {
mappedAddresses.withLock { $0.contains(address) }
}

/// The tensor in file-backed storage, or nil if the file changed.
func array(for array: MLXArray, span: SafetensorSpan) throws -> MLXArray? {
guard unchanged(checkPath: false) else { return nil }
guard span.byteOffset >= 0, span.byteCount > 0,
span.byteCount == array.nbytes,
span.byteOffset <= status.st_size,
span.byteCount <= status.st_size - span.byteOffset
else { throw POSIXError(.EINVAL) }
// Typed reads need aligned views, so tensors at other offsets are copied first.
let result =
if span.byteOffset.isMultiple(of: Int64(MemoryLayout<UInt64>.alignment)) {
try fileBackedArray(
like: array, mapping: handle.fileDescriptor, offset: span.byteOffset)
} else {
try fileBackedArray(
like: array, copying: handle.fileDescriptor, offset: span.byteOffset,
directory: directory)
}
if let address = result.asData(access: .noCopy).data.withUnsafeBytes({
$0.baseAddress.map(UInt.init(bitPattern:))
}) {
mappedAddresses.withLock { _ = $0.insert(address) }
}
return result
}
}

private struct Source {
let snapshot: MLXArray
let strides: [Int]
let location: Mapping
}

private let locations: [String: Mapping]
private let vocabularySizes: Set<Int>
private var sources: [UInt: Source] = [:]
#endif

package struct Mapping: Sendable {
#if canImport(Darwin)
fileprivate let file: File
fileprivate let span: SafetensorSpan
#endif

func array(for array: MLXArray) throws -> MLXArray? {
#if canImport(Darwin)
return try file.array(for: array, span: span)
#else
return nil
#endif
}
}

let mappings: [String: Mapping]

/// Tensors that cannot map in place are copied into unlinked files in `directory`.
init?(
model: BaseLanguageModel, policy: EmbeddingStoragePolicy, urls: [URL],
quantization: BaseConfiguration.PerLayerQuantization? = nil,
directory: URL = FileManager.default.temporaryDirectory
) {
#if canImport(Darwin)
guard policy == .backed,
let provider = model as? any InputOnlyEmbeddingsProviding,
!provider.inputOnlyEmbeddings.isEmpty,
GPU.deviceInfo().maxBufferSize > 0
else { return nil }
var locations: [String: Mapping] = [:]
do {
for url in urls {
let file = try File(url: url, directory: directory)
for span in try safetensorSpansInFileOrder(url: url) {
locations[span.name] = Mapping(file: file, span: span)
}
guard file.unchanged(checkPath: true) else { return nil }
}
} catch { return nil }
self.locations = locations
self.vocabularySizes = Set(provider.inputOnlyEmbeddings.map { $0.weight.dim(0) })
let eligible = Set(provider.inputOnlyEmbeddings.map(ObjectIdentifier.init))
var mappings: [String: Mapping] = [:]
for (name, module) in model.namedModules() where eligible.contains(ObjectIdentifier(module))
{
guard let embedding = module as? Embedding else { continue }
let parameters: [String]
if embedding is QuantizedEmbedding {
guard supportsFileBackedStorage(embedding) else { continue }
parameters = ["weight", "scales", "biases"]
} else if let settings = quantization?.quantization(layer: name) {
guard type(of: embedding) == Embedding.self,
settings.mode == .affine, locations["\(name).scales"] != nil
else { continue }
parameters = ["weight", "scales", "biases"]
} else {
guard supportsFileBackedStorage(embedding) else { continue }
parameters = ["weight"]
}
for parameter in parameters {
let path = "\(name).\(parameter)"
mappings[path] = locations[path]
}
}
self.mappings = mappings
#else
return nil
#endif
}

func record(_ weights: [String: MLXArray]) {
#if canImport(Darwin)
for (name, value) in weights where value.ndim == 2 && vocabularySizes.contains(value.dim(0))
{
guard let location = locations[name], location.file.unchanged(checkPath: true),
location.span.byteCount == value.nbytes
else { continue }
// A second handle to the same array, which preparation cannot update in place.
let snapshot = value.reshaped(value.shape)
let data = snapshot.asData(access: .noCopy)
data.data.withUnsafeBytes { bytes in
guard let pointer = bytes.baseAddress else { return }
sources[UInt(bitPattern: pointer)] = Source(
snapshot: snapshot, strides: data.strides, location: location)
}
}
#endif
}

#if canImport(Darwin)
func array(matching array: MLXArray) throws -> MLXArray? {
let data = array.asData(access: .noCopy)
let source = data.data.withUnsafeBytes { bytes -> Source? in
guard let pointer = bytes.baseAddress else { return nil }
return sources[UInt(bitPattern: pointer)]
}
guard let source, source.snapshot.shape == array.shape,
source.snapshot.dtype == array.dtype, source.strides == data.strides,
source.location.file.unchanged(checkPath: false)
else { return nil }
let address = data.data.withUnsafeBytes { $0.baseAddress.map(UInt.init(bitPattern:)) }
if let address, source.location.file.containsMappedAddress(address) {
return source.snapshot
}
return try source.location.array(for: array)
}
#endif
}
2 changes: 1 addition & 1 deletion Libraries/MLXLMCommon/Documentation.docc/porting.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ public init(dimensions: Int, eps: Float = 1e-5) {
}
```

Note that the weight is given an initial value and shape based on the parameters to the initializer. In typical inference use, these values will be replaced when the weights are loaded (``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:)-fqoy``).
Note that the weight is given an initial value and shape based on the parameters to the initializer. In typical inference use, these values will be replaced when the weights are loaded (``loadWeights(modelDirectory:model:quantization:perLayerQuantization:weightFileSelection:excludedComponents:componentLoading:embeddingStorage:)-7iyka``).

* Note: If the property names in Python don't make good Swift names, you can use the `@ParameterInfo` property wrapper to specify the key: `@ParameterInfo(key: "some_weight") var weight: MLXArray`

Expand Down
Loading