Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,13 @@ func testMTPDrafterFactoryLoadFromDirectoryWhenCheckpointPresent() async throws
await Gemma4AssistantRegistration.register()
let factory = MTPDrafterModelFactory.shared

let container = try await factory.loadContainer(
let context = try await factory.load(
from: #hubDownloader(),
using: NoOpTokenizerLoader(),
configuration: .init(
id: "mlx-community/gemma-4-31B-it-assistant-bf16", revision: drafter31BRevision)
)
let isDrafter = await container.perform { ctx in
ctx.model is Gemma4AssistantDraftModel
}
let isDrafter = context.model is Gemma4AssistantDraftModel
#expect(isDrafter)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,6 @@ private func mtpFixturesDirOrSkip(name: String) async -> URL? {
// expensive (~30–60s); the `@Suite(.serialized)` wrapper below ensures
// the three Rung 4 case methods run sequentially, and this module-level
// cache reuses one (drafter, target) pair across all three.
//
// `Gemma4AssistantDraftModel` is deliberately non-Sendable (see the
// design note at Gemma4Assistant.swift:153–155 — Embedding is a
// reference type and cross-domain access must go through
// `MTPDrafterContainer.perform`). `nonisolated(unsafe)` is appropriate
// here because the suite is serialized — only one test runs at a time,
// and the cache becomes read-only after first population.
Comment on lines -39 to -45

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is obsolete, though the cache here looks like it probably needs at least a lock -- it isn't thread safe.


private struct Rung4BoundDrafter {
let drafter: Gemma4AssistantDraftModel
Expand Down
16 changes: 8 additions & 8 deletions Libraries/BenchmarkHelpers/BenchmarkHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -413,15 +413,15 @@ public func benchmarkEmbeddingLoading(
id: "mlx-community/Qwen3-Embedding-0.6B-8bit"),
runs: Int = BenchmarkDefaults.loadingRuns
) async throws -> BenchmarkStats {
_ = try await EmbedderModelFactory.shared.loadContainer(
_ = try await EmbedderModelFactory.shared.load(
from: downloader, using: tokenizerLoader, configuration: configuration
) { _ in }
Memory.clearCache()

var times: [Double] = []
for i in 1 ... runs {
let start = CFAbsoluteTimeGetCurrent()
_ = try await EmbedderModelFactory.shared.loadContainer(
_ = try await EmbedderModelFactory.shared.load(
from: downloader, using: tokenizerLoader, configuration: configuration
) { _ in }
let elapsed = (CFAbsoluteTimeGetCurrent() - start) * 1000
Expand Down Expand Up @@ -542,7 +542,7 @@ public func benchmarkLLMGeneration(
runs: Int = BenchmarkDefaults.loadingRuns
) async throws -> LLMGenerationStats {
let configuration = MLXLMCommon.ModelConfiguration(id: modelId)
let container = try await LLMModelFactory.shared.loadContainer(
let context = try await LLMModelFactory.shared.load(
from: downloader, using: tokenizerLoader, configuration: configuration
) { _ in }

Expand All @@ -558,9 +558,9 @@ public func benchmarkLLMGeneration(
// Warm-up: prime caches and weights. UserInput is `sending`, so build a
// fresh instance for each call.
do {
let warmInput = try await container.prepare(input: UserInput(prompt: benchmarkPrompt))
let warmStream = try await container.generate(
input: warmInput, parameters: parameters)
let warmInput = try await context.processor.prepare(
input: UserInput(prompt: benchmarkPrompt))
let warmStream = try generate(input: warmInput, parameters: parameters, context: context)
Comment on lines +561 to +563

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ModelContext instead of ModelContainer. The latter still works, but is deprecated.

for await _ in warmStream {}
}

Expand All @@ -570,8 +570,8 @@ public func benchmarkLLMGeneration(
var generationTokenCount = 0

for i in 1 ... runs {
let input = try await container.prepare(input: UserInput(prompt: benchmarkPrompt))
let stream = try await container.generate(input: input, parameters: parameters)
let input = try await context.processor.prepare(input: UserInput(prompt: benchmarkPrompt))
let stream = try generate(input: input, parameters: parameters, context: context)
var info: GenerateCompletionInfo?
for await item in stream {
if case .info(let i) = item { info = i }
Expand Down
20 changes: 10 additions & 10 deletions Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -485,8 +485,8 @@ public enum EmbedderTests {

public enum ToolCallTests {

public static func lfm2FormatAutoDetection(container: LLModelContainer) async throws {
let config = await container.configuration
public static func lfm2FormatAutoDetection(container: LLModelContainer) throws {
let config = container.configuration
try check(
config.toolCallFormat == ToolCallFormat.lfm2,
"Expected .lfm2 tool call format, got: \(String(describing: config.toolCallFormat))"
Expand Down Expand Up @@ -516,8 +516,8 @@ public enum ToolCallTests {
)
}

public static func glm4FormatAutoDetection(container: LLModelContainer) async throws {
let config = await container.configuration
public static func glm4FormatAutoDetection(container: LLModelContainer) throws {
let config = container.configuration
try check(
config.toolCallFormat == ToolCallFormat.glm4,
"Expected .glm4 tool call format, got: \(String(describing: config.toolCallFormat))"
Expand Down Expand Up @@ -549,8 +549,8 @@ public enum ToolCallTests {

// MARK: Mistral3

public static func mistral3FormatAutoDetection(container: LLModelContainer) async throws {
let config = await container.configuration
public static func mistral3FormatAutoDetection(container: LLModelContainer) throws {
let config = container.configuration
try check(
config.toolCallFormat == ToolCallFormat.mistral,
"Expected .mistral tool call format, got: \(String(describing: config.toolCallFormat))"
Expand Down Expand Up @@ -622,8 +622,8 @@ public enum ToolCallTests {

// MARK: Nemotron

public static func nemotronFormatAutoDetection(container: LLModelContainer) async throws {
let config = await container.configuration
public static func nemotronFormatAutoDetection(container: LLModelContainer) throws {
let config = container.configuration
try check(
config.toolCallFormat == ToolCallFormat.xmlFunction,
"Expected .xmlFunction tool call format, got: \(String(describing: config.toolCallFormat))"
Expand Down Expand Up @@ -697,8 +697,8 @@ public enum ToolCallTests {

// MARK: Qwen3.5

public static func qwen35FormatAutoDetection(container: LLModelContainer) async throws {
let config = await container.configuration
public static func qwen35FormatAutoDetection(container: LLModelContainer) throws {
let config = container.configuration
try check(
config.toolCallFormat == ToolCallFormat.xmlFunction,
"Expected .xmlFunction tool call format, got: \(String(describing: config.toolCallFormat))"
Expand Down
94 changes: 64 additions & 30 deletions Libraries/MLXEmbedders/EmbedderModelContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import MLXLMCommon

/// Container for embedder models that guarantees single threaded access.
///
/// * Important: `EmbedderModelContext` is now `Sendable` and can be used directly.
///
/// Wrap models used by e.g. the UI in a ModelContainer. Callers can access
/// the model and/or tokenizer (any values from the ``EmbedderModelContext``):
///
Expand All @@ -26,53 +28,84 @@ import MLXLMCommon
/// return result.map { $0.asArray(Float.self) }
/// }
/// ```
public final class EmbedderModelContainer: Sendable {
private let context: SerialAccessContainer<EmbedderModelContext>
///
/// ## Implementation Note
///
/// Previously the `EmbedderModelContainer` held the `EmbedderModelContext` in a `SerialAccessContainer` -- an internal type
/// that provided a lock-like exclusive access for ``perform(_:)-((EmbedderModelContext)->R)`` and ``update(_:)``.
/// The `EmbedderModelContext` was not `Sendable` and this provided the `@unchecked Sendable` protection needed.
/// In practice, some code would use ``perform(_:)-((EmbedderModelContext)->R)`` to
/// _borrow_ the model. This wouldn't have been safe if
/// another thread was mutating through the reference, of course.
///
/// The new code uses an `NSLock` to guard access to the `EmbedderModelContext`. The context is now `Sendable`
/// and the model itself is immutable. This now allows concurrent _use_ of the context -- all reads of the struct
/// itself are done under the lock. Callers to ``update(_:)`` can modify the context (to a lesser extent than before)
/// and this is done with the lock held.
///
/// Ideally, all use cases will move to use `EmbedderModelContext` directly, but in the meantime be aware of this
/// change in implementation.
@available(*, deprecated, message: "use EmbedderModelContext instead")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can start removing this. Everything should still work but it is no longer needed for Sendable conformance.

public final class EmbedderModelContainer: @unchecked (Sendable) {
private var _context: EmbedderModelContext
private let lock = NSLock()
private var context: EmbedderModelContext {
Comment on lines +50 to +52

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the API allows mutation (of a value type) we do it under lock so the mutation itself is thread safe.

get {
lock.lock()
defer { lock.unlock() }
return _context
}
set {
lock.lock()
defer { lock.unlock() }
_context = newValue
}
}

public var configuration: ModelConfiguration {
get async {
await context.read { $0.configuration }
}
context.configuration

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These become synchronous accessors.

}

public var tokenizer: Tokenizer {
get async {
await context.read { $0.tokenizer }
}
context.tokenizer
}

public var poolingStrategy: Pooling.Strategy {
get async {
await context.read { $0.pooling.strategy }
}
context.pooling.strategy
}

public init(context: consuming EmbedderModelContext) {
self.context = .init(context)
self._context = context
}

/// Perform an action on the ``EmbedderModelContext``.
/// Callers _must_ eval any `MLXArray` before returning as `MLXArray` is not `Sendable`.
///
/// - Note: The closure receives `EmbedderModelContext` which is not `Sendable`. This is intentional -
/// the closure runs within the actor's isolation, ensuring thread-safe access to the model.
/// - Note: The `sending` keyword indicates the return value is transferred (not shared) across
/// isolation boundaries, allowing non-Sendable types to be safely returned.
public func perform<R: Sendable>(
_ action: @Sendable (EmbedderModelContext) async throws -> sending R
) async rethrows -> sending R {
try await context.read {
try await action($0)
}
try await action(context)

@aleroot aleroot Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to drop the serialization guarantee previously provided. The old SerialAccessContainer.read held an async mutex for the full duration of the closure, including suspension points, so concurrent perform calls could not overlap on the same model/tokenizer/pooling context.

With this direct call, two tasks can now enter perform concurrently and use the same underlying context values at the same time, while the type-level documentation still says the container “guarantees single threaded access.” Even if MaterializedModule makes the wrapped model sendable, that does not by itself preserve the previous exclusive-access contract for all work reachable through the context.

This may not be a real issue, except a documentation kind of inconsistency

@davidkoski davidkoski Jun 10, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that is a good point -- it won't matter as much for the Embedders because they don't have state, but for example the KVCache is state. It has to have exclusive access or be some kind of copy-in/copy-out setup.

For example in ChatSession it had to play some games with private classes and knowledge of what was safe:

    private func streamMap<R: Sendable>() {
                try await cache.update { cache in

                    let model = await model.perform { context in
                        SendableBox(context.model)
                    }.consume()

This would get exclusive access to the KVCache and then "borrow" the model/weights -- it treated them as Sendable, but they were not represented that way in the type system. This had to be internal implementation because it required care to make sure it was thread safe.

My hope is that providing Sendable pieces would allow anyone to write this code and do it safely.

But your point about what is serial access vs not is important.

}

/// Perform an action on the ``EmbedderModelContext``.
///
/// This is the synchronous form of ``perform(_:)`` and has
/// fewer restrictions.
public func perform<R>(
_ action: @Sendable (EmbedderModelContext) throws -> R
) rethrows -> R {
Comment on lines +96 to +98

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And we can have a synchronous perform()

try action(context)
}

@available(*, deprecated, message: "use perform(_: (EmbedderModelContext) -> R) instead")
public func perform<R: Sendable>(
_ action: @Sendable (EmbeddingModel, Tokenizer, Pooling) async throws -> sending R
) async rethrows -> sending R {
try await context.read {
try await action($0.model, $0.tokenizer, $0.pooling)
}
try await action(
context.model, context.tokenizer, context.pooling
)
}

/// Perform an action on the ``EmbedderModelContext`` with additional (non `Sendable`) context values.
Expand All @@ -82,33 +115,34 @@ public final class EmbedderModelContainer: Sendable {
nonSendable values: consuming V,
_ action: @Sendable (EmbedderModelContext, V) async throws -> R
) async rethrows -> sending R {
let values = SendableBox(values)
return try await context.read {
try await action($0, values.consume())
}
try await action(context, values)
}

/// Update the owned `EmbedderModelContext`.
/// - Parameter action: update action
@available(
*, deprecated,
message: "mutate EmbedderModelContext before passing to EmbedderModelContainer"
)
public func update(_ action: @Sendable (inout EmbedderModelContext) -> Void) async {
await context.update {
action(&$0)
lock.withLock {
action(&_context)
}
}

// MARK: - Thread-safe convenience methods

/// The resolved local model directory for the loaded container.
public var modelDirectory: URL {
get async throws {
try (await configuration).modelDirectory
get throws {
try configuration.modelDirectory
}
}

/// The resolved local tokenizer directory for the loaded container.
public var tokenizerDirectory: URL {
get async throws {
try (await configuration).tokenizerDirectory
get throws {
try configuration.tokenizerDirectory
}
}
}
22 changes: 21 additions & 1 deletion Libraries/MLXEmbedders/EmbeddingModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import Foundation
import MLX
import MLXLMCommon
import MLXNN
@_spi(MaterializedModule) import MLXNN

public struct EmbeddingModelOutput {
public let hiddenStates: MLXArray?
Expand Down Expand Up @@ -48,3 +48,23 @@ extension EmbeddingModel {
attentionMask: attentionMask)
}
}

public typealias TrainableEmbeddingModel = EmbeddingModel & Module

extension MaterializedModule: EmbeddingModel where LayerType: EmbeddingModel {

public var vocabularySize: Int { _base.vocabularySize }
public var poolingStrategy: Pooling.Strategy? { _base.poolingStrategy }
public var maxPositionEmbeddings: Int? { _base.maxPositionEmbeddings }

public func callAsFunction(
_ inputs: MLXArray,
positionIds: MLXArray? = nil,
tokenTypeIds: MLXArray? = nil,
attentionMask: MLXArray? = nil
) -> EmbeddingModelOutput {
return _base(
inputs, positionIds: positionIds, tokenTypeIds: tokenTypeIds,
attentionMask: attentionMask)
}
}
Loading
Loading