Repository navigation
Use MaterializedArray for Sendable conformance #335
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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 } | ||
|
|
||
|
|
@@ -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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 {} | ||
| } | ||
|
|
||
|
|
@@ -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 } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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``): | ||
| /// | ||
|
|
@@ -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") | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This seems to drop the serialization guarantee previously provided. The old With this direct call, two tasks can now enter This may not be a real issue, except a documentation kind of inconsistency
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And we can have a synchronous |
||
| 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. | ||
|
|
@@ -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 | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
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.