diff --git a/IntegrationTesting/IntegrationTestingTests/MTPDrafterModelFactoryIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/MTPDrafterModelFactoryIntegrationTests.swift index 07ad4e3668..ef2c8aec87 100644 --- a/IntegrationTesting/IntegrationTestingTests/MTPDrafterModelFactoryIntegrationTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MTPDrafterModelFactoryIntegrationTests.swift @@ -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) } diff --git a/IntegrationTesting/IntegrationTestingTests/MTPRung4TokenParityTests.swift b/IntegrationTesting/IntegrationTestingTests/MTPRung4TokenParityTests.swift index ebf00c7c3e..191037bf07 100644 --- a/IntegrationTesting/IntegrationTestingTests/MTPRung4TokenParityTests.swift +++ b/IntegrationTesting/IntegrationTestingTests/MTPRung4TokenParityTests.swift @@ -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. private struct Rung4BoundDrafter { let drafter: Gemma4AssistantDraftModel diff --git a/Libraries/BenchmarkHelpers/BenchmarkHelpers.swift b/Libraries/BenchmarkHelpers/BenchmarkHelpers.swift index 8b18ce73ce..a09da76b1e 100644 --- a/Libraries/BenchmarkHelpers/BenchmarkHelpers.swift +++ b/Libraries/BenchmarkHelpers/BenchmarkHelpers.swift @@ -413,7 +413,7 @@ 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() @@ -421,7 +421,7 @@ public func benchmarkEmbeddingLoading( 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) 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 } diff --git a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift index cfaee158a3..6fddcb047c 100644 --- a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift +++ b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift @@ -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))" @@ -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))" @@ -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))" @@ -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))" @@ -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))" diff --git a/Libraries/MLXEmbedders/EmbedderModelContainer.swift b/Libraries/MLXEmbedders/EmbedderModelContainer.swift index 5ea6425d3e..7de6ccca37 100644 --- a/Libraries/MLXEmbedders/EmbedderModelContainer.swift +++ b/Libraries/MLXEmbedders/EmbedderModelContainer.swift @@ -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 +/// +/// ## 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") +public final class EmbedderModelContainer: @unchecked (Sendable) { + private var _context: EmbedderModelContext + private let lock = NSLock() + private var context: EmbedderModelContext { + 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 } 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( _ action: @Sendable (EmbedderModelContext) async throws -> sending R ) async rethrows -> sending R { - try await context.read { - try await action($0) - } + try await action(context) + } + + /// Perform an action on the ``EmbedderModelContext``. + /// + /// This is the synchronous form of ``perform(_:)`` and has + /// fewer restrictions. + public func perform( + _ action: @Sendable (EmbedderModelContext) throws -> R + ) rethrows -> R { + try action(context) } @available(*, deprecated, message: "use perform(_: (EmbedderModelContext) -> R) instead") public func perform( _ 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,17 +115,18 @@ 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) } } @@ -100,15 +134,15 @@ public final class EmbedderModelContainer: Sendable { /// 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 } } } diff --git a/Libraries/MLXEmbedders/EmbeddingModel.swift b/Libraries/MLXEmbedders/EmbeddingModel.swift index 2fb9c588d4..35684e071e 100644 --- a/Libraries/MLXEmbedders/EmbeddingModel.swift +++ b/Libraries/MLXEmbedders/EmbeddingModel.swift @@ -3,7 +3,7 @@ import Foundation import MLX import MLXLMCommon -import MLXNN +@_spi(MaterializedModule) import MLXNN public struct EmbeddingModelOutput { public let hiddenStates: MLXArray? @@ -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) + } +} diff --git a/Libraries/MLXEmbedders/ModelFactory.swift b/Libraries/MLXEmbedders/ModelFactory.swift index 1cd49b7067..b1b1f2a4ad 100644 --- a/Libraries/MLXEmbedders/ModelFactory.swift +++ b/Libraries/MLXEmbedders/ModelFactory.swift @@ -16,7 +16,7 @@ private func create( /// Registry of model type, e.g 'bert', to functions that can instantiate the model from configuration. public enum EmbedderTypeRegistry { - public static let shared: ModelTypeRegistry = .init(creators: [ + public static let shared: ModelTypeRegistry = .init(creators: [ "bert": create(BertConfiguration.self) { BertModel($0) }, "roberta": create(BertConfiguration.self) { BertModel($0) }, "xlm-roberta": create(BertConfiguration.self) { BertModel($0) }, @@ -124,16 +124,25 @@ public class EmbedderRegistry: AbstractModelRegistry, @unchecked Sendable { /// Context of values that work together to provide an ``EmbeddingModel``. /// -/// This is created using a ``EmbedderModelFactory`` and often used -/// inside a ``EmbedderModelContainer``. -public struct EmbedderModelContext { +/// This is created using a ``EmbedderModelFactory``. +public struct EmbedderModelContext: Sendable { public var configuration: ModelConfiguration - public var model: any EmbeddingModel + public var model: any EmbeddingModel & Sendable public var tokenizer: any Tokenizer public let pooling: Pooling public init( - configuration: ModelConfiguration, model: any EmbeddingModel, + configuration: ModelConfiguration, model: some TrainableEmbeddingModel, + tokenizer: any Tokenizer, pooling: Pooling + ) { + self.configuration = configuration + self.model = MaterializedModule(model) + self.tokenizer = tokenizer + self.pooling = pooling + } + + public init( + configuration: ModelConfiguration, model: some EmbeddingModel & Sendable, tokenizer: any Tokenizer, pooling: Pooling ) { self.configuration = configuration @@ -152,7 +161,7 @@ public struct EmbedderModelContext { /// let downloader: any Downloader /// let tokenizerLoader: any TokenizerLoader /// let modelId = "mlx-community/gemma-3-1b-it-qat-4bit" -/// let modelContainer = try await EmbedderModelFactory.shared.loadContainer( +/// let modelContainer = try await EmbedderModelFactory.shared.load( /// from: downloader, using: tokenizerLoader, configuration: .init(id: modelId), /// progressHandler: logProgress(modelId) /// ) @@ -160,10 +169,9 @@ public struct EmbedderModelContext { public final class EmbedderModelFactory: GenericModelFactory { public typealias ContextType = EmbedderModelContext - public typealias ContainerType = EmbedderModelContainer public init( - typeRegistry: ModelTypeRegistry, + typeRegistry: ModelTypeRegistry, modelRegistry: AbstractModelRegistry ) { self.typeRegistry = typeRegistry @@ -175,7 +183,7 @@ public final class EmbedderModelFactory: GenericModelFactory { typeRegistry: EmbedderTypeRegistry.shared, modelRegistry: EmbedderRegistry.shared) /// registry of model type, e.g. configuration value `gemma3` -> configuration and init methods - public let typeRegistry: ModelTypeRegistry + public let typeRegistry: ModelTypeRegistry /// registry of model id to configuration, e.g. `sentence-transformers/all-MiniLM-L6-v2` public let modelRegistry: AbstractModelRegistry @@ -204,7 +212,7 @@ public final class EmbedderModelFactory: GenericModelFactory { configurationURL.lastPathComponent, configuration.name, error) } - let model: EmbeddingModel + let model: any TrainableEmbeddingModel do { model = try await typeRegistry.createModel( configuration: configData, modelType: baseConfig.modelType) @@ -245,7 +253,39 @@ public final class EmbedderModelFactory: GenericModelFactory { ) } - public func _wrap(_ context: EmbedderModelContext) -> EmbedderModelContainer { - .init(context: context) + /// Load a model from a ``Downloader`` and ``ModelConfiguration``, + /// producing a ``ModelContainer``. + /// + /// Note: `ModelContext` is now `Sendable` and is preferred over `ModelContainer`. + @available(*, deprecated, message: "use load instead") + public func loadContainer( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> EmbedderModelContainer { + let context = try await load( + from: downloader, + using: tokenizerLoader, + configuration: configuration, + useLatest: useLatest, progressHandler: progressHandler) + return EmbedderModelContainer(context: context) + } + + /// Load a model from a local directory, producing a ``ModelContainer``. + /// + /// Note: `ModelContext` is now `Sendable` and is preferred over `ModelContainer`. + @available(*, deprecated, message: "use load instead") + public func loadContainer( + from directory: URL, + using tokenizerLoader: any TokenizerLoader + ) async throws -> EmbedderModelContainer { + let context = try await load( + from: LocalDownloader(url: directory), + using: tokenizerLoader, + configuration: .init(directory: directory), + useLatest: false, progressHandler: { _ in }) + return EmbedderModelContainer(context: context) } } diff --git a/Libraries/MLXEmbedders/Pooling.swift b/Libraries/MLXEmbedders/Pooling.swift index 597487e45a..1a23eb6037 100644 --- a/Libraries/MLXEmbedders/Pooling.swift +++ b/Libraries/MLXEmbedders/Pooling.swift @@ -80,7 +80,7 @@ func loadPooling(modelDirectory: URL, model: EmbeddingModel) -> Pooling { /// /// `Pooling` takes the sequence of hidden states from a transformer model and collapses them /// into a single vector using strategies like mean, max, or token selection. -open class Pooling: Module { +public struct Pooling: Sendable { /// Supported pooling strategies. public enum Strategy: Sendable { @@ -99,10 +99,10 @@ open class Pooling: Module { } /// The active strategy used for pooling hidden states. - public private(set) var strategy: Strategy + public let strategy: Strategy /// Optional dimension to truncate the resulting embedding to. - public private(set) var dimension: Int? + public let dimension: Int? /// Initializes a `Pooling` module with a specific strategy. /// - Parameters: diff --git a/Libraries/MLXEmbedders/README.md b/Libraries/MLXEmbedders/README.md index 10d9c54081..cf848801a7 100644 --- a/Libraries/MLXEmbedders/README.md +++ b/Libraries/MLXEmbedders/README.md @@ -6,12 +6,14 @@ This directory contains ports of popular Encoders / Embedding Models. ```swift import MLXEmbedders -import MLXEmbeddersHuggingFace +import MLXLMCommon import MLXLMTokenizers +import MLXLMHuggingFace -let modelContainer = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( + from: HubClient.default, using: TokenizersLoader(), - configuration: .nomic_text_v1_5 + configuration: EmbedderRegistry.nomic_text_v1_5 ) let searchInputs = [ "search_query: Animals in Tropical Climates.", @@ -21,45 +23,48 @@ let searchInputs = [ ] // Generate embeddings -let resultEmbeddings = await modelContainer.perform { - (model: EmbeddingModel, tokenizer: Tokenizer, pooling: Pooling) -> [[Float]] in - let inputs = searchInputs.map { - tokenizer.encode(text: $0, addSpecialTokens: true) - } - // Pad to longest - let maxLength = inputs.reduce(into: 16) { acc, elem in - acc = max(acc, elem.count) - } +let model = context.model +let tokenizer = context.tokenizer +let pooling = context.pooling - let padded = stacked( - inputs.map { elem in - MLXArray( - elem - + Array( - repeating: tokenizer.eosTokenId ?? 0, - count: maxLength - elem.count)) - }) - let mask = (padded .!= tokenizer.eosTokenId ?? 0) - let tokenTypes = MLXArray.zeros(like: padded) - let result = pooling( - model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask), - normalize: true, applyLayerNorm: true - ) - result.eval() - return result.map { $0.asArray(Float.self) } +let inputs = searchInputs.map { + tokenizer.encode(text: $0, addSpecialTokens: true) } +// Pad to longest +let maxLength = inputs.reduce(into: 16) { acc, elem in + acc = max(acc, elem.count) +} + +let padded = stacked( + inputs.map { elem in + MLXArray( + elem + + Array( + repeating: tokenizer.eosTokenId ?? 0, + count: maxLength - elem.count)) + }) +let mask = (padded .!= tokenizer.eosTokenId ?? 0) +let tokenTypes = MLXArray.zeros(like: padded) +let result = pooling( + model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask), + normalize: true, applyLayerNorm: true +) +result.eval() +let resultEmbeddings = result.map { $0.asArray(Float.self) } ``` Load from a local directory: ```swift import MLXEmbedders +import MLXLMCommon import MLXLMTokenizers let modelDirectory = URL(filePath: "/path/to/embedder") -let modelContainer = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: modelDirectory, - using: TokenizersLoader() + using: TokenizersLoader(), + configuration: EmbedderRegistry.nomic_text_v1_5 ) ``` @@ -67,14 +72,15 @@ Use a custom Hugging Face client: ```swift import MLXEmbedders -import MLXEmbeddersHuggingFace +import MLXLMCommon import MLXLMTokenizers +import MLXLMHuggingFace let hub = HubClient(token: "hf_...") -let modelContainer = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: hub, using: TokenizersLoader(), - configuration: .nomic_text_v1_5 + configuration: EmbedderRegistry.nomic_text_v1_5 ) ``` @@ -98,7 +104,7 @@ struct S3Downloader: Downloader { } } -let modelContainer = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: S3Downloader(), using: TokenizersLoader(), configuration: .init(id: "my-bucket/my-embedder") diff --git a/Libraries/MLXHuggingFace/Macros.swift b/Libraries/MLXHuggingFace/Macros.swift index 54092ce505..407beb3d75 100644 --- a/Libraries/MLXHuggingFace/Macros.swift +++ b/Libraries/MLXHuggingFace/Macros.swift @@ -7,7 +7,7 @@ import MLXLMCommon /// import MLXHuggingFace /// import HuggingFace /// -/// let model = try await loadModelContainer( +/// let model = try await loadModel( /// from: #hubDownloader(HubClient()), /// using: #huggingFaceTokenizerLoader(), /// configuration: modelConfiguration @@ -23,7 +23,7 @@ public macro hubDownloader(_ hub: Any) -> MLXLMCommon.Downloader = /// import MLXHuggingFace /// import HuggingFace /// -/// let model = try await loadModelContainer( +/// let model = try await loadModel( /// from: #hubDownloader(), /// using: #huggingFaceTokenizerLoader(), /// configuration: modelConfiguration @@ -55,7 +55,7 @@ public macro adaptHuggingFaceTokenizer(_ upstream: Any) -> MLXLMCommon.Tokenizer /// import MLXHuggingFace /// import HuggingFace /// -/// let model = try await loadModelContainer( +/// let model = try await loadModel( /// from: #hubDownloader(), /// using: #huggingFaceTokenizerLoader(), /// configuration: modelConfiguration @@ -76,6 +76,7 @@ public macro huggingFaceTokenizerLoader() -> MLXLMCommon.TokenizerLoader = /// configuration: modelConfiguration /// ) /// ``` +@available(*, deprecated, message: "use huggingFaceLoadModel instead") @freestanding(expression) public macro huggingFaceLoadModelContainer( configuration: ModelConfiguration @@ -93,6 +94,7 @@ public macro huggingFaceLoadModelContainer( /// configuration: modelConfiguration /// ) { progres in ... } /// ``` +@available(*, deprecated, message: "use huggingFaceLoadModel instead") @freestanding(expression) public macro huggingFaceLoadModelContainer( configuration: ModelConfiguration, @@ -135,6 +137,24 @@ public macro huggingFaceLoadModel( ) -> ModelContext = #externalMacro(module: "MLXHuggingFaceMacros", type: "LoadContextMacro") +/// Load a `TrainableModelContext` using default hub client and tokenizer loader with progress. +/// +/// ```swift +/// import MLXHuggingFace +/// import HuggingFace +/// import Tokenizers +/// +/// let modelContext = try await huggingFaceLoadTrainableModel( +/// configuration: modelConfiguration +/// ) { progres in ... } +/// ``` +@freestanding(expression) +public macro huggingFaceLoadTrainableModel( + configuration: ModelConfiguration, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } +) -> TrainableModelContext = + #externalMacro(module: "MLXHuggingFaceMacros", type: "LoadTrainableContextMacro") + public enum HuggingFaceDownloaderError: LocalizedError { case invalidRepositoryID(String) diff --git a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift index 35e5559c17..6e2585c602 100644 --- a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift +++ b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift @@ -11,6 +11,7 @@ struct Macros: CompilerPlugin { TokenizerLoaderMacro.self, LoadContainerMacro.self, LoadContextMacro.self, + LoadTrainableContextMacro.self, LanguageModelMacro.self, ] } @@ -166,14 +167,16 @@ public struct LoadContainerMacro: ExpressionMacro { "#huggingFaceLoadModelContainer requires a configuration") } - let progress = - if let expr = node.arguments.first(where: { $0.label?.text == "progressHandler" })? - .expression - { - expr.description - } else { - "{ _ in }" - } + let progress: String + if let expr = node.arguments.first(where: { $0.label?.text == "progressHandler" })? + .expression + { + progress = expr.description + } else if let trailingClosure = node.trailingClosure { + progress = trailingClosure.description + } else { + progress = "{ _ in }" + } return """ @@ -195,14 +198,16 @@ public struct LoadContextMacro: ExpressionMacro { throw MacroExpansionError.message("#huggingFaceLoadModel requires a configuration") } - let progress = - if let expr = node.arguments.first(where: { $0.label?.text == "progressHandler" })? - .expression - { - expr.description - } else { - "{ _ in }" - } + let progress: String + if let expr = node.arguments.first(where: { $0.label?.text == "progressHandler" })? + .expression + { + progress = expr.description + } else if let trailingClosure = node.trailingClosure { + progress = trailingClosure.description + } else { + progress = "{ _ in }" + } return """ @@ -215,6 +220,38 @@ public struct LoadContextMacro: ExpressionMacro { } } +public struct LoadTrainableContextMacro: ExpressionMacro { + public static func expansion( + of node: some FreestandingMacroExpansionSyntax, + in context: some MacroExpansionContext + ) throws -> ExprSyntax { + guard let configuration = node.arguments.first?.expression else { + throw MacroExpansionError.message( + "#huggingFaceLoadTrainableModel requires a configuration") + } + + let progress: String + if let expr = node.arguments.first(where: { $0.label?.text == "progressHandler" })? + .expression + { + progress = expr.description + } else if let trailingClosure = node.trailingClosure { + progress = trailingClosure.description + } else { + progress = "{ _ in }" + } + + return + """ + loadTrainable( + from: #hubDownloader(), + using: #huggingFaceTokenizerLoader(), + configuration: \(configuration), + progressHandler: \(raw: progress)) + """ + } +} + public struct LanguageModelMacro: ExpressionMacro { public static func expansion( of node: some FreestandingMacroExpansionSyntax, diff --git a/Libraries/MLXLLM/Documentation.docc/using-model.md b/Libraries/MLXLLM/Documentation.docc/using-model.md index e4d4f400ee..ccda188dd2 100644 --- a/Libraries/MLXLLM/Documentation.docc/using-model.md +++ b/Libraries/MLXLLM/Documentation.docc/using-model.md @@ -19,13 +19,15 @@ let modelConfiguration: ModelConfiguration // e.g. TokenizersLoader() from MLXLMTokenizers let tokenizerLoader: any TokenizerLoader -let container = try await modelFactory.loadContainer( +let context = try await modelFactory.load( using: tokenizerLoader, configuration: modelConfiguration ) ``` -The `container` provides an isolation context (an `actor`) to run inference in the model. +The result is a `ModelContext` -- a `Sendable` struct whose `model` is wrapped in +a `MaterializedModule` -- that you use directly. There is no actor or isolation +wrapper to work through. Predefined `ModelConfiguration` instances are provided as static variables on the `ModelRegistry` types or they can be created: @@ -80,18 +82,13 @@ This example shows adding some images and processing instructions -- if model accepts text only then these parts can be omitted. The inference calls are the same. -Assuming you are using a `ModelContainer` (an actor that holds -a `ModelContext`, which is the bundled set of types that implement a -model), the first step is to convert the `UserInput` into the +Assuming you are using a `ModelContext` (which is the bundled set of +types that implement a model), the first step is to convert the `UserInput` into the `LMInput` (LanguageModel Input): ```swift let generateParameters: GenerateParameters -let input: UserInput - -let result = try await modelContainer.perform { [input] context in - let input = try context.processor.prepare(input: input) - +let input = try context.processor.prepare(input: input) ``` Given that `input` we can call `generate()` to produce a stream @@ -100,26 +97,25 @@ to assist in converting a stream of tokens into text and print it. The stream is stopped after we hit a maximum number of tokens: ``` - var detokenizer = NaiveStreamingDetokenizer(tokenizer: context.tokenizer) - - return try MLXLMCommon.generate( - input: input, parameters: generateParameters, context: context - ) { tokens in - - if let last = tokens.last { - detokenizer.append(token: last) - } - - if let new = detokenizer.next() { - print(new, terminator: "") - fflush(stdout) - } - - if tokens.count >= maxTokens { - return .stop - } else { - return .more - } +var detokenizer = NaiveStreamingDetokenizer(tokenizer: context.tokenizer) + +return try MLXLMCommon.generate( + input: input, parameters: generateParameters, context: context +) { tokens in + + if let last = tokens.last { + detokenizer.append(token: last) + } + + if let new = detokenizer.next() { + print(new, terminator: "") + fflush(stdout) + } + + if tokens.count >= maxTokens { + return .stop + } else { + return .more } } ``` diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 1925dc41a6..cd63bd33cd 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -19,11 +19,11 @@ private func create( /// Registry of model type, e.g 'llama', to functions that can instantiate the model from configuration. /// -/// Typically called via ``LLMModelFactory/loadContainer(from:using:configuration:useLatest:progressHandler:)``. +/// Typically called via ``LLMModelFactory/load(from:using:configuration:useLatest:progressHandler:)``. public enum LLMTypeRegistry { /// Shared instance with default model types. - public static let shared: ModelTypeRegistry = .init(creators: [ + public static let shared: ModelTypeRegistry = .init(creators: [ "mistral": create(LlamaConfiguration.self, LlamaModel.init), "mixtral": create(MixtralConfiguration.self, MixtralModel.init), "llama": create(LlamaConfiguration.self, LlamaModel.init), @@ -541,16 +541,16 @@ private struct LLMUserInputProcessor: UserInputProcessor { /// is required. /// /// ```swift -/// let modelContainer = try await LLMModelFactory.shared.loadContainer( +/// let model = try await LLMModelFactory.shared.load( /// configuration: LLMRegistry.llama3_8B_4bit) /// ``` -public final class LLMModelFactory: GenericModelFactory { +public final class LLMModelFactory: GenericModelFactory, TrainableModelContextLoader { public typealias ContextType = ModelContext - public typealias ContainerType = ModelContainer public init( - typeRegistry: ModelTypeRegistry, modelRegistry: AbstractModelRegistry + typeRegistry: ModelTypeRegistry, + modelRegistry: AbstractModelRegistry ) { self.typeRegistry = typeRegistry self.modelRegistry = modelRegistry @@ -561,15 +561,45 @@ public final class LLMModelFactory: GenericModelFactory { typeRegistry: LLMTypeRegistry.shared, modelRegistry: LLMRegistry.shared) /// registry of model type, e.g. configuration value `llama` -> configuration and init methods - public let typeRegistry: ModelTypeRegistry + public let typeRegistry: ModelTypeRegistry /// registry of model id to configuration, e.g. `mlx-community/Llama-3.2-3B-Instruct-4bit` public let modelRegistry: AbstractModelRegistry + /// Load a model from a ``Downloader`` and ``ModelConfiguration``, + /// producing a ``TrainableModelContext``. + /// + /// Use this when the model needs to be mutated -- e.g. for training or + /// applying adapters (LoRA). The model inside a ``ModelContext`` is + /// materialized and sealed and cannot be modified; convert a trainable + /// context to an inference ``ModelContext`` via `ModelContext(_:)` when done. + public func loadTrainable( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> sending TrainableModelContext { + let resolved = try await resolve( + configuration: configuration, from: downloader, + useLatest: useLatest, progressHandler: progressHandler) + return try await _loadTrainable(configuration: resolved, tokenizerLoader: tokenizerLoader) + } + public func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader ) async throws -> ModelContext { + let trainable = try await _loadTrainable( + configuration: configuration, tokenizerLoader: tokenizerLoader) + return ModelContext(trainable) + } + + /// internal load of a TrainableModelContext that can be converted into a ModelContext + private func _loadTrainable( + configuration: ResolvedModelConfiguration, + tokenizerLoader: any TokenizerLoader + ) async throws -> TrainableModelContext { let modelDirectory = configuration.modelDirectory // Load config.json once and decode for both base config and model-specific config @@ -589,7 +619,7 @@ public final class LLMModelFactory: GenericModelFactory { configurationURL.lastPathComponent, configuration.name, error) } - let model: LanguageModel + let model: any TrainableLanguageModel do { model = try await typeRegistry.createModel( configuration: configData, modelType: baseConfig.modelType) diff --git a/Libraries/MLXLLM/ModelConversion.swift b/Libraries/MLXLLM/ModelConversion.swift index d4908990f3..7cc6401a99 100644 --- a/Libraries/MLXLLM/ModelConversion.swift +++ b/Libraries/MLXLLM/ModelConversion.swift @@ -112,7 +112,7 @@ extension LLMModelFactory { configurationURL.lastPathComponent, configuration.name, error) } - let model: LanguageModel + let model: TrainableLanguageModel do { model = try await typeRegistry.createModel( configuration: configData, modelType: baseConfig.modelType) diff --git a/Libraries/MLXLMCommon/Adapters/LoRA/LoRAContainer.swift b/Libraries/MLXLMCommon/Adapters/LoRA/LoRAContainer.swift index f1858ebea9..2017495061 100644 --- a/Libraries/MLXLMCommon/Adapters/LoRA/LoRAContainer.swift +++ b/Libraries/MLXLMCommon/Adapters/LoRA/LoRAContainer.swift @@ -96,7 +96,7 @@ public struct LoRAContainer: ModelAdapter, @unchecked Sendable { /// /// Note: This function freezes the model base weights and applies LoRA layers to it. public static func from( - model: LanguageModel, + model: TrainableLanguageModel, configuration: LoRAConfiguration = .init() ) throws -> LoRAContainer { guard let lora = model as? LoRAModel else { @@ -138,7 +138,7 @@ public struct LoRAContainer: ModelAdapter, @unchecked Sendable { /// This method replaces target layers in the model with corresponding /// adapter layers based on the configuration. It also loads adapter-specific /// weights into the model. - public func load(into model: LanguageModel) throws { + public func load(into model: TrainableLanguageModel) throws { guard let lora = model as? LoRAModel else { throw ModelAdapterError.incompatibleModelType } @@ -159,7 +159,7 @@ public struct LoRAContainer: ModelAdapter, @unchecked Sendable { /// /// After fusion, adapter weights become part of the model’s original parameters, /// and adapter layers are no longer needed. - public func fuse(with model: LanguageModel) throws { + public func fuse(with model: TrainableLanguageModel) throws { guard let lora = model as? LoRAModel else { throw ModelAdapterError.incompatibleModelType } @@ -175,7 +175,7 @@ public struct LoRAContainer: ModelAdapter, @unchecked Sendable { /// Removes adapter layers (LoRA or DoRA) and restores the model to its original form. /// /// This method reverts each adapted layer to its original linear layer, if possible. - public func unload(from model: LanguageModel) { + public func unload(from model: TrainableLanguageModel) { guard let lora = model as? LoRAModel else { return // Don't throw an error because nothing was likely applied before } diff --git a/Libraries/MLXLMCommon/Adapters/ModelAdapter.swift b/Libraries/MLXLMCommon/Adapters/ModelAdapter.swift index 62ae85d58e..fd101627bf 100644 --- a/Libraries/MLXLMCommon/Adapters/ModelAdapter.swift +++ b/Libraries/MLXLMCommon/Adapters/ModelAdapter.swift @@ -19,19 +19,19 @@ public enum ModelAdapterError: Error { public protocol ModelAdapter: Sendable { /// Loads the adapter into the specified model. - func load(into model: LanguageModel) throws + func load(into model: TrainableLanguageModel) throws /// Permanently fuses the adapter into the specified model. - func fuse(with model: LanguageModel) throws + func fuse(with model: TrainableLanguageModel) throws /// Unloads the adapter from the specified model. - func unload(from model: LanguageModel) + func unload(from model: TrainableLanguageModel) } public typealias SendableModelAdapter = ModelAdapter & Sendable /// Extension to `LanguageModel` providing convenience methods for adapter usage. -extension LanguageModel { +extension LanguageModel where Self: TrainableLanguageModel { /// Loads an adapter into the model. /// diff --git a/Libraries/MLXLMCommon/Chat.swift b/Libraries/MLXLMCommon/Chat.swift index e2c8d9861e..12ccc1bc8a 100644 --- a/Libraries/MLXLMCommon/Chat.swift +++ b/Libraries/MLXLMCommon/Chat.swift @@ -1,7 +1,7 @@ // Copyright © 2025 Apple Inc. public enum Chat { - public struct Message { + public struct Message: Sendable { /// The role of the message sender. public var role: Role diff --git a/Libraries/MLXLMCommon/ChatSession.swift b/Libraries/MLXLMCommon/ChatSession.swift index 3b7963d9e9..e524be62df 100644 --- a/Libraries/MLXLMCommon/ChatSession.swift +++ b/Libraries/MLXLMCommon/ChatSession.swift @@ -17,8 +17,8 @@ import CoreGraphics /// /// Example usage: /// ```swift -/// let main = try await LLMModelFactory.shared.loadContainer(configuration: mainConfig) -/// let draft = try await LLMModelFactory.shared.loadContainer(configuration: draftConfig) +/// let main = try await LLMModelFactory.shared.load(configuration: mainConfig) +/// let draft = try await LLMModelFactory.shared.load(configuration: draftConfig) /// /// let session = ChatSession( /// main, @@ -36,15 +36,15 @@ import CoreGraphics /// draftModelBytes: estimatedDraftBytes, /// memoryPolicy: .recommendedWorkingSet /// ) { -/// try await LLMModelFactory.shared.loadContainer(configuration: draftConfig) +/// try await LLMModelFactory.shared.load(configuration: draftConfig) /// } /// ) /// ``` public struct SpeculativeDecodingConfig: Sendable { package enum DraftModelSource: Sendable { - case loaded(ModelContainer) - case deferred(bytes: Int, @Sendable () async throws -> ModelContainer) + case loaded(ModelContext) + case deferred(bytes: Int, @Sendable () async throws -> ModelContext) } package let draftModelSource: DraftModelSource @@ -54,7 +54,7 @@ public struct SpeculativeDecodingConfig: Sendable { /// Configurations initialized with a loader closure return `nil` because the /// draft model is loaded asynchronously by ``ChatSession`` only when speculation /// is admitted by the memory policy. - public var draftModel: ModelContainer? { + public var draftModel: ModelContext? { if case .loaded(let draftModel) = draftModelSource { return draftModel } @@ -72,7 +72,7 @@ public struct SpeculativeDecodingConfig: Sendable { public let memoryPolicy: SpeculativeDecodingMemoryPolicy? public init( - draftModel: ModelContainer, + draftModel: ModelContext, numDraftTokens: Int = 5, memoryPolicy: SpeculativeDecodingMemoryPolicy? = nil ) { @@ -97,7 +97,7 @@ public struct SpeculativeDecodingConfig: Sendable { draftModelBytes: Int, numDraftTokens: Int = 5, memoryPolicy: SpeculativeDecodingMemoryPolicy? = nil, - loadDraftModel: @escaping @Sendable () async throws -> ModelContainer + loadDraftModel: @escaping @Sendable () async throws -> ModelContext ) { self.draftModelSource = .deferred(bytes: max(0, draftModelBytes), loadDraftModel) self.numDraftTokens = numDraftTokens @@ -111,7 +111,7 @@ public struct SpeculativeDecodingConfig: Sendable { return bytes } - package func loadDraftModel() async throws -> ModelContainer { + package func loadDraftModel() async throws -> ModelContext { switch draftModelSource { case .loaded(let draftModel): draftModel @@ -126,8 +126,8 @@ public struct SpeculativeDecodingConfig: Sendable { /// For example: /// /// ```swift -/// let modelContainer = try await loadModelContainer(id: "mlx-community/Qwen3-4B-4bit") -/// let session = ChatSession(modelContainer) +/// let model = try await loadModel(id: "mlx-community/Qwen3-4B-4bit") +/// let session = ChatSession(model) /// 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?")) /// ``` @@ -135,16 +135,16 @@ public struct SpeculativeDecodingConfig: Sendable { /// To enable speculative decoding for faster generation, pass a `SpeculativeDecodingConfig`: /// /// ```swift -/// let draft = try await LLMModelFactory.shared.loadContainer(configuration: draftConfig) +/// let draft = try await LLMModelFactory.shared.load(configuration: draftConfig) /// let session = ChatSession( -/// modelContainer, +/// model, /// speculativeDecoding: SpeculativeDecodingConfig(draftModel: draft) /// ) /// ``` /// /// - Note: `ChatSession` is not thread-safe. Each session should be used from a single -/// task/thread at a time. The underlying `ModelContainer` handles thread safety for -/// model operations. +/// task/thread at a time. The `ModelContext` it holds is `Sendable` (its model is a +/// `MaterializedModule`), so it can be shared across sessions and tasks. public final class ChatSession { enum Cache { @@ -157,10 +157,12 @@ public final class ChatSession { case history([Chat.Message]) } - private let model: ModelContainer + private let modelContext: ModelContext public var instructions: String? private let cache: SerialAccessContainer - private let loadedDraftModel: SerialAccessContainer + + // note: this is in a SerialAccessContainer because it can be loaded on the fly + private let loadedDraftModel: SerialAccessContainer public var processing: UserInput.Processing public var generateParameters: GenerateParameters public var additionalContext: [String: any Sendable]? @@ -181,6 +183,7 @@ public final class ChatSession { /// - tools: optional tool specifications /// - toolDispatch: optional tool dispatch -- required for toolcalls if streaming strings rather than details /// - additionalContext: optional model-specific context + @available(*, deprecated, message: "use ModelContext variant instead") public init( _ model: ModelContainer, instructions: String? = nil, @@ -191,7 +194,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = model + self.modelContext = model.materialize() self.instructions = instructions self.cache = .init(.empty) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -224,7 +227,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = ModelContainer(context: model) + self.modelContext = model self.instructions = instructions self.cache = .init(.empty) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -250,10 +253,11 @@ public final class ChatSession { /// - tools: optional tool specifications /// - toolDispatch: optional tool dispatch -- required for toolcalls if streaming strings rather than details /// - additionalContext: optional model-specific context + @available(*, deprecated, message: "use ModelContext variant instead") public init( _ model: ModelContainer, instructions: String? = nil, - history: consuming [Chat.Message], + history: [Chat.Message], speculativeDecoding: SpeculativeDecodingConfig? = nil, generateParameters: GenerateParameters = .init(), processing: UserInput.Processing = .init(resize: CGSize(width: 512, height: 512)), @@ -261,7 +265,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = model + self.modelContext = model.materialize() self.instructions = instructions self.cache = .init(.history(history)) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -298,7 +302,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = ModelContainer(context: model) + self.modelContext = model self.instructions = instructions self.cache = .init(.history(history)) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -333,6 +337,7 @@ public final class ChatSession { /// - tools: optional tool specifications /// - toolDispatch: optional tool dispatch -- required for toolcalls if streaming strings rather than details /// - additionalContext: optional model-specific context + @available(*, deprecated, message: "use ModelContext variant instead") public init( _ model: ModelContainer, instructions: String? = nil, @@ -344,7 +349,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = model + self.modelContext = model.materialize() self.instructions = instructions self.cache = .init(.kvcache(cache, draftKVCache: nil, state: nil)) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -390,7 +395,7 @@ public final class ChatSession { tools: [ToolSpec]? = nil, toolDispatch: (@Sendable (ToolCall) async throws -> String)? = nil ) { - self.model = ModelContainer(context: model) + self.modelContext = model self.instructions = instructions self.cache = .init(.kvcache(cache, draftKVCache: nil, state: nil)) self.loadedDraftModel = .init(speculativeDecoding?.draftModel) @@ -414,9 +419,9 @@ public final class ChatSession { public func respond( to prompt: String, role: Chat.Message.Role = .user, - images: consuming [UserInput.Image], - videos: consuming [UserInput.Video], - audios: consuming [UserInput.Audio] + images: [UserInput.Image], + videos: [UserInput.Video], + audios: [UserInput.Audio] ) async throws -> String { var output = "" for try await chunk in streamResponse( @@ -439,9 +444,9 @@ public final class ChatSession { public func respond( to prompt: String, role: Chat.Message.Role = .user, - image: consuming UserInput.Image? = nil, - video: consuming UserInput.Video? = nil, - audio: consuming UserInput.Audio? = nil + image: UserInput.Image? = nil, + video: UserInput.Video? = nil, + audio: UserInput.Audio? = nil ) async throws -> String { try await respond( to: prompt, @@ -465,7 +470,7 @@ public final class ChatSession { /// - Parameter messages: chat messages to append before generation /// - Returns: the model's response public func respond( - to messages: consuming [Chat.Message] + to messages: [Chat.Message] ) async throws -> String { var output = "" for try await chunk in streamResponse(to: messages) { @@ -486,9 +491,9 @@ public final class ChatSession { public func streamResponse( to prompt: String, role: Chat.Message.Role = .user, - images: consuming [UserInput.Image] = [], - videos: consuming [UserInput.Video] = [], - audios: consuming [UserInput.Audio] = [] + images: [UserInput.Image] = [], + videos: [UserInput.Video] = [], + audios: [UserInput.Audio] = [] ) -> AsyncThrowingStream { streamMap(to: prompt, role: role, images: images, videos: videos, audios: audios) { $0.chunk @@ -503,7 +508,7 @@ public final class ChatSession { /// - Parameter messages: chat messages to append before generation /// - Returns: a stream of string chunks from the model public func streamResponse( - to messages: consuming [Chat.Message] + to messages: [Chat.Message] ) -> AsyncThrowingStream { streamMap(messages: messages) { $0.chunk @@ -522,9 +527,9 @@ public final class ChatSession { public func streamDetails( to prompt: String, role: Chat.Message.Role = .user, - images: consuming [UserInput.Image] = [], - videos: consuming [UserInput.Video] = [], - audios: consuming [UserInput.Audio] = [], + images: [UserInput.Image] = [], + videos: [UserInput.Video] = [], + audios: [UserInput.Audio] = [], ) -> AsyncThrowingStream { streamMap(to: prompt, role: role, images: images, videos: videos, audios: audios) { $0 @@ -539,7 +544,7 @@ public final class ChatSession { /// - Parameter messages: chat messages to append before generation /// - Returns: a stream of `Generation` from the model public func streamDetails( - to messages: consuming [Chat.Message] + to messages: [Chat.Message] ) -> AsyncThrowingStream { streamMap(messages: messages) { $0 @@ -558,9 +563,9 @@ public final class ChatSession { private func streamMap( to prompt: String, role: Chat.Message.Role, - images: consuming [UserInput.Image] = [], - videos: consuming [UserInput.Video] = [], - audios: consuming [UserInput.Audio] = [], + images: [UserInput.Image] = [], + videos: [UserInput.Video] = [], + audios: [UserInput.Audio] = [], transform: @Sendable @escaping (Generation) -> R? ) -> AsyncThrowingStream { streamMap( @@ -572,51 +577,30 @@ public final class ChatSession { } private func streamMap( - messages: consuming [Chat.Message], + messages inputMessages: [Chat.Message], transform: @Sendable @escaping (Generation) -> R? ) -> AsyncThrowingStream { let (stream, continuation) = AsyncThrowingStream.makeStream() - // images and videos are not Sendable (MLXArray) but they are consumed - // and are only being sent to the inner async - let inputMessages = SendableBox<[Chat.Message]>(messages) - let task = Task { [ - model, + modelContext, instructions, processing, tools, toolDispatch, additionalContext, cache, loadedDraftModel, generateParameters, speculativeDecoding ] in do { try await cache.update { cache in - // these are all Sendable - let processor = await model.processor - let tokenizer = await model.tokenizer - let modelConfiguration = await model.configuration + let model = modelContext.model + let processor = modelContext.processor + let tokenizer = modelContext.tokenizer + let modelConfiguration = modelContext.configuration var messages: [Chat.Message] = [] if let instructions { messages.append(.system(instructions)) } - // prepare the cache, if needed. note: - // this is using the LanguageModel (not Sendable) outside - // the protective lock. Assuming the weights are not - // being mutated behind the scenes, this will obey the MLXArray - // contract that they be evaluated if used across threads. - // This is internal to the implementation and this technique - // should not be used in calling code. - // - // The benefit is that callers can be running multiple - // ChatSessions in parallel, as long as the instances - // are distinct. In particular the KVCache cannot - // be shared and that is the lock that is held here. - - let model = await model.perform { context in - SendableBox(context.model) - }.consume() - var kvCache: [KVCache] var draftKVCache: [KVCache]? // Per-call model state (e.g. M-RoPE rope deltas) carried @@ -641,7 +625,7 @@ public final class ChatSession { } // prepare the input - messages.append(contentsOf: inputMessages.consume()) + messages.append(contentsOf: inputMessages) // loop can restart on tool calls restart: while !messages.isEmpty { @@ -684,9 +668,7 @@ public final class ChatSession { speculativeDecoding.estimatedDraftModelBytes { let memoryEvaluation = memoryPolicy.evaluate( - mainModelBytes: - SpeculativeDecodingMemoryPolicy - .modelWeightBytes(model), + mainModelBytes: model.parameterNBytes, draftModelBytes: draftModelBytes ) if !memoryEvaluation.shouldUseSpeculativeDecoding { @@ -702,18 +684,14 @@ public final class ChatSession { if shouldFallBackBeforeLoadingDraft { (genStream, genTask) = try defaultGeneration() } else { - let cachedDraftContainer = await loadedDraftModel.read { $0 } - let draftContainer: ModelContainer - if let cachedDraftContainer { - draftContainer = cachedDraftContainer + let cachedDraftContext = await loadedDraftModel.read { $0 } + let draftContext: ModelContext + if let cachedDraftContext { + draftContext = cachedDraftContext } else { - draftContainer = try await speculativeDecoding.loadDraftModel() + draftContext = try await speculativeDecoding.loadDraftModel() } - - // Extract the draft model from its container (same pattern as the main model). - let draftModel = await draftContainer.perform { context in - SendableBox(context.model) - }.consume() + let draftModel = draftContext.model let memoryEvaluation = speculativeDecoding.memoryPolicy?.evaluate( mainModel: model, @@ -729,10 +707,12 @@ public final class ChatSession { (genStream, genTask) = try defaultGeneration() } else { - if cachedDraftContainer == nil { + if cachedDraftContext == nil { + // The draft model can be loaded on the fly so it is + // protected by a SerialAccessContainer await loadedDraftModel.update { storedDraftModel in if storedDraftModel == nil { - storedDraftModel = draftContainer + storedDraftModel = draftContext } } } @@ -845,9 +825,9 @@ public final class ChatSession { /// - Returns: a stream of string chunks from the model public func streamResponse( to prompt: String, - image: consuming UserInput.Image? = nil, - video: consuming UserInput.Video? = nil, - audio: consuming UserInput.Audio? = nil + image: UserInput.Image? = nil, + video: UserInput.Video? = nil, + audio: UserInput.Audio? = nil ) -> AsyncThrowingStream { streamResponse( to: prompt, diff --git a/Libraries/MLXLMCommon/Documentation.docc/porting.md b/Libraries/MLXLMCommon/Documentation.docc/porting.md index 3969ec3082..0176865516 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/porting.md +++ b/Libraries/MLXLMCommon/Documentation.docc/porting.md @@ -604,7 +604,7 @@ let modelConfiguration = ModelConfiguration(id: "mlx-community/quantized-gemma-2 let tokenizerLoader: any TokenizerLoader // This will download the weights and load the model -let container = try await MLXModelFactory.shared.loadContainer( +let context = try await MLXModelFactory.shared.load( using: tokenizerLoader, configuration: modelConfiguration ) @@ -613,19 +613,19 @@ let container = try await MLXModelFactory.shared.loadContainer( let generateParameters = GenerateParameters() let input = UserInput(prompt: "Are cherries sweet?") +// Convert the UserInput into LMInput +let lmInput = try context.processor.prepare(input: input) + // Run inference -let result = try await modelContainer.perform { [input] context in - // Convert the UserInput into LMInput - let input = try context.processor.prepare(input: input) - - return generate(input: input, parameters: generateParameters, context: context) { tokens in - // This could potentially use NaiveStreamingDetokenizer and print - // text as it was generated - if tokens.count >= 20 { - return .stop - } else { - return .more - } +let result = generate( + input: lmInput, parameters: generateParameters, context: context +) { tokens in + // This could potentially use NaiveStreamingDetokenizer and print + // text as it was generated + if tokens.count >= 20 { + return .stop + } else { + return .more } } diff --git a/Libraries/MLXLMCommon/Documentation.docc/upgrade.md b/Libraries/MLXLMCommon/Documentation.docc/upgrade.md index 55f1395fa5..ab6b7f26c8 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/upgrade.md +++ b/Libraries/MLXLMCommon/Documentation.docc/upgrade.md @@ -48,7 +48,7 @@ import HuggingFace import Tokenizers let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit -let model = try await #huggingFaceLoadModelContainer( +let model = try await #huggingFaceLoadModel( configuration: modelConfiguration ) @@ -67,7 +67,7 @@ import HuggingFace import Tokenizers let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit -let model = try await loadModelContainer( +let model = try await loadModel( from: #hubDownloader(), using: #huggingFaceTokenizerLoader(), configuration: modelConfiguration @@ -99,7 +99,7 @@ import MLXLMCommon import IntegrationPackage let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit -let model = try await loadModelContainer( +let model = try await loadModel( from: HubClient(), configuration: modelConfiguration ) @@ -145,8 +145,8 @@ let defaultModelConfiguration = EmbedderRegistry.nomic_text_v1_5 let hub = #hubDownloader() let loader = #huggingFaceTokenizerLoader() -// MLXEmbedders.loadModelContainer (free function) -> EmbedderModelFactory.shared.loadContainer -let container = try await EmbedderModelFactory.shared.loadContainer( +// MLXEmbedders.loadModelContainer (free function) -> EmbedderModelFactory.shared.load +let context = try await EmbedderModelFactory.shared.load( from: hub, using: loader, configuration: configuration @@ -161,7 +161,7 @@ These types are removed or replaced: - `ModelConfiguration.nomic_text_v1_5` -> `EmbedderRegistry.nomic_text_v1_5` - `BaseConfiguration` -> use MLXLMCommon - `ModelType` - removed -- `ModelContainer` -> EmbedderModelContainer and EmbedderModelContext (matches LLM/VLM concepts) +- `ModelContainer` -> EmbedderModelContext (matches LLM/VLM concepts; `EmbedderModelContainer` is deprecated) - `load()` free functions -> EmbedderModelFactory ## Release Notes @@ -188,7 +188,7 @@ let container = try await loadModelContainer( // After (3.x) – Using HuggingFace integration macros import MLXHuggingFace -let model = try await #huggingFaceLoadModelContainer( +let model = try await #huggingFaceLoadModel( configuration: LLMRegistry.gemma3_1B_qat_4bit ) ``` @@ -202,13 +202,13 @@ Loading from a local directory: let container = try await loadModelContainer(directory: modelDirectory) // After (3.x) -let container = try await loadModelContainer(from: modelDirectory) +let context = try await loadModel(from: modelDirectory) ``` Loading with a model factory: ```swift -let container = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, configuration: modelConfiguration ) @@ -272,3 +272,60 @@ The `defaultHubApi` global has been removed. Hugging Face Hub access is now prov - `ModelFactory._load(hub:configuration:progressHandler:)` → `_load(configuration: ResolvedModelConfiguration)` - `ModelFactory._loadContainer`: removed (base `loadContainer` now builds the container from `_load`) +## `ModelContext` is now Sendable + +`ModelContext` (and `EmbedderModelContext`) are now `Sendable`: the model they +hold is wrapped in a `MaterializedModule`, which evaluates and materializes all +of its parameters and seals the module against mutation. This means you can hold +a `ModelContext` and pass it directly across tasks and actors -- there is no +longer any need for a container wrapper to coordinate access. + +Because of this the `ModelContainer` / `EmbedderModelContainer` wrappers are +deprecated, along with their `perform`, async property accessors, and `update` +methods. Instead of: + +```swift +let result = try await modelContainer.perform { [input] context in + let input = try context.processor.prepare(input: input) + return generate(input: input, parameters: parameters, context: context) { ... } +} +``` + +use the `ModelContext` directly: + +```swift +let input = try context.processor.prepare(input: input) +let result = generate(input: input, parameters: parameters, context: context) { ... } +``` + +The loading APIs are renamed to return a `ModelContext` rather than a container: + +- `loadModelContainer(...)` → `loadModel(...)` +- `factory.loadContainer(...)` → `factory.load(...)` +- `#huggingFaceLoadModelContainer(...)` → `#huggingFaceLoadModel(...)` + +The old names remain as deprecated aliases. + +### Training and Adapters + +Because a `ModelContext`'s model is materialized and sealed, it cannot be +mutated -- so it cannot be used for training or applying adapters (e.g. LoRA). +For those use cases load a trainable model instead, which returns a mutable +`TrainableModelContext`: + +- free function `loadTrainable(...)` +- `factory.loadTrainable(...)` +- macro `#huggingFaceLoadTrainableModel(configuration:progressHandler:)` + +Once training is complete you can convert a `TrainableModelContext` into an +inference `ModelContext` with `ModelContext(trainableContext)`. + +### Crossing Isolation Boundaries with MLXArray + +A plain `MLXArray` is still not `Sendable` and remains lazy. To move array data +across an isolation boundary, read a scalar with `.item()` or convert it to a +Sendable snapshot with `array.materialized()`, which yields a +`MaterializedArray` -- a fully-evaluated, immutable `MLXArray` you can use +anywhere an `MLXArray` is expected. + + diff --git a/Libraries/MLXLMCommon/Documentation.docc/using.md b/Libraries/MLXLMCommon/Documentation.docc/using.md index ccbc96b4be..2f8d15ee4c 100644 --- a/Libraries/MLXLMCommon/Documentation.docc/using.md +++ b/Libraries/MLXLMCommon/Documentation.docc/using.md @@ -148,7 +148,7 @@ import Tokenizers let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit -let model = try await #huggingFaceLoadModelContainer( +let model = try await #huggingFaceLoadModel( configuration: modelConfiguration ) @@ -170,7 +170,7 @@ import MLXHuggingFace let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit -let model = try await LLMModelFactory.shared.loadContainer( +let model = try await LLMModelFactory.shared.load( from: #hubDownloader(), using: #huggingFaceTokenizerLoader(), configuration: modelConfiguration diff --git a/Libraries/MLXLMCommon/Downloader.swift b/Libraries/MLXLMCommon/Downloader.swift index 60aaa2c1f1..645cd9cb0d 100644 --- a/Libraries/MLXLMCommon/Downloader.swift +++ b/Libraries/MLXLMCommon/Downloader.swift @@ -35,6 +35,22 @@ public protocol Downloader: Sendable { ) async throws -> URL } +/// Implementation of Downloader that produces a local URL. +public struct LocalDownloader: Downloader { + let url: URL + + public init(url: URL) { + self.url = url + } + + public func download( + id: String, revision: String?, matching patterns: [String], useLatest: Bool, + progressHandler: @escaping (Progress) -> Void + ) async throws -> URL { + url + } +} + /// Identifies where a tokenizer should be loaded from. /// /// Used by ``ModelConfiguration`` to specify an alternate tokenizer source diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index df34922e17..19af5775fd 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -1263,7 +1263,7 @@ private func runSynchronousGenerationLoop( /// - extraEOSTokens: any additional stop tokens /// - didGenerate: visitor for the tokens as they are generated @available( - *, deprecated, + *, unavailable, message: "Use the AsyncStream-based generate(input:cache:parameters:context:) instead for better Swift concurrency support" ) @@ -1273,21 +1273,7 @@ public func generate( extraEOSTokens: Set? = nil, didGenerate: ([Int]) -> GenerateDisposition ) throws -> GenerateResult { - let tokens = MLXArray(promptTokens) - let iterator = try TokenIterator( - prompt: tokens, model: model, parameters: parameters) - - // this is a compatibility cover -- create the required values - // for the iteration - let input = LMInput(tokens: tokens) - let configuration = ModelConfiguration(id: "stand-in", extraEOSTokens: extraEOSTokens ?? []) - let context = ModelContext( - configuration: configuration, model: model, processor: StandInUserInputProcessor(), - tokenizer: tokenizer) - - return generate( - input: input, context: context, iterator: iterator, - didGenerate: didGenerate) + fatalError("not implemented") } /// Generate tokens from an ``LMInput`` and a ``ModelContext``. @@ -1465,13 +1451,14 @@ public func generate( /// } /// } /// ``` -public func generate( - input: LMInput, cache: [KVCache]? = nil, parameters: GenerateParameters, context: ModelContext, +public func generate( + input: LMInput, cache: [KVCache]? = nil, parameters: GenerateParameters, + context: C, wiredMemoryTicket: WiredMemoryTicket? = nil, tools: [[String: any Sendable]]? = nil ) throws -> AsyncStream { let iterator = try TokenIterator( - input: input, model: context.model, cache: cache, parameters: parameters) + input: input, model: context.languageModel, cache: cache, parameters: parameters) let (stream, _) = generateTask( promptTokenCount: input.text.tokens.size, modelConfiguration: context.configuration, diff --git a/Libraries/MLXLMCommon/LanguageModel.swift b/Libraries/MLXLMCommon/LanguageModel.swift index 147b07cca2..bfb136d317 100644 --- a/Libraries/MLXLMCommon/LanguageModel.swift +++ b/Libraries/MLXLMCommon/LanguageModel.swift @@ -2,10 +2,17 @@ import Foundation import MLX -import MLXNN +@_spi(MaterializedModule) import MLXNN /// Abstract form of a model that processes language. -public protocol BaseLanguageModel: Module { +public protocol BaseLanguageModel { + + /// Sum of all the `nbytes` of the parameters in the encapsulated model. + var parameterNBytes: Int { get } + + /// Sum of all the `parameterCount` of the modules in the encapsulated model. + var parameterCount: Int { get } + /// Optionally preprocess the weights and modify / remove values as needed. func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] @@ -37,6 +44,14 @@ extension BaseLanguageModel { } } +extension BaseLanguageModel where Self: Module { + public var parameterNBytes: Int { + parameters().reduce(0) { $0 + $1.nbytes } + } +} + +public typealias TrainableBaseLanguageModel = BaseLanguageModel & Module + /// Time/Height/Width struct to represent information about input images. public struct THW: Sendable { @@ -300,3 +315,46 @@ extension LanguageModel where Self: KVCacheDimensionProvider { } } } + +/// A mutable and trainable LanguageModel. +/// +/// This is a `Module` so it can be fine tuned, e.g. with LoRA. It is _not_ Sendable. +/// +/// See also ``TrainableModelContext`` and ``ModelContext``. +public typealias TrainableLanguageModel = LanguageModel & Module + +extension MaterializedModule: BaseLanguageModel where LayerType: BaseLanguageModel { + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + _base.sanitize(weights: weights) + } + + public func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: + MLXArray] + { + _base.sanitize(weights: weights, metadata: metadata) + } +} + +extension MaterializedModule: LanguageModel where LayerType: LanguageModel { + + public func prepare( + _ input: LMInput, cache: [any KVCache], state: LMOutput.State?, windowSize: Int? + ) throws -> PrepareResult { + try _base.prepare(input, cache: cache, state: state, windowSize: windowSize) + } + + public func callAsFunction(_ input: LMInput.Text, cache: [KVCache]?, state: LMOutput.State?) + -> LMOutput + { + _base.callAsFunction(input, cache: cache, state: state) + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + _base.callAsFunction(inputs, cache: cache) + } + + public func newCache(parameters: GenerateParameters?) -> [KVCache] { + _base.newCache(parameters: parameters) + } +} diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 8ea5f9293d..b7c7b80678 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -40,7 +40,7 @@ package func safetensorWeightURLs(in modelDirectory: URL) throws -> [URL] { /// applies optional quantization, and /// updates the model with the weights. public func loadWeights( - modelDirectory: URL, model: BaseLanguageModel, + modelDirectory: URL, model: TrainableBaseLanguageModel, quantization: BaseConfiguration.Quantization? = nil, perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil ) throws { diff --git a/Libraries/MLXLMCommon/MTPDrafterModel.swift b/Libraries/MLXLMCommon/MTPDrafterModel.swift index fe916794bf..f081889551 100644 --- a/Libraries/MLXLMCommon/MTPDrafterModel.swift +++ b/Libraries/MLXLMCommon/MTPDrafterModel.swift @@ -2,7 +2,7 @@ import Foundation import MLX -import MLXNN +@_spi(MaterializedModule) import MLXNN /// Protocol for Multi-Token Prediction (MTP) speculative drafter models. /// @@ -59,26 +59,44 @@ public protocol MTPDrafterModel: BaseLanguageModel { ) -> MLXArray } +public typealias TrainableMTPDrafterModel = MTPDrafterModel & Module + +extension MaterializedModule: MTPDrafterModel where LayerType: MTPDrafterModel { + + public func draftBlock( + target: any LanguageModel, lastToken: MLXArray, lastHidden: MLXArray, + sharedKV: [String: (MLXArray, MLXArray)], queryOffset: Int, blockSize: Int, + sampler: any LogitSampler + ) -> MLXArray { + _base.draftBlock( + target: target, + lastToken: lastToken, lastHidden: lastHidden, + sharedKV: sharedKV, queryOffset: queryOffset, + blockSize: blockSize, sampler: sampler) + } +} + /// Lightweight context for an MTP drafter — simpler than `ModelContext` /// because drafters have no tokenizer, no user input processor, no chat /// template. -/// -/// Not `Sendable`; cross-domain access goes through ``MTPDrafterContainer``. -public struct MTPDrafterContext { +public struct MTPDrafterContext: Sendable { public var configuration: ModelConfiguration - public var model: any MTPDrafterModel + public var model: any MTPDrafterModel & Sendable - public init(configuration: ModelConfiguration, model: any MTPDrafterModel) { + public init(configuration: ModelConfiguration, model: some TrainableMTPDrafterModel) { self.configuration = configuration - self.model = model + self.model = MaterializedModule(model) } } /// Sendable container for an ``MTPDrafterContext``. /// +/// * Important: `MTPDrafterContext` is now `Sendable` and can be used directly. +/// /// Mirrors the ``ModelContainer`` pattern: a `final class : Sendable` that /// wraps the non-Sendable context in a `SerialAccessContainer` and exposes /// async `perform(_:)` closures for serialized access. +@available(*, deprecated, message: "use MTPDrafterContext instead") public final class MTPDrafterContainer: Sendable { private let context: SerialAccessContainer diff --git a/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift b/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift index d13274ccc1..1fc32176ee 100644 --- a/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift +++ b/Libraries/MLXLMCommon/MTPDrafterModelFactory.swift @@ -17,7 +17,7 @@ import MLX public enum MTPDrafterTypeRegistry { /// Shared registry. Empty until a downstream module registers a drafter /// type via `await MTPDrafterTypeRegistry.shared.registerModelType(...)`. - public static let shared: ModelTypeRegistry = .init() + public static let shared: ModelTypeRegistry = .init() } /// Registry of model id (e.g. `"mlx-community/gemma-4-31B-it-assistant-bf16"`) @@ -44,18 +44,17 @@ public class MTPDrafterRegistry: AbstractModelRegistry, @unchecked Sendable { /// tokenizer). public final class MTPDrafterModelFactory: GenericModelFactory { public typealias ContextType = MTPDrafterContext - public typealias ContainerType = MTPDrafterContainer public static let shared = MTPDrafterModelFactory( typeRegistry: MTPDrafterTypeRegistry.shared, modelRegistry: MTPDrafterRegistry.shared ) - public let typeRegistry: ModelTypeRegistry + public let typeRegistry: ModelTypeRegistry public let modelRegistry: AbstractModelRegistry public init( - typeRegistry: ModelTypeRegistry, + typeRegistry: ModelTypeRegistry, modelRegistry: AbstractModelRegistry ) { self.typeRegistry = typeRegistry @@ -83,7 +82,7 @@ public final class MTPDrafterModelFactory: GenericModelFactory { configurationURL.lastPathComponent, configuration.name, error) } - let model: any MTPDrafterModel + let model: any TrainableMTPDrafterModel do { model = try await typeRegistry.createModel( configuration: configData, modelType: baseConfig.modelType) @@ -104,8 +103,4 @@ public final class MTPDrafterModelFactory: GenericModelFactory { ) return MTPDrafterContext(configuration: modelConfig, model: model) } - - public func _wrap(_ context: MTPDrafterContext) -> MTPDrafterContainer { - .init(context: context) - } } diff --git a/Libraries/MLXLMCommon/ModelContainer.swift b/Libraries/MLXLMCommon/ModelContainer.swift index 9ecc309d76..f24f070357 100644 --- a/Libraries/MLXLMCommon/ModelContainer.swift +++ b/Libraries/MLXLMCommon/ModelContainer.swift @@ -6,6 +6,9 @@ import MLXNN /// Container for models that guarantees single threaded access. /// +/// * Important: `ModelContext` is now `Sendable` that can be used directly. `ModelContainer` +/// is now deprecated. +/// /// Wrap models used by e.g. the UI in a ModelContainer. Callers can access /// the model and/or tokenizer (any values from the ``ModelContext``): /// @@ -29,8 +32,164 @@ import MLXNN /// } /// } /// ``` -public final class ModelContainer: Sendable { - private let context: SerialAccessContainer +/// +/// ## Source Compatibility +/// +/// All callers _should_ migrate to using ``ModelContext`` or ``TrainableModelContext`` directly. +/// +/// Previously this held and provided a `ModelContext`. That type still exists but is now `Sendable` +/// and immutable. The container now holds a `TrainableModelContext`, which is equivalent +/// to the old mutable context. +/// +/// Methods, such as ``perform(_:)->_``, call the closure with a `TrainableModelContext`. +/// Typical calls to this will still compile -- the type inference finds the new type and the methods are +/// the same. +/// +/// From example code, there are two cases that must be updated. The first is when your closure calls +/// a function that will mutate the context: +/// +/// ```swift +/// // OLD +/// func prepare(_ context: inout ModelContext) { ... } +/// +/// // NEW +/// func prepare(_ context: inout TrainableModelContext) { ... } +/// ``` +/// +/// The second is when the closure calls a method that will do inference (or related) and +/// just needs access to the tokenizer and `LanguageModel`: +/// +/// ```swift +/// // OLD +/// func generate(input: LMInput, context: ModelContext) async throws -> ... { ... } +/// +/// // NEW +/// func generate(input: LMInput, context: ModelContextProviding) async throws -> ... { ... } +/// ``` +/// +/// Code that relies on type inference should build without change. +/// +/// ## Migration +/// +/// `ModelContainer` and methods that create it are all deprecated. There are two main +/// patterns for migration off of it and onto ``ModelContext`` and ``TrainableModelContext``. +/// For inference-only uses, migrate onto `ModelContext`. +/// +/// * Note: Both original examples still work, but they now have deprecation warnings. +/// +/// For example, if you had code along these lines: +/// +/// ```swift +/// let modelContainer = try await LLMModelFactory.shared.loadContainer( +/// from: self.downloader, +/// using: #huggingFaceTokenizerLoader(), +/// configuration: modelConfiguration) +/// +/// let session = ChatSession( +/// modelContainer, +/// instructions: "You are a helpful assistant." +/// ) +/// +/// let response = try await session.respond(to: "Tell me a story.") +/// print(response) +/// ``` +/// +/// You could switch it to `ModelContext` by calling `loadModel()` instead +/// of `loadContainer()`: +/// +/// ```swift +/// let modelContext = try await LLMModelFactory.shared.load( +/// from: self.downloader, +/// using: #huggingFaceTokenizerLoader(), +/// configuration: modelConfiguration) +/// +/// let session = ChatSession( +/// modelContext, +/// instructions: "You are a helpful assistant." +/// ) +/// +/// let response = try await session.respond(to: "Tell me a story.") +/// print(response) +/// ``` +/// +/// For cases where the goal is model mutation, e.g. training or LoRA fine-tuning, you will need +/// a ``TrainableModelContext``. If the previous code looked like this: +/// +/// ```swift +/// let modelContainer = try await LLMModelFactory.shared.loadContainer( +/// from: self.downloader, +/// using: #huggingFaceTokenizerLoader(), +/// configuration: modelConfiguration) +/// +/// modelAdapter = try await modelContainer.perform { context in +/// return try LoRAContainer.from( +/// model: context.model, configuration: LoRAConfiguration(numLayers: loraLayers)) +/// } +/// ``` +/// +/// The migrated code would call `loadTrainable()` instead: +/// +/// ```swift +/// // load a mutable language model +/// let modelContext = try await LLMModelFactory.shared.loadTrainable( +/// from: self.downloader, +/// using: #huggingFaceTokenizerLoader(), +/// configuration: modelConfiguration) +/// +/// // augment the model with LoRA adaptors +/// modelAdapter = try! LoRAContainer.from( +/// model: modelContext.model, configuration: LoRAConfiguration(numLayers: loraLayers)) +/// ``` +/// +/// ## Mutation and Thread Safety +/// +/// In earlier versions, `ModelContainer` stored a plain `Module`. If you had reference to it, +/// you could mutate it. The ``update(_:)`` method was meant for this purpose, though in +/// practice that was only used to mutate the `ModelConfiguration`, +/// +/// However, there are cases where callers also mutated through the context's `model` reference: +/// +/// ```swift +/// modelAdapter = try await modelContainer.perform { context in +/// return try LoRAContainer.from( +/// model: context.model, configuration: LoRAConfiguration(numLayers: loraLayers)) +/// } +/// ``` +/// +/// This appears to be thread safe -- the `ModelContainer` guarantees exclusive access to the +/// context during calls to ``perform(_:)->_``, but in practice callers would carefully _borrow_ +/// the model in order to allow concurrent evaluation. As long as LoRA (or other training) was not +/// done at the same time as inference, this worked, but was unsafe. See: +/// +/// - ``generate(input:parameters:wiredMemoryTicket:)`` +/// - ``ChatSession`` +/// +/// Now, the container stores a ``TrainableModelContext`` and a private `MaterializedState`. +/// If a caller initializes a ``ChatSession`` with a `ModelContainer`, this will materialize the +/// model and produce a `ModelContext`. Callers who attempt to access the +/// ``TrainableModelContext`` after this occurs will be met with a `fatalError`. +/// +/// * Important: there is a race when initializing `ChatSession` and using `perform()`. +/// This implements a best effort check, but cannot guarantee it doesn't happen. This race is +/// probably insignificant when compared to callers that escape the `model` in calls to +/// `perform()` (including this type's own ``generate(input:parameters:wiredMemoryTicket:)``). +/// These are done on purpose, but were never safe when combined with mutation +/// +/// Please migrate to ``ModelContext`` and ``TrainableModelContext`` directly as +/// soon as possible. +@available(*, deprecated, message: "use ModelContext instead") +public final class ModelContainer: @unchecked (Sendable) { + + private let context: SerialAccessContainer + + /// Internal state to provide `ChatSession` with synchronous access to the ModelContext + private enum MaterializedState { + case editable(TrainableModelContext) + case materialized(ModelContext) + } + + private var _state: MaterializedState + private let lock = NSLock() public var configuration: ModelConfiguration { get async { @@ -50,8 +209,44 @@ public final class ModelContainer: Sendable { } } - public init(context: consuming ModelContext) { + public init(context: TrainableModelContext) { self.context = .init(context) + self._state = .editable(context) + } + + /// Verify that the model is still mutable (has not been materialized). + /// + /// Note: there is a race in calling this and using `context`. This is + /// best effort on top of the fact that many callers allowed the `model` + /// to escape calls to `perform()`. + /// + /// Migrate off `ModelContainer` at your earliest convenience. + private func check() { + lock.withLock { + switch _state { + case .editable: + break + case .materialized: + fatalError("context has been converted to ModelContext (immutable)") + } + } + } + + /// Allow ChatSession to obtain a materialized version of the ModelContext. + /// + /// Note: this permanently marks the main context as unusable as it is not longer + /// mutable. + func materialize() -> ModelContext { + lock.withLock { + switch _state { + case .editable(let context): + let materialized = ModelContext.init(context) + _state = .materialized(materialized) + return materialized + case .materialized(let context): + return context + } + } } /// Perform an action on the model and/or tokenizer. Callers _must_ eval any `MLXArray` before returning as @@ -63,7 +258,8 @@ public final class ModelContainer: Sendable { async rethrows -> sending R { - try await context.read { + check() + return try await context.read { try action($0.model, $0.tokenizer) } } @@ -75,7 +271,8 @@ public final class ModelContainer: Sendable { public func perform( values: V, _ action: @Sendable (any LanguageModel, Tokenizer, V) throws -> sending R ) async rethrows -> sending R { - try await context.read { + check() + return try await context.read { try action($0.model, $0.tokenizer, values) } } @@ -88,9 +285,10 @@ public final class ModelContainer: Sendable { /// - 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( - _ action: @Sendable (ModelContext) async throws -> sending R + _ action: @Sendable (TrainableModelContext) async throws -> sending R ) async rethrows -> sending R { - try await context.read { + check() + return try await context.read { try await action($0) } } @@ -99,9 +297,10 @@ public final class ModelContainer: Sendable { /// Callers _must_ eval any `MLXArray` before returning as /// `MLXArray` is not `Sendable`. public func perform( - values: V, _ action: @Sendable (ModelContext, V) async throws -> R + values: V, _ action: @Sendable (TrainableModelContext, V) async throws -> R ) async rethrows -> sending R { - try await context.read { + check() + return try await context.read { try await action($0, values) } } @@ -110,8 +309,10 @@ public final class ModelContainer: Sendable { /// Callers _must_ eval any `MLXArray` before returning as /// `MLXArray` is not `Sendable`. public func perform( - nonSendable values: consuming V, _ action: @Sendable (ModelContext, V) async throws -> R + nonSendable values: consuming V, + _ action: @Sendable (TrainableModelContext, V) async throws -> R ) async rethrows -> sending R { + check() let values = SendableBox(values) return try await context.read { try await action($0, values.consume()) @@ -120,8 +321,9 @@ public final class ModelContainer: Sendable { /// Update the owned `ModelContext`. /// - Parameter action: update action - public func update(_ action: @Sendable (inout ModelContext) -> Void) async { - await context.update { + public func update(_ action: @Sendable (inout TrainableModelContext) -> Void) async { + check() + return await context.update { action(&$0) } } @@ -131,14 +333,16 @@ public final class ModelContainer: Sendable { /// The resolved local model directory for the loaded container. public var modelDirectory: URL { get async throws { - try (await configuration).modelDirectory + check() + return try (await configuration).modelDirectory } } /// The resolved local tokenizer directory for the loaded container. public var tokenizerDirectory: URL { get async throws { - try (await configuration).tokenizerDirectory + check() + return try (await configuration).tokenizerDirectory } } @@ -152,6 +356,7 @@ public final class ModelContainer: Sendable { /// - Note: The `sending` keyword indicates the return value is transferred (not shared), /// allowing non-Sendable types like `LMInput` to safely cross isolation boundaries. public func prepare(input: consuming sending UserInput) async throws -> sending LMInput { + check() let processor = await self.processor return try await processor.prepare(input: input) } @@ -186,6 +391,26 @@ public final class ModelContainer: Sendable { parameters: GenerateParameters, wiredMemoryTicket: WiredMemoryTicket? = nil ) async throws -> AsyncStream { + // handle a model that has been materialized + let materializedStream: AsyncStream? = try lock.withLock { + switch _state { + case .editable: + return nil + case .materialized(let context): + return try MLXLMCommon.generate( + input: input, + parameters: parameters, + context: context, + wiredMemoryTicket: wiredMemoryTicket + ) + } + } + + if let materializedStream { + return materializedStream + } + + // else, generate using the non-materialized model let input = SendableBox(input) // Note: this is only visiting the model exclusively @@ -210,6 +435,7 @@ public final class ModelContainer: Sendable { /// - Parameter tokenIds: Array of token IDs /// - Returns: Decoded string public func decode(tokenIds: [Int]) async -> String { + check() let tokenizer = await self.tokenizer return tokenizer.decode(tokenIds: tokenIds) } @@ -224,6 +450,7 @@ public final class ModelContainer: Sendable { /// - Parameter text: Text to encode /// - Returns: Array of token IDs public func encode(_ text: String) async -> [Int] { + check() let tokenizer = await self.tokenizer return tokenizer.encode(text: text) } @@ -234,6 +461,7 @@ public final class ModelContainer: Sendable { /// - Returns: Array of token IDs @available(*, deprecated, message: "Use applyChatTemplate directly on tokenizer") public func applyChatTemplate(messages: [[String: String]]) async throws -> [Int] { + check() let tokenizer = await self.tokenizer return try tokenizer.applyChatTemplate(messages: messages) } diff --git a/Libraries/MLXLMCommon/ModelConversion.swift b/Libraries/MLXLMCommon/ModelConversion.swift index 4c1d532e2e..732f4ae2c1 100644 --- a/Libraries/MLXLMCommon/ModelConversion.swift +++ b/Libraries/MLXLMCommon/ModelConversion.swift @@ -180,7 +180,7 @@ public enum ModelConversionError: LocalizedError, Equatable { public func convert( modelDirectory: URL, tokenizerDirectory: URL? = nil, - model: BaseLanguageModel, + model: any TrainableLanguageModel, to outputDirectory: URL, options: ModelConversionOptions = .init(), progressHandler: @Sendable (ModelConversionProgress) -> Void = { _ in }, @@ -285,7 +285,7 @@ package func removeExistingModelWeights(in outputDirectory: URL) throws { public func convert( modelDirectory: URL, tokenizerDirectory: URL? = nil, - model: BaseLanguageModel, + model: any TrainableLanguageModel, to outputDirectory: URL, bits: Int? = nil, groupSize: Int? = nil, @@ -553,7 +553,7 @@ private func removeModelConversionWeights(in outputDirectory: URL) throws { } private func quantizeForModelConversion( - model: BaseLanguageModel, + model: any TrainableLanguageModel, options: ModelConversionOptions ) -> ModelConversionQuantizationResult { var layerQuantization = [String: ModelConversionQuantizationDecision]() diff --git a/Libraries/MLXLMCommon/ModelFactory.swift b/Libraries/MLXLMCommon/ModelFactory.swift index f131e2bbe7..61160cf20b 100644 --- a/Libraries/MLXLMCommon/ModelFactory.swift +++ b/Libraries/MLXLMCommon/ModelFactory.swift @@ -1,6 +1,7 @@ // Copyright © 2024 Apple Inc. import Foundation +import MLXNN /// File patterns required to resolve a tokenizer without downloading model weights. package let tokenizerDownloadPatterns = ["*.json", "*.jinja"] @@ -60,26 +61,80 @@ public protocol ModelConfigurationValidating { func validateModelConfiguration() throws } +/// Protocol for generic ``ModelContext``. +/// +/// This should be used for functions that can take either a ``ModelContext`` or a +/// ``TrainableModelContext`` -- they use the base ``LanguageModel`` +/// protocol for inference. +/// +/// This should be strictly for parameter types and not a return value. +public protocol ModelContextProviding { + var configuration: ModelConfiguration { get } + var languageModel: any LanguageModel { get } + var processor: any UserInputProcessor { get } + var tokenizer: Tokenizer { get } +} + /// Context of types that work together to provide a ``LanguageModel``. /// -/// A ``ModelContext`` is created by ``GenericModelFactory/load(from:using:configuration:useLatest:progressHandler:)``. +/// A ``ModelContext`` is `Sendable` and is created by ``loadModel(from:using:configuration:useLatest:progressHandler:)`` +/// or ``GenericModelFactory/load(from:using:configuration:useLatest:progressHandler:)``. /// This contains the following: /// /// - ``ModelConfiguration``: identifier for the model -/// - ``LanguageModel``: the model itself, see ``generate(input:cache:parameters:context:wiredMemoryTicket:tools:)`` +/// - ``LanguageModel``: the model itself (wrapped in a `MaterializedModule`), see ``generate(input:cache:parameters:context:wiredMemoryTicket:tools:)`` /// - ``UserInputProcessor``: can convert ``UserInput`` into ``LMInput`` /// - `Tokenizer` -- the tokenizer used by ``UserInputProcessor`` /// -/// See also ``GenericModelFactory/loadContainer(from:using:configuration:useLatest:progressHandler:)`` and +/// See also the deprecated ``GenericModelFactory/loadContainer(from:using:configuration:useLatest:progressHandler:)`` and /// ``ModelContainer``. -public struct ModelContext { +public struct ModelContext: Sendable, ModelContextProviding { + public var configuration: ModelConfiguration + public var model: any LanguageModel & Sendable + public var processor: any UserInputProcessor + public var tokenizer: Tokenizer + + public var languageModel: any LanguageModel { model } + + public init( + configuration: ModelConfiguration, model: some TrainableLanguageModel, + processor: any UserInputProcessor, tokenizer: any Tokenizer + ) { + self.configuration = configuration + self.model = MaterializedModule(model) + self.processor = processor + self.tokenizer = tokenizer + } + + public init(_ context: consuming TrainableModelContext) { + self.configuration = context.configuration + func makeModel(_ m: consuming T) -> any LanguageModel & Sendable + { + MaterializedModule(m) + } + self.model = makeModel(context.model) + self.processor = context.processor + self.tokenizer = context.tokenizer + } +} + +/// A version of ``ModelContext`` that holds a ``TrainableLanguageModel``. +/// +/// This context contains the same properties as a `ModelContext` but the `model` is +/// mutable and thus the context is _not_ `Sendable`. +/// +/// Produced by ``loadTrainable(from:using:configuration:useLatest:progressHandler:)`` or the +/// equivalent methods on `LLMModelFactory` and `VLMModelFactory`. +public struct TrainableModelContext: ModelContextProviding { public var configuration: ModelConfiguration - public var model: any LanguageModel + public var model: any TrainableLanguageModel public var processor: any UserInputProcessor public var tokenizer: Tokenizer + public var languageModel: any LanguageModel { model } + public init( - configuration: ModelConfiguration, model: any LanguageModel, + configuration: ModelConfiguration, model: some TrainableLanguageModel, processor: any UserInputProcessor, tokenizer: any Tokenizer ) { self.configuration = configuration @@ -103,26 +158,20 @@ public struct ModelContext { /// - ``loadModelContainer(from:using:configuration:useLatest:progressHandler:)`` /// /// or variants. -public protocol GenericModelFactory: Sendable { +public protocol GenericModelFactory: Sendable { - associatedtype ContextType - associatedtype ContainerType: Sendable + associatedtype ContextType: Sendable var modelRegistry: AbstractModelRegistry { get } /// load level load of a ``ResolvedModelConfiguration`` (urls) into a - /// ``ContextType``. This is typically `struct` that holds the values - /// needed to run inference in the model and is _not_ `Sendable`. + /// ``ContextType``. This is typically a `Sendable` `struct` that holds the + /// values needed to run inference in the model (for ``ModelContext`` the + /// model is wrapped in a `MaterializedModule`). func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader ) async throws -> ContextType - - /// Wrap a ``ContextType`` in a ``ContainerType``. - /// - /// The `ContainerType` is a `Sendable` container for managing the model contained - /// in the `ContextType`. - func _wrap(_ context: ContextType) -> ContainerType } extension GenericModelFactory { @@ -169,22 +218,6 @@ extension GenericModelFactory { return try await _load(configuration: resolved, tokenizerLoader: tokenizerLoader) } - /// Load a model from a ``Downloader`` and ``ModelConfiguration``, - /// producing a ``ModelContainer``. - public func loadContainer( - from downloader: any Downloader, - using tokenizerLoader: any TokenizerLoader, - configuration: ModelConfiguration, - useLatest: Bool = false, - progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } - ) async throws -> ContainerType { - let resolved = try await resolve( - configuration: configuration, from: downloader, - useLatest: useLatest, progressHandler: progressHandler) - let context = try await _load(configuration: resolved, tokenizerLoader: tokenizerLoader) - return _wrap(context) - } - /// Load a model from a local directory, producing a ``ModelContext``. /// /// No downloader is needed — the model and tokenizer are loaded from @@ -197,28 +230,73 @@ extension GenericModelFactory { configuration: .init(directory: directory), tokenizerLoader: tokenizerLoader) } - /// Load a model from a local directory, producing a ``ModelContainer``. - public func loadContainer( - from directory: URL, - using tokenizerLoader: any TokenizerLoader - ) async throws -> ContainerType { - let context = try await _load( - configuration: .init(directory: directory), tokenizerLoader: tokenizerLoader) - return _wrap(context) - } +} +public protocol TrainableModelContextLoader { + + func loadTrainable( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool, + progressHandler: @Sendable @escaping (Progress) -> Void + ) async throws -> sending TrainableModelContext } -extension GenericModelFactory where ContextType == ModelContext, ContainerType == ModelContainer { +extension TrainableModelContextLoader { + + public func loadTrainable( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> sending TrainableModelContext { + try await loadTrainable( + from: downloader, using: tokenizerLoader, configuration: configuration, + useLatest: useLatest, progressHandler: progressHandler) + } - public func _wrap(_ context: ModelContext) -> ModelContainer { - .init(context: context) + /// Load a model from a ``Downloader`` and ``ModelConfiguration``, + /// producing a ``ModelContainer``. + /// + /// Note: `ModelContext` is now `Sendable` and is preferred over `ModelContainer`. + @available(*, deprecated, message: "use load instead") + public func loadContainer( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> ModelContainer { + let trainableContext = try await loadTrainable( + from: downloader, + using: tokenizerLoader, + configuration: configuration, + useLatest: useLatest, progressHandler: progressHandler) + return ModelContainer(context: trainableContext) } + /// Load a model from a local directory, producing a ``ModelContainer``. + /// + /// Note: `ModelContext` is now `Sendable` and is preferred over `ModelContainer`. + @available(*, deprecated, message: "use load instead") + public func loadContainer( + from directory: URL, + using tokenizerLoader: any TokenizerLoader + ) async throws -> ModelContainer { + let trainableContext = try await loadTrainable( + from: LocalDownloader(url: directory), + using: tokenizerLoader, + configuration: .init(directory: directory), + useLatest: false, progressHandler: { _ in }) + return ModelContainer(context: trainableContext) + } } /// For backward compatibility: `ModelFactory` refers to an LLM/VLM model factory. -public typealias ModelFactory = GenericModelFactory +public typealias ModelFactory = GenericModelFactory + & TrainableModelContextLoader /// Resolve a ``ModelConfiguration`` into a ``ResolvedModelConfiguration`` by /// downloading remote sources via a ``Downloader``. @@ -302,6 +380,7 @@ public func loadModel( /// - useLatest: when true, always checks the provider for the latest version /// - progressHandler: optional callback for progress /// - Returns: a ``ModelContainer`` +@available(*, deprecated, message: "use loadModel instead") public func loadModelContainer( from downloader: any Downloader, using tokenizerLoader: any TokenizerLoader, @@ -358,6 +437,7 @@ public func loadModel( /// - useLatest: when true, always checks the provider for the latest version /// - progressHandler: optional callback for progress /// - Returns: a ``ModelContainer`` +@available(*, deprecated, message: "use loadModel instead") public func loadModelContainer( from downloader: any Downloader, using tokenizerLoader: any TokenizerLoader, @@ -376,8 +456,8 @@ public func loadModelContainer( /// Load a model from a local directory of configuration and weights. /// -/// Returns a ``ModelContext`` holding the model and tokenizer without -/// an `actor` providing an isolation context. +/// Returns a ``ModelContext`` holding the model and tokenizer +/// in a Sendable context. /// /// - Parameters: /// - directory: directory of configuration and weights @@ -392,6 +472,55 @@ public func loadModel( } } +/// Load a model from a local directory of configuration and weights. +/// +/// Returns a ``TrainableModelContext`` holding the model and tokenizer +/// in a non-Sendable context (suitable for training). +/// +/// - Parameters: +/// - directory: directory of configuration and weights +/// - tokenizerLoader: the ``TokenizerLoader`` to use for loading the tokenizer +/// - Returns: a ``TrainableModelContext`` +public func loadTrainable( + from directory: URL, + using tokenizerLoader: any TokenizerLoader +) async throws -> sending TrainableModelContext { + try await load { + try await $0.loadTrainable( + from: LocalDownloader(url: directory), + using: tokenizerLoader, + configuration: .init(directory: directory)) + } +} + +/// Load a model given a model identifier, downloading via a ``Downloader``. +/// +/// Returns a ``TrainableModelContext`` holding the model and tokenizer +/// in a non-Sendable context (suitable for training). +/// +/// - Parameters: +/// - downloader: the ``Downloader`` to use for fetching remote resources +/// - tokenizerLoader: the ``TokenizerLoader`` to use for loading the tokenizer +/// - id: model identifier, e.g "mlx-community/Qwen3-4B-4bit" +/// - revision: revision to download (defaults to "main") +/// - useLatest: when true, always checks the provider for the latest version +/// - progressHandler: optional callback for progress +/// - Returns: a ``TrainableModelContext`` +public func loadTrainable( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } +) async throws -> sending TrainableModelContext { + try await load { + try await $0.loadTrainable( + from: downloader, using: tokenizerLoader, + configuration: configuration, + useLatest: useLatest, progressHandler: progressHandler) + } +} + /// Load a model from a local directory of configuration and weights. /// /// Returns a ``ModelContainer`` holding a ``ModelContext`` @@ -401,6 +530,7 @@ public func loadModel( /// - directory: directory of configuration and weights /// - tokenizerLoader: the ``TokenizerLoader`` to use for loading the tokenizer /// - Returns: a ``ModelContainer`` +@available(*, deprecated, message: "use loadModel instead") public func loadModelContainer( from directory: URL, using tokenizerLoader: any TokenizerLoader @@ -457,7 +587,7 @@ private func load(loader: (any ModelFactory) async throws -> sending R) async /// ## See Also /// - ``ModelFactoryRegistry`` public protocol ModelFactoryTrampoline { - static func modelFactory() -> (any GenericModelFactory)? + static func modelFactory() -> (any ModelFactory)? } /// Registry of ``ModelFactory`` trampolines. diff --git a/Libraries/MLXLMCommon/Module+Extensions.swift b/Libraries/MLXLMCommon/Module+Extensions.swift index 885dd27c71..a153732c5a 100644 --- a/Libraries/MLXLMCommon/Module+Extensions.swift +++ b/Libraries/MLXLMCommon/Module+Extensions.swift @@ -5,20 +5,8 @@ import MLXNN extension Module { /// Compute the number of parameters in a possibly quantized model + @available(*, deprecated, message: "use parameterCount (per module)") public func numParameters() -> Int { - return leafModules().flattenedValues().map { - mod -> Int in - if let qlin = mod as? QuantizedLinear { - return qlin.scales.size * qlin.groupSize - } else if let qemb = mod as? QuantizedEmbedding { - return qemb.scales.size * qemb.groupSize - } else { - return mod.parameters().flattenedValues().reduce( - 0, - { - $0 + $1.size - }) - } - }.reduce(0, +) + parameterCount } } diff --git a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift index ccf4d31659..edc8c216e8 100644 --- a/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift +++ b/Libraries/MLXLMCommon/ParoQuant/ParoQuantLoader.swift @@ -331,7 +331,7 @@ private struct ParoQuantInputProcessor: UserInputProcessor { // MARK: - Load Entry Point -/// Load a ParoQuant model from a local directory, returning a ``ModelContainer``. +/// Load a ParoQuant model from a local directory, returning a ``ModelContext``. /// /// Handles AutoAWQ weight conversion, rotation layer patching, and IO layer /// quantization. Rotation parameters (theta, pairs, channel_scales) are kept @@ -342,13 +342,13 @@ private struct ParoQuantInputProcessor: UserInputProcessor { /// - typeRegistry: Registry used to create the underlying model architecture. /// - tokenizerLoader: Loader for tokenizer. /// - toolCallFormat: Optional tool-call format for the model configuration. -/// - Returns: A ``ModelContainer`` ready for inference. -public func loadParoQuantModel( +/// - Returns: A ``ModelContext`` ready for inference. +public func loadParoQuantModel( from directory: URL, typeRegistry: ModelTypeRegistry, tokenizerLoader: any TokenizerLoader, toolCallFormat: ToolCallFormat? = nil -) async throws -> ModelContainer { +) async throws -> ModelContext { // 1. Parse config.json (flatten VLM text_config if present) let configURL = directory.appendingPathComponent("config.json") var configData = try Data(contentsOf: configURL) @@ -492,7 +492,7 @@ public func loadParoQuantModel( configuration: config, model: model, processor: processor, tokenizer: tokenizer ) - return ModelContainer(context: context) + return context } // MARK: - Errors diff --git a/Libraries/MLXLMCommon/ParoQuant/RotateQuantizedLinear.swift b/Libraries/MLXLMCommon/ParoQuant/RotateQuantizedLinear.swift index 591aa04f33..33ed714832 100644 --- a/Libraries/MLXLMCommon/ParoQuant/RotateQuantizedLinear.swift +++ b/Libraries/MLXLMCommon/ParoQuant/RotateQuantizedLinear.swift @@ -84,8 +84,7 @@ private func metalSource( // MARK: - Kernel Cache /// Cached compiled Metal kernels keyed by tile size, guarded by `kernelCacheLock`. -/// Callers are multi-threaded (each `ModelContainer.perform` closure can run on its -/// own task), so the dictionary read-modify-write is serialised. Contention is +/// Callers are multi-threaded, so the dictionary read-modify-write is serialised. Contention is /// practically nil — only two tile sizes (1 and 4) are ever requested, so the lock /// is contended exactly twice per process before steady-state hits. nonisolated(unsafe) private var kernelCache: [Int: MLXFast.MLXFastKernel] = [:] diff --git a/Libraries/MLXLMCommon/README.md b/Libraries/MLXLMCommon/README.md index f505408e51..0399c8a37c 100644 --- a/Libraries/MLXLMCommon/README.md +++ b/Libraries/MLXLMCommon/README.md @@ -36,7 +36,7 @@ import MLXLLM import MLXLMTokenizers let modelDirectory = URL(filePath: "/path/to/model") -let container = try await loadModelContainer( +let context = try await loadModel( from: modelDirectory, using: TokenizersLoader() ) @@ -50,7 +50,7 @@ import MLXLMHuggingFace import MLXLMTokenizers let hub = HubClient(token: "hf_...") -let container = try await loadModelContainer( +let context = try await loadModel( from: hub, using: TokenizersLoader(), id: "mlx-community/Qwen3-4B-4bit" @@ -77,7 +77,7 @@ struct S3Downloader: Downloader { } } -let container = try await loadModelContainer( +let context = try await loadModel( from: S3Downloader(), using: TokenizersLoader(), id: "my-bucket/my-model" @@ -114,7 +114,7 @@ let modelFactory: ModelFactory // e.g. VLMRegistry.paligemma3bMix4488bit let modelConfiguration: ModelConfiguration -let container = try await modelFactory.loadContainer( +let context = try await modelFactory.load( from: HubClient.default, using: TokenizersLoader(), configuration: modelConfiguration @@ -122,15 +122,13 @@ let container = try await modelFactory.loadContainer( // Custom Hub client (token, endpoint, etc.). let customHub = HubClient(token: "hf_...") -let privateContainer = try await modelFactory.loadContainer( +let privateContext = try await modelFactory.load( from: customHub, using: TokenizersLoader(), configuration: modelConfiguration ) ``` -The `container` provides an isolation context (an `actor`) to run inference in the model. - Predefined `ModelConfiguration` instances are provided as static variables on the `ModelRegistry` types or they can be created: @@ -185,18 +183,13 @@ This example shows adding some images and processing instructions -- if model accepts text only then these parts can be omitted. The inference calls are the same. -Assuming you are using a `ModelContainer` (an actor that holds -a `ModelContext`, which is the bundled set of types that implement a -model), the first step is to convert the `UserInput` into the +Assuming you are using a `ModelContext` (which is the bundled set of types +that implement a model), the first step is to convert the `UserInput` into the `LMInput` (LanguageModel Input): ```swift let generateParameters: GenerateParameters -let input: UserInput - -let result = try await modelContainer.perform { [input] context in - let input = try context.processor.prepare(input: input) - +let input = try context.processor.prepare(input: input) ``` Given that `input` we can call `generate()` to produce a stream @@ -205,26 +198,25 @@ to assist in converting a stream of tokens into text and print it. The stream is stopped after we hit a maximum number of tokens: ``` - var detokenizer = NaiveStreamingDetokenizer(tokenizer: context.tokenizer) - - return try MLXLMCommon.generate( - input: input, parameters: generateParameters, context: context - ) { tokens in - - if let last = tokens.last { - detokenizer.append(token: last) - } - - if let new = detokenizer.next() { - print(new, terminator: "") - fflush(stdout) - } - - if tokens.count >= maxTokens { - return .stop - } else { - return .more - } +var detokenizer = NaiveStreamingDetokenizer(tokenizer: context.tokenizer) + +return try MLXLMCommon.generate( + input: input, parameters: generateParameters, context: context +) { tokens in + + if let last = tokens.last { + detokenizer.append(token: last) + } + + if let new = detokenizer.next() { + print(new, terminator: "") + fflush(stdout) + } + + if tokens.count >= maxTokens { + return .stop + } else { + return .more } } ``` diff --git a/Libraries/MLXLMCommon/SpeculativeDecoding.swift b/Libraries/MLXLMCommon/SpeculativeDecoding.swift index 26511e1941..6ccd8228e9 100644 --- a/Libraries/MLXLMCommon/SpeculativeDecoding.swift +++ b/Libraries/MLXLMCommon/SpeculativeDecoding.swift @@ -188,14 +188,10 @@ public struct SpeculativeDecodingMemoryPolicy: Sendable, Hashable { draftModel: any LanguageModel ) -> SpeculativeDecodingMemoryEvaluation { evaluate( - mainModelBytes: Self.modelWeightBytes(mainModel), - draftModelBytes: Self.modelWeightBytes(draftModel) + mainModelBytes: mainModel.parameterNBytes, + draftModelBytes: draftModel.parameterNBytes ) } - - package static func modelWeightBytes(_ model: any LanguageModel) -> Int { - model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes } - } } public struct SpeculativeDecodingMemoryError: Error, Sendable { diff --git a/Libraries/MLXLMCommon/UserInput.swift b/Libraries/MLXLMCommon/UserInput.swift index c620111716..efd4bb7ac4 100644 --- a/Libraries/MLXLMCommon/UserInput.swift +++ b/Libraries/MLXLMCommon/UserInput.swift @@ -16,13 +16,13 @@ public typealias Message = [String: any Sendable] /// /// A ``UserInputProcessor`` can convert this to ``LMInput``. /// See also ``ModelContext``. -public struct UserInput { +public struct UserInput: Sendable { /// Representation of a prompt or series of messages (conversation). /// /// This may be a single string with a user prompt or a series of back /// and forth responses representing a conversation. - public enum Prompt: CustomStringConvertible { + public enum Prompt: CustomStringConvertible, Sendable { /// A single string case text(String) @@ -44,7 +44,7 @@ public struct UserInput { } } - public struct VideoFrame { + public struct VideoFrame: Sendable { public let image: Image public let timeStamp: CMTime @@ -76,7 +76,7 @@ public struct UserInput { } /// Representation of a video resource. - public enum Video { + public enum Video: Sendable { #if canImport(AVFoundation) case avAsset(AVAsset) #endif @@ -105,12 +105,12 @@ public struct UserInput { } /// Representation of an image resource. - public enum Image { + public enum Image: Sendable { #if canImport(CoreImage) case ciImage(CIImage) #endif case url(URL) - case array(MLXArray) + case array(MaterializedArray) #if canImport(CoreImage) public func asCIImage() throws -> CIImage { @@ -130,7 +130,7 @@ public struct UserInput { "array must have 3 dimensions: \(array.ndim)") } - var array = array + var array: MLXArray = array // convert to 0 .. 255 if array.max().item(Float.self) <= 1.0 { @@ -173,9 +173,9 @@ public struct UserInput { } /// Representation of an audio resource. - public enum Audio { + public enum Audio: Sendable { case url(URL) - case array(MLXArray) + case array(MaterializedArray) // See also UserInput+Audio } diff --git a/Libraries/MLXLMCommon/Utilities/SerialAccessContainer.swift b/Libraries/MLXLMCommon/Utilities/SerialAccessContainer.swift index b6c591b97b..32650c3a58 100644 --- a/Libraries/MLXLMCommon/Utilities/SerialAccessContainer.swift +++ b/Libraries/MLXLMCommon/Utilities/SerialAccessContainer.swift @@ -89,17 +89,6 @@ package final class SerialAccessContainer: @unchecked Sendable { /// ``` /// /// Note that the parameters are `consuming`. -/// -/// Here is an example where ``UserInput`` is consumed and passed to an async block and ``LMInput`` -/// is produced and handed back: -/// -/// ```swift -/// public func prepare(input: consuming sending UserInput) async throws -> sending LMInput { -/// let input = SendableBox(input) -/// return try await context.read { -/// SendableBox(try await $0.processor.prepare(input: input.consume())) -/// }.consume() -/// } /// ``` package final class SendableBox: @unchecked Sendable { private var value: T? diff --git a/Libraries/MLXLMCommon/WiredMemoryUtils.swift b/Libraries/MLXLMCommon/WiredMemoryUtils.swift index 987f3f25c3..9bb28ddd53 100644 --- a/Libraries/MLXLMCommon/WiredMemoryUtils.swift +++ b/Libraries/MLXLMCommon/WiredMemoryUtils.swift @@ -143,7 +143,7 @@ public enum WiredMemoryUtils { seedText: String = " hello", resetPeakMemory: Bool = true ) async throws -> WiredMemoryMeasurement { - let weights = context.model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes } + let weights = context.model.parameterNBytes let input = makeTokenInput( count: tokenCount, @@ -193,7 +193,7 @@ public enum WiredMemoryUtils { parameters: GenerateParameters, resetPeakMemory: Bool = true ) async throws -> WiredMemoryMeasurement { - let weights = context.model.parameters().flattened().reduce(0) { $0 + $1.1.nbytes } + let weights = context.model.parameterNBytes let startActive = Memory.activeMemory if resetPeakMemory { diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 205dcb24b9..90bfc0b458 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -86,7 +86,7 @@ private func create( public enum VLMTypeRegistry { /// Shared instance with default model types. - public static let shared: ModelTypeRegistry = .init(creators: [ + public static let shared: ModelTypeRegistry = .init(creators: [ "paligemma": create(PaliGemmaConfiguration.self, PaliGemma.init), "qwen2_vl": create(Qwen2VLConfiguration.self, Qwen2VL.init), "qwen2_5_vl": create(Qwen25VLConfiguration.self, Qwen25VL.init), @@ -301,16 +301,16 @@ public typealias ModelRegistry = VLMRegistry /// is required. /// /// ```swift -/// let modelContainer = try await VLMModelFactory.shared.loadContainer( +/// let modelContainer = try await VLMModelFactory.shared.load( /// configuration: VLMRegistry.paligemma3bMix4488bit) /// ``` -public final class VLMModelFactory: GenericModelFactory { +public final class VLMModelFactory: GenericModelFactory, TrainableModelContextLoader { public typealias ContextType = ModelContext - public typealias ContainerType = ModelContainer public init( - typeRegistry: ModelTypeRegistry, processorRegistry: ProcessorTypeRegistry, + typeRegistry: ModelTypeRegistry, + processorRegistry: ProcessorTypeRegistry, modelRegistry: AbstractModelRegistry ) { self.typeRegistry = typeRegistry @@ -324,7 +324,7 @@ public final class VLMModelFactory: GenericModelFactory { modelRegistry: VLMRegistry.shared) /// registry of model type, e.g. configuration value `paligemma` -> configuration and init methods - public let typeRegistry: ModelTypeRegistry + public let typeRegistry: ModelTypeRegistry /// registry of input processor type, e.g. configuration value `PaliGemmaProcessor` -> configuration and init methods public let processorRegistry: ProcessorTypeRegistry @@ -332,10 +332,40 @@ public final class VLMModelFactory: GenericModelFactory { /// registry of model id to configuration, e.g. `mlx-community/paligemma-3b-mix-448-8bit` public let modelRegistry: AbstractModelRegistry + /// Load a model from a ``Downloader`` and ``ModelConfiguration``, + /// producing a ``TrainableModelContext``. + /// + /// Use this when the model needs to be mutated -- e.g. for training or + /// applying adapters (LoRA). The model inside a ``ModelContext`` is + /// materialized and sealed and cannot be modified; convert a trainable + /// context to an inference ``ModelContext`` via `ModelContext(_:)` when done. + public func loadTrainable( + from downloader: any Downloader, + using tokenizerLoader: any TokenizerLoader, + configuration: ModelConfiguration, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> sending TrainableModelContext { + let resolved = try await resolve( + configuration: configuration, from: downloader, + useLatest: useLatest, progressHandler: progressHandler) + return try await _loadTrainable(configuration: resolved, tokenizerLoader: tokenizerLoader) + } + public func _load( configuration: ResolvedModelConfiguration, tokenizerLoader: any TokenizerLoader - ) async throws -> sending ModelContext { + ) async throws -> ModelContext { + let trainable = try await _loadTrainable( + configuration: configuration, tokenizerLoader: tokenizerLoader) + return ModelContext(trainable) + } + + /// internal load of a TrainableModelContext that can be converted into a ModelContext + private func _loadTrainable( + configuration: ResolvedModelConfiguration, + tokenizerLoader: any TokenizerLoader + ) async throws -> TrainableModelContext { let modelDirectory = configuration.modelDirectory // Load config.json once and decode for both base config and model-specific config @@ -355,7 +385,7 @@ public final class VLMModelFactory: GenericModelFactory { configurationURL.lastPathComponent, configuration.name, error) } - let model: LanguageModel + let model: any TrainableLanguageModel do { model = try await typeRegistry.createModel( configuration: configData, modelType: baseConfig.modelType) diff --git a/README.md b/README.md index 668349ea21..a22821b9c4 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ import MLXHuggingFace import HuggingFace import Tokenizers -let model = try await #huggingFaceLoadModelContainer( +let model = try await #huggingFaceLoadModel( configuration: LLMRegistry.gemma3_1B_qat_4bit ) diff --git a/skills/mlx-swift-lm/SKILL.md b/skills/mlx-swift-lm/SKILL.md index 395afa3187..bd40f8a4ce 100644 --- a/skills/mlx-swift-lm/SKILL.md +++ b/skills/mlx-swift-lm/SKILL.md @@ -33,17 +33,21 @@ mlx-swift-lm is a Swift package for running Large Language Models (LLMs) and Vis ### Architecture Overview ``` -MLXLMCommon - Core infra (ModelContainer, ChatSession, Evaluate, KVCache, wired memory helpers) +MLXLMCommon - Core infra (ModelContext, ChatSession, Evaluate, KVCache, wired memory helpers) MLXLLM - Text-only LLM support (Llama, Qwen, Gemma, Phi, DeepSeek, etc.) MLXVLM - Vision-Language Models (Qwen-VL, PaliGemma, Gemma3, etc.) MLXEmbedders - Embedding models and pooling utilities ``` +`ModelContext` (the model + tokenizer + processor bundle) is `Sendable` — its +model is wrapped in a `MaterializedModule` — so you pass it directly across +tasks and actors. `ModelContainer` is deprecated. + ## 2. Key File Reference | Purpose | File Path | |---------|-----------| -| Thread-safe model wrapper | `Libraries/MLXLMCommon/ModelContainer.swift` | +| Sendable model bundle (`ModelContext`) | `Libraries/MLXLMCommon/ModelFactory.swift` | | Simplified chat API | `Libraries/MLXLMCommon/ChatSession.swift` | | Generation & streaming APIs | `Libraries/MLXLMCommon/Evaluate.swift` | | KV cache types | `Libraries/MLXLMCommon/KVCache.swift` | @@ -68,13 +72,13 @@ import MLXLMCommon import MLXLMHuggingFace // from swift-huggingface-mlx import MLXLMTokenizers // from swift-tokenizers-mlx -let modelContainer = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: .init(id: "mlx-community/Qwen3-4B-4bit") ) -let session = ChatSession(modelContainer) +let session = ChatSession(context) let response = try await session.respond(to: "What is Swift?") print(response) @@ -92,13 +96,13 @@ import MLXLMCommon import MLXLMHuggingFace // from swift-huggingface-mlx import MLXLMTokenizers // from swift-tokenizers-mlx -let modelContainer = try await VLMModelFactory.shared.loadContainer( +let context = try await VLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: .init(id: "mlx-community/Qwen2-VL-2B-Instruct-4bit") ) -let session = ChatSession(modelContainer) +let session = ChatSession(context) let image = UserInput.Image.url(imageURL) let response = try await session.respond( @@ -115,20 +119,18 @@ import MLXEmbedders import MLXEmbeddersHuggingFace // from swift-huggingface-mlx import MLXLMTokenizers // from swift-tokenizers-mlx -let container = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: ModelConfiguration(id: "mlx-community/bge-small-en-v1.5-mlx") ) -let embeddings = await container.perform { model, tokenizer, pooler in - let tokens = tokenizer.encode(text: "Hello world") - let input = MLXArray(tokens).expandedDimensions(axis: 0) - let output = model(input) - let pooled = pooler(output, normalize: true) - eval(pooled) - return pooled -} +// EmbedderModelContext is Sendable — use its members directly +let tokens = context.tokenizer.encode(text: "Hello world") +let input = MLXArray(tokens).expandedDimensions(axis: 0) +let output = context.model(input) +let pooled = context.pooling(output, normalize: true) +eval(pooled) ``` ## 4. Primary Workflow: LLM Inference @@ -139,7 +141,7 @@ let embeddings = await container.perform { model, tokenizer, pooler in ```swift let session = ChatSession( - modelContainer, + context, instructions: "You are a helpful assistant", generateParameters: GenerateParameters(maxTokens: 500, temperature: 0.7) ) @@ -150,17 +152,19 @@ let r2 = try await session.respond(to: "And if you multiply that by 3?") await session.clear() ``` -### Streaming with `ModelContainer.generate(...)` +### Streaming with `generate(...)` -For lower-level control, prepare `UserInput` and generate directly: +For lower-level control, prepare `UserInput` and generate directly on the +`ModelContext` (which is `Sendable`, so no container/actor is needed): ```swift let userInput = UserInput(prompt: "Hello") -let lmInput = try await modelContainer.prepare(input: userInput) +let lmInput = try context.processor.prepare(input: userInput) -let stream = try await modelContainer.generate( +let stream = try generate( input: lmInput, - parameters: GenerateParameters() + parameters: GenerateParameters(), + context: context ) for await generation in stream { @@ -207,8 +211,8 @@ let userInput = UserInput( tools: [weatherTool.schema] ) -let lmInput = try await modelContainer.prepare(input: userInput) -let stream = try await modelContainer.generate(input: lmInput, parameters: GenerateParameters()) +let lmInput = try context.processor.prepare(input: userInput) +let stream = try generate(input: lmInput, parameters: GenerateParameters(), context: context) for await generation in stream { switch generation { @@ -251,11 +255,12 @@ let policy = WiredSumPolicy() let ticket = policy.ticket(size: estimatedBytes, kind: .active) let userInput = UserInput(prompt: "Summarize this text") -let lmInput = try await modelContainer.prepare(input: userInput) +let lmInput = try context.processor.prepare(input: userInput) -let stream = try await modelContainer.generate( +let stream = try generate( input: lmInput, parameters: GenerateParameters(), + context: context, wiredMemoryTicket: ticket ) @@ -277,7 +282,7 @@ let history: [Chat.Message] = [ .assistant("Hi there!") ] -let session = ChatSession(modelContainer, history: history) +let session = ChatSession(context, history: history) ``` ## 5. Secondary Workflow: VLM Inference @@ -311,7 +316,7 @@ let response = try await session.respond(to: "Compare these two images", images: ```swift let session = ChatSession( - modelContainer, + context, processing: UserInput.Processing(resize: CGSize(width: 512, height: 512)) ) ``` @@ -322,11 +327,11 @@ let session = ChatSession( ```swift // DO: Prefer ChatSession for multi-turn chat UX -let session = ChatSession(modelContainer) +let session = ChatSession(context) -// DO: Prepare UserInput before container-level generation +// DO: Prepare UserInput before low-level generation let userInput = UserInput(prompt: "Hello") -let lmInput = try await modelContainer.prepare(input: userInput) +let lmInput = try context.processor.prepare(input: userInput) // DO: Use task-handle variants for early-stop scenarios let (stream, task) = generateTask( @@ -342,14 +347,14 @@ await task.value // DO: Use wired tickets when coordinating concurrent workloads let ticket = WiredSumPolicy().ticket(size: estimatedBytes) -let _ = try await modelContainer.generate(input: lmInput, parameters: params, wiredMemoryTicket: ticket) +let _ = try generate(input: lmInput, parameters: params, context: context, wiredMemoryTicket: ticket) ``` ### DON'T ```swift -// DON'T: Skip prepare(input:) before container-level generation. -// ModelContainer.generate expects LMInput, not UserInput. +// DON'T: Skip prepare(input:) before low-level generation. +// generate(...) expects LMInput, not UserInput. // DON'T: Share MLXArray across tasks (not Sendable) let array = MLXArray(...) @@ -364,9 +369,9 @@ for await item in stream { ### Thread Safety -- `ModelContainer` is `Sendable` and thread-safe. +- `ModelContext` is now `Sendable` (its model is a `MaterializedModule`); use it directly across tasks and actors. - `ChatSession` is not thread-safe; use one session per task/flow. -- `MLXArray` is not `Sendable`; keep it inside one isolation domain or use `SendableBox` transfer patterns. +- `MLXArray` is not `Sendable`; keep it inside one isolation domain, or snapshot it with `array.materialized()` (a Sendable `MaterializedArray`) or use `SendableBox` transfer patterns. ### Memory Management @@ -380,7 +385,7 @@ await session.clear() | Reference | When to Use | |-----------|-------------| -| [references/model-container.md](references/model-container.md) | Loading models, ModelContainer API, ModelConfiguration | +| [references/model-container.md](references/model-container.md) | Loading models, the Sendable `ModelContext`, `ModelConfiguration` (deprecated `ModelContainer`) | | [references/generation.md](references/generation.md) | `generate`, `generateTask`, raw token streaming APIs | | [references/wired-memory.md](references/wired-memory.md) | Wired tickets, policies, budgeting, reservations | | [references/kv-cache.md](references/kv-cache.md) | Cache types, memory optimization, cache serialization | diff --git a/skills/mlx-swift-lm/references/concurrency.md b/skills/mlx-swift-lm/references/concurrency.md index 24d4d757d5..6395ea0fba 100644 --- a/skills/mlx-swift-lm/references/concurrency.md +++ b/skills/mlx-swift-lm/references/concurrency.md @@ -2,7 +2,7 @@ ## Overview -mlx-swift-lm uses Swift concurrency with specialized utilities to handle the unique constraints of ML workloads: non-Sendable `MLXArray` types, long-running computations, and thread-safe model access. +mlx-swift-lm uses Swift concurrency with specialized utilities to handle the unique constraints of ML workloads: non-Sendable `MLXArray` types, long-running computations, and thread-safe model access. There is a `MaterializedArray` that is a subclass of MLXArray and it is sendable. `MaterializedModule` can wrap a `Module` and provide Sendable access as well. **File:** `Libraries/MLXLMCommon/Utilities/SerialAccessContainer.swift` @@ -13,7 +13,9 @@ mlx-swift-lm uses Swift concurrency with specialized utilities to handle the uni | `SerialAccessContainer` | Exclusive async access to wrapped state | | `AsyncMutex` | Lock that works with async blocks | | `SendableBox` | Transfer non-Sendable values across isolation | -| `ModelContainer` | Thread-safe model wrapper (uses SerialAccessContainer) | +| `MaterializedArray` | `Sendable` snapshot of an `MLXArray` (immutable, evaluated) | +| `MaterializedModule` | `Sendable` wrapper of a `Module` (materialized, sealed) | +| `ModelContext` / `EmbedderModelContext` | `Sendable` model bundles (model is a `MaterializedModule`) | | `ChatSession` | NOT thread-safe (single task only) | ## SerialAccessContainer @@ -75,29 +77,16 @@ Transfer non-Sendable values across isolation boundaries: ```swift // Problem: LMInput is not Sendable -let input: LMInput = ... +let iterator: IteratorProtocol = ... Task { - use(input) // Compiler error! + use(iterator) // Compiler error! } // Solution: Use SendableBox -let box = SendableBox(input) +let box = SendableBox(iterator) Task { - let input = box.consume() // Transfer ownership - use(input) -} -``` - -### Pattern: Consuming Parameters - -```swift -func processAsync(input: consuming LMInput) async throws -> Result { - let boxed = SendableBox(input) - - return try await container.read { context in - let input = boxed.consume() // Consume inside closure - return try process(input, context: context) - } + let iterator = box.consume() // Transfer ownership + use(iterator) } ``` @@ -109,62 +98,24 @@ let v1 = box.consume() // OK let v2 = box.consume() // fatalError: "value already consumed" ``` -## ModelContainer Thread Safety - -`ModelContainer` uses `SerialAccessContainer` internally: - -```swift -public final class ModelContainer: Sendable { - private let context: SerialAccessContainer - - // Thread-safe access - public func perform( - _ action: @Sendable (ModelContext) async throws -> R - ) async rethrows -> R -} -``` - -### Safe Usage - -```swift -// Multiple tasks can call perform() safely -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) - id: "mlx-community/Qwen3-4B-4bit" -) - -Task { - await container.perform { context in - // Exclusive access to model - } -} - -Task { - await container.perform { context in - // Waits for first task to complete - } -} -``` - ## ChatSession Thread Safety -`ChatSession` is NOT thread-safe. Use from a single task: +`ChatSession` is NOT thread-safe (it is a class and has mutable properties). Use from a single task: ```swift // WRONG: Multiple tasks using same session -let session = ChatSession(container) +let session = ChatSession(context) Task { await session.respond(to: "A") } // Race condition! Task { await session.respond(to: "B") } // CORRECT: Single task per session -let session = ChatSession(container) +let session = ChatSession(context) let r1 = await session.respond(to: "A") let r2 = await session.respond(to: "B") -// Or: Separate sessions per task +// Or: Separate sessions per task (ModelContext is Sendable, so share it freely) Task { - let session = ChatSession(container) // Own session + let session = ChatSession(context) // Own session await session.respond(to: "...") } ``` @@ -271,39 +222,95 @@ task.cancel() // Stream terminates `MLXArray` is NOT `Sendable`. Strategies: -### 1. Eval Before Returning +### 1. Use item() to extract a value: ```swift -await container.perform { context in - let result = context.model(input) - eval(result) // Evaluate before crossing boundary - return result.item(Float.self) // Return primitive -} +let result = context.model(input) +eval(result) // Evaluate before crossing boundary +let value = result.item(Float.self) // Return a primitive (Sendable) ``` -### 2. Use SendableBox for Transfer +### 2. Use MaterializedArray for Transfer ```swift -let box = SendableBox(array) +let snapshot = array.materialized() // MaterializedArray: a Sendable snapshot Task { - let array = box.consume() - // Use array in this task only + // Use snapshot safely across the isolation boundary. + // Operations on it still produce ordinary lazy MLXArray results. + let doubled = snapshot * 2 + eval(doubled) } ``` ### 3. Keep Arrays Within Isolation ```swift -// All array operations in same perform block -await container.perform { context in - let a = model(input1) - let b = model(input2) - let combined = a + b - eval(combined) - return combined.item() -} +// Keep all array operations in the same isolation domain +let a = context.model(input1) +let b = context.model(input2) +let combined = a + b +eval(combined) +let value = combined.item(Float.self) +``` + +## MaterializedArray and MaterializedModule + +These two `@unchecked Sendable` types are what let a `ModelContext` cross +isolation boundaries safely, so you can pass it directly instead of hiding a +model behind a `ModelContainer` actor. + +### MaterializedArray + +A subclass of `MLXArray` that holds a fully-evaluated, immutable snapshot. + +```swift +// Create from an existing array +let snapshot = array.materialized() // or: materialize(array) + +// Usable anywhere an MLXArray is expected +let y = snapshot + 1 // produces an ordinary lazy MLXArray ``` +- It is `Sendable`, so it can be captured by another task/actor. +- It is immutable: attempting to mutate it in place traps. +- Operations on it produce ordinary lazy `MLXArray` results (only the snapshot + itself is materialized). + +### MaterializedModule + +A `Sendable` wrapper around a `Module` (`MaterializedModule`). + +```swift +let sealed = MaterializedModule(module) +``` + +On init it evaluates and materializes all of the module's parameters and then +SEALS the module against mutation: `update`, `apply`, `freeze`, and `train` +all trap. Protocol conformances are added via extensions constrained on +`LayerType` (e.g. `extension MaterializedModule: LanguageModel where LayerType: LanguageModel`), +so a sealed language model is still usable for inference. + +### Why this matters for ModelContext + +`ModelContext` and `EmbedderModelContext` are now `Sendable` because their model +is a `MaterializedModule`. You use them directly across tasks and actors — no +`ModelContainer` actor and no `perform { }` block: + +```swift +let context = try await LLMModelFactory.shared.load( + from: HubClient.default, + using: TokenizersLoader(), + configuration: .init(id: "mlx-community/Qwen3-4B-4bit") +) + +let input = try context.processor.prepare(input: UserInput(prompt: "Hello")) +let stream = try generate(input: input, parameters: .init(), context: context) +``` + +Because the model is sealed, you cannot mutate/train it or call +`context.model.update(parameters:)` (it traps). To modify weights or apply LoRA +adapters, load a mutable `TrainableModelContext` via `loadTrainable(...)` instead. + ## Async Evaluation MLX uses lazy evaluation. Force evaluation at boundaries: diff --git a/skills/mlx-swift-lm/references/embeddings.md b/skills/mlx-swift-lm/references/embeddings.md index bf81529ffc..f909e9d878 100644 --- a/skills/mlx-swift-lm/references/embeddings.md +++ b/skills/mlx-swift-lm/references/embeddings.md @@ -17,7 +17,7 @@ The Embedders library provides text embedding models for semantic search, RAG, c | Type | Purpose | |------|---------| | `EmbeddingModel` | Protocol for embedding models | -| `ModelContainer` | Thread-safe embedding model wrapper | +| `EmbedderModelContext` | `Sendable` model + tokenizer + pooling bundle | | `ModelConfiguration` | Model ID and settings | | `Pooling` | Pooling strategies for embeddings | | `Pooling.Strategy` | mean, cls, first, last, max, none | @@ -51,9 +51,9 @@ The Embedders library provides text embedding models for semantic search, RAG, c import MLXEmbedders let config = ModelConfiguration.bge_small -let container = try await loadModelContainer( - from: HubClient.default, - using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) +let context = try await EmbedderModelFactory.shared.load( + from: HubClient.default, // a Downloader (e.g. HubClient.default), or a directory URL + using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: config ) ``` @@ -62,7 +62,7 @@ let container = try await loadModelContainer( ```swift let config = ModelConfiguration(id: "BAAI/bge-small-en-v1.5") -let container = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: config @@ -72,8 +72,8 @@ let container = try await loadModelContainer( ### From Local Directory ```swift -let container = try await loadModelContainer( - from: localModelURL, +let context = try await EmbedderModelFactory.shared.load( + from: localModelURL, // directory URL using: TokenizersLoader() ) ``` @@ -81,7 +81,7 @@ let container = try await loadModelContainer( ### With Progress Tracking ```swift -let container = try await loadModelContainer( +let context = try await EmbedderModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: config @@ -95,22 +95,19 @@ let container = try await loadModelContainer( ### Basic Usage ```swift -let container: ModelContainer = ... +let context: EmbedderModelContext = ... -let embedding = await container.perform { model, tokenizer, pooler in - // Encode text - let tokens = tokenizer.encode(text: "Hello world") - let input = MLXArray(tokens).expandedDimensions(axis: 0) +// EmbedderModelContext is Sendable — use its members directly +let tokens = context.tokenizer.encode(text: "Hello world") +let input = MLXArray(tokens).expandedDimensions(axis: 0) - // Get model output - let output = model(input) +// Get model output +let output = context.model(input) - // Pool to single vector - let pooled = pooler(output, normalize: true) +// Pool to single vector +let pooled = context.pooling(output, normalize: true) - eval(pooled) - return pooled -} +eval(pooled) ``` ### Batch Embeddings @@ -118,33 +115,30 @@ let embedding = await container.perform { model, tokenizer, pooler in ```swift let texts = ["First text", "Second text", "Third text"] -let embeddings = await container.perform { model, tokenizer, pooler in - // Encode all texts - let tokensList = texts.map { tokenizer.encode(text: $0) } - let maxLen = tokensList.map { $0.count }.max() ?? 0 - - // Pad to same length - var padded = [[Int]]() - var mask = [[Float]]() - for tokens in tokensList { - let padding = Array(repeating: 0, count: maxLen - tokens.count) - padded.append(tokens + padding) - mask.append(Array(repeating: 1.0, count: tokens.count) + - Array(repeating: 0.0, count: padding.count)) - } +// Encode all texts +let tokensList = texts.map { context.tokenizer.encode(text: $0) } +let maxLen = tokensList.map { $0.count }.max() ?? 0 + +// Pad to same length +var padded = [[Int]]() +var mask = [[Float]]() +for tokens in tokensList { + let padding = Array(repeating: 0, count: maxLen - tokens.count) + padded.append(tokens + padding) + mask.append(Array(repeating: 1.0, count: tokens.count) + + Array(repeating: 0.0, count: padding.count)) +} - let input = MLXArray(padded) - let attentionMask = MLXArray(mask) +let input = MLXArray(padded) +let attentionMask = MLXArray(mask) - // Forward pass - let output = model(input, attentionMask: attentionMask) +// Forward pass +let output = context.model(input, attentionMask: attentionMask) - // Pool - let pooled = pooler(output, mask: attentionMask, normalize: true) +// Pool +let pooled = context.pooling(output, mask: attentionMask, normalize: true) - eval(pooled) - return pooled -} +eval(pooled) ``` ## Pooling Strategies diff --git a/skills/mlx-swift-lm/references/lora-adapters.md b/skills/mlx-swift-lm/references/lora-adapters.md index 16116a3def..06f9620490 100644 --- a/skills/mlx-swift-lm/references/lora-adapters.md +++ b/skills/mlx-swift-lm/references/lora-adapters.md @@ -228,42 +228,30 @@ public protocol LoRALayer: Module { ### Inference with Adapter ```swift -// Load base model -let container = try await LLMModelFactory.shared.loadContainer( +// Adapters require a TrainableLanguageModel, so load a TRAINABLE context. +// A materialized ModelContext (from load(...)) is sealed and traps on adapter +// application, so use loadTrainable(...) here. +let context = try await LLMModelFactory.shared.loadTrainable( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: .init(id: "mlx-community/Llama-3.2-3B-Instruct-4bit") ) -// Load and apply adapter -// Note: adapter.load() throws, but container.update() closure is non-throwing +// Load and apply adapter directly to the trainable model let adapter = try LoRAContainer.from(directory: adapterDir) -await container.update { context in - do { - try adapter.load(into: context.model) - } catch { - // Handle adapter loading error - print("Failed to load adapter: \(error)") - } -} +try adapter.load(into: context.model) -// Generate with adapted model -let session = ChatSession(container) +// Convert to an inference (Sendable, materialized) ModelContext to generate +let inferenceContext = ModelContext(context) +let session = ChatSession(inferenceContext) let response = try await session.respond(to: "Hello") ``` ### Fuse for Deployment ```swift -// Fuse adapter for faster inference -// Note: adapter.fuse() throws, handle errors in closure -await container.update { context in - do { - try adapter.fuse(with: context.model) - } catch { - print("Failed to fuse adapter: \(error)") - } -} +// Fuse adapter for faster inference (apply to the trainable model) +try adapter.fuse(with: context.model) // Save fused model weights if desired // Model no longer has LoRA overhead @@ -272,20 +260,12 @@ await container.update { context in ### Hot-swap Adapters ```swift -// Remove current adapter (unload is non-throwing) -await container.update { context in - adapter1.unload(from: context.model) -} +// Remove current adapter from the trainable model +adapter1.unload(from: context.model) // Apply different adapter let adapter2 = try LoRAContainer.from(directory: adapter2Dir) -await container.update { context in - do { - try adapter2.load(into: context.model) - } catch { - print("Failed to load adapter: \(error)") - } -} +try adapter2.load(into: context.model) ``` ## Memory Considerations diff --git a/skills/mlx-swift-lm/references/model-container.md b/skills/mlx-swift-lm/references/model-container.md index 4cba423f14..914424760b 100644 --- a/skills/mlx-swift-lm/references/model-container.md +++ b/skills/mlx-swift-lm/references/model-container.md @@ -1,15 +1,28 @@ -# ModelContainer & Model Loading +# ModelContext & Model Loading ## Overview -`ModelContainer` is the thread-safe wrapper for language models, providing exclusive access to model resources during inference. `ModelConfiguration` describes model identity and settings. Factory classes handle model instantiation from HuggingFace or local directories. +`ModelContext` is the primary bundle for a loaded language model: it holds the +model, tokenizer, processor, and configuration. It is `Sendable` (its `model` is +`any LanguageModel & Sendable`, wrapped in a `MaterializedModule`), so you pass it +directly across tasks and actors — no wrapper or `perform { }` block needed. +`ModelConfiguration` describes model identity and settings. Factory classes handle +model instantiation from HuggingFace or local directories. + +> `MaterializedModule` (a Sendable, sealed wrapper around a `Module`) and +> `MaterializedArray` (a Sendable snapshot of an `MLXArray`) are what make +> `ModelContext` Sendable. See [concurrency.md](concurrency.md) for details. + +`ModelContainer` — the old thread-safe actor wrapper — is **deprecated**; use +`ModelContext` directly. ## Quick Reference | Type | Purpose | File | |------|---------|------| -| `ModelContainer` | Thread-safe model wrapper | `MLXLMCommon/ModelContainer.swift` | -| `ModelContext` | Model + tokenizer + processor bundle | `MLXLMCommon/ModelFactory.swift` | +| `ModelContext` | **Primary** Sendable model + tokenizer + processor bundle | `MLXLMCommon/ModelFactory.swift` | +| `TrainableModelContext` | Mutable model bundle for training / applying adapters | `MLXLMCommon/ModelFactory.swift` | +| `ModelContainer` | Deprecated thread-safe wrapper (use `ModelContext`) | `MLXLMCommon/ModelContainer.swift` | | `ModelConfiguration` | Model ID, EOS tokens, settings | `MLXLMCommon/ModelConfiguration.swift` | | `LLMModelFactory` | Load text-only LLMs | `MLXLLM/LLMModelFactory.swift` | | `VLMModelFactory` | Load vision-language models | `MLXVLM/VLMModelFactory.swift` | @@ -18,28 +31,35 @@ | `LLMTypeRegistry` | Model type -> init mapping | `MLXLLM/LLMModelFactory.swift` | | `VLMTypeRegistry` | VLM type -> init mapping | `MLXVLM/VLMModelFactory.swift` | -## ModelContainer +## ModelContext -### Creating a ModelContainer +### Loading a ModelContext ```swift -// Via factory (recommended) -let container = try await LLMModelFactory.shared.loadContainer( +// Via factory (recommended). The factory method is `load` (NOT `loadModel`). +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: .init(id: "mlx-community/Qwen3-4B-4bit") ) +// Or the free function +let context = try await loadModel( + from: HubClient.default, + using: TokenizersLoader(), + configuration: .init(id: "mlx-community/Qwen3-4B-4bit") +) + // With custom hub (from MLXLMHuggingFace) let hub = HubClient(token: "hf_...") -let container = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: hub, using: TokenizersLoader(), configuration: .init(id: "private/model") ) // With progress tracking -let container = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), configuration: config, @@ -49,72 +69,61 @@ let container = try await LLMModelFactory.shared.loadContainer( ) ``` -### Using ModelContainer - -```swift -// Access configuration (async property) -let config = await container.configuration +You can also load via the `#huggingFaceLoadModel(configuration:)` macro. -// Access tokenizer -let tokenizer = await container.tokenizer +### Using ModelContext -// Access processor -let processor = await container.processor +Because `ModelContext` is `Sendable`, access its members directly — no actor, +no `perform { }`: -// Thread-safe model access via perform() -let result = try await container.perform { context in - // context.model - the LanguageModel - // context.tokenizer - the Tokenizer - // context.processor - the UserInputProcessor - // context.configuration - ModelConfiguration +```swift +let config = context.configuration // ModelConfiguration +let tokenizer = context.tokenizer // Tokenizer +let processor = context.processor // UserInputProcessor +let model = context.model // any LanguageModel & Sendable (sealed) - let tokens = try context.tokenizer.applyChatTemplate(messages: messages) - return tokens -} +let tokens = try context.tokenizer.applyChatTemplate(messages: messages) ``` -### Convenience Methods +### Generation ```swift // Prepare input for generation -let lmInput = try await container.prepare(input: userInput) +let lmInput = try context.processor.prepare(input: userInput) -// Generate with streaming -let stream = try await container.generate(input: lmInput, parameters: params) +// Generate with streaming (from Evaluate.swift) +let stream = try generate(input: lmInput, parameters: params, context: context) // Generate with wired-memory coordination let ticket = WiredSumPolicy().ticket(size: estimatedBytes, kind: .active) -let streamWithTicket = try await container.generate( +let streamWithTicket = try generate( input: lmInput, parameters: params, + context: context, wiredMemoryTicket: ticket ) -// Encode/decode -let tokens = await container.encode("Hello world") -let text = await container.decode(tokens: [1, 2, 3]) - -// Apply chat template -let tokens = try await container.applyChatTemplate(messages: [ - ["role": "user", "content": "Hello"] -]) +// Encode/decode via the tokenizer +let tokens = context.tokenizer.encode(text: "Hello world") +let text = context.tokenizer.decode(tokens: [1, 2, 3]) ``` ### Generation + Wired Memory -`ModelContainer.generate(...)` accepts an optional `wiredMemoryTicket` so callers can -coordinate process-wide wired-memory policy with active inference work. +`generate(...)` accepts an optional `wiredMemoryTicket` so callers can coordinate +process-wide wired-memory policy with active inference work. ```swift let policy = WiredBudgetPolicy(baseBytes: measuredWeightPlusWorkspaceBytes) let inferenceTicket = policy.ticket(size: measuredKVBytes, kind: .active) let userInput = UserInput(prompt: "Summarize this article") -let lmInput = try await container.prepare(input: userInput) +let lmInput = try context.processor.prepare(input: userInput) -let stream = try await container.generate( +let stream = try generate( input: lmInput, parameters: GenerateParameters(maxTokens: 400), + context: context, wiredMemoryTicket: inferenceTicket ) @@ -177,8 +186,8 @@ let config = ModelConfiguration( // Shared instance let factory = LLMModelFactory.shared -// Load container -let container = try await factory.loadContainer( +// Load a Sendable ModelContext +let context = try await factory.load( from: HubClient.default, using: TokenizersLoader(), configuration: LLMRegistry.llama3_2_3B_4bit @@ -196,7 +205,7 @@ let customFactory = LLMModelFactory( ```swift let factory = VLMModelFactory.shared -let container = try await factory.loadContainer( +let context = try await factory.load( from: HubClient.default, using: TokenizersLoader(), configuration: VLMRegistry.qwen2VL2BInstruct4Bit @@ -265,23 +274,77 @@ let modelDir = resolved.modelDirectory // Memory estimate: ~0.5GB per 1B parameters for 4-bit quantized // Example: 7B 4-bit model ~ 3.5GB -// To unload, release all references to ModelContainer -container = nil // Model memory freed +// To unload, release all references to the ModelContext +context = nil // Model memory freed +``` + +## Modifying Model Weights / Adapters + +A `ModelContext`'s model is **materialized and sealed** — you cannot mutate or +train it, and calling `context.model.update(parameters:)` traps. To modify +weights or apply LoRA adapters, load a **mutable** `TrainableModelContext` +instead of a `ModelContext`: + +```swift +// Trainable load returns a MUTABLE TrainableModelContext +let trainable = try await LLMModelFactory.shared.loadTrainable( + from: HubClient.default, + using: TokenizersLoader(), + configuration: .init(id: "mlx-community/Llama-3.2-3B-Instruct-4bit") +) + +// trainable.model is a TrainableLanguageModel — adapters/updates apply directly +let adapter = try LoRAContainer.from(directory: adapterDir) +try adapter.load(into: trainable.model) + +// When done, convert to an inference (Sendable, materialized) ModelContext +let context = ModelContext(trainable) ``` -## Updating Model Parameters +`loadTrainable(...)` is also available as a factory method +(`factory.loadTrainable(...)`) and as the `#huggingFaceLoadTrainableModel(...)` +macro (note the spelling "Trainabled"). `TrainableModelContext` exposes +`configuration`, `model` (`any TrainableLanguageModel`), `processor`, and +`tokenizer`. + +## Deprecated: ModelContainer + +`ModelContainer` (and `EmbedderModelContainer`) is retained only for +back-compat. It is marked `@available(*, deprecated, message: "use ModelContext +instead")`. Because `ModelContext` is now `Sendable`, the actor wrapper is no +longer needed — prefer loading a `ModelContext` directly and using its members. + +Deprecated loading aliases (map to the current API): + +| Deprecated | Use instead | +|------------|-------------| +| `factory.loadContainer(...)` | `factory.load(...)` | +| `loadModelContainer(...)` | `loadModel(...)` | +| `#huggingFaceLoadModelContainer(...)` | `#huggingFaceLoadModel(...)` | + +The deprecated `ModelContainer` API surface: ```swift -// Load adapters into model +// DEPRECATED: async property accessors +let config = await container.configuration +let tokenizer = await container.tokenizer +let processor = await container.processor + +// DEPRECATED: serialized access via perform() +let result = try await container.perform { context in + // context.model, context.tokenizer, context.processor, context.configuration + return try context.tokenizer.applyChatTemplate(messages: messages) +} + +// DEPRECATED: mutation via update() await container.update { context in - try context.model.update( - parameters: adapterParams, - verify: .noUnusedKeys - ) + // ... } -``` -## Deprecated Patterns +// DEPRECATED: convenience generation/encode/decode on the container +let lmInput = try await container.prepare(input: userInput) +let stream = try await container.generate(input: lmInput, parameters: params) +``` ### Old perform() signatures @@ -296,10 +359,13 @@ await container.perform(values: myData) { model, tokenizer, data in // ... } -// USE INSTEAD: perform with ModelContext +// DEPRECATED: perform with ModelContext (the whole ModelContainer is deprecated) await container.perform { context in // context.model, context.tokenizer, context.processor, context.configuration } + +// USE INSTEAD: access the Sendable ModelContext directly +let tokens = try context.tokenizer.applyChatTemplate(messages: messages) ``` ### ModelRegistry typealias diff --git a/skills/mlx-swift-lm/references/model-porting.md b/skills/mlx-swift-lm/references/model-porting.md index 17f57577ae..b050f8bd0d 100644 --- a/skills/mlx-swift-lm/references/model-porting.md +++ b/skills/mlx-swift-lm/references/model-porting.md @@ -364,18 +364,18 @@ If you need custom keys, override `loraDefaultKeys`. ## Testing ```swift -let modelContainer = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: ModelConfiguration(id: "mlx-community/YourModel-4bit") ) let parameters = GenerateParameters() -let lmInput = try await modelContainer.prepare( +let lmInput = try context.processor.prepare( input: UserInput(prompt: "Hello") ) -let stream = try await modelContainer.generate(input: lmInput, parameters: parameters) +let stream = try generate(input: lmInput, parameters: parameters, context: context) for await event in stream { if case let .chunk(text) = event { print(text, terminator: "") diff --git a/skills/mlx-swift-lm/references/supported-models.md b/skills/mlx-swift-lm/references/supported-models.md index 8f7d455929..08f8987118 100644 --- a/skills/mlx-swift-lm/references/supported-models.md +++ b/skills/mlx-swift-lm/references/supported-models.md @@ -149,7 +149,7 @@ Models not in registries can be loaded by ID: ```swift // Any mlx-community model let config = ModelConfiguration(id: "mlx-community/SomeModel-4bit") -let container = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: config diff --git a/skills/mlx-swift-lm/references/tokenizer-chat.md b/skills/mlx-swift-lm/references/tokenizer-chat.md index e85609cb33..17f18ac533 100644 --- a/skills/mlx-swift-lm/references/tokenizer-chat.md +++ b/skills/mlx-swift-lm/references/tokenizer-chat.md @@ -27,12 +27,12 @@ Tokenizers convert text to/from token IDs and apply chat templates for multi-tur Tokenizers are loaded automatically by model factories: ```swift -let container = try await LLMModelFactory.shared.loadContainer( +let context = try await LLMModelFactory.shared.load( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: config ) -let tokenizer = await container.tokenizer +let tokenizer = context.tokenizer ``` ### Manual Loading @@ -185,7 +185,7 @@ let message = Chat.Message( ```swift // ChatSession handles messages internally -let session = ChatSession(container, instructions: "You are helpful") +let session = ChatSession(context, instructions: "You are helpful") let response = try await session.respond(to: "Hello") // Or restore from history @@ -194,7 +194,7 @@ let history: [Chat.Message] = [ .user("Previous question"), .assistant("Previous answer") ] -let session = ChatSession(container, history: history) +let session = ChatSession(context, history: history) ``` ## MessageGenerator diff --git a/skills/mlx-swift-lm/references/training.md b/skills/mlx-swift-lm/references/training.md index 978d22f33d..75c77c20c7 100644 --- a/skills/mlx-swift-lm/references/training.md +++ b/skills/mlx-swift-lm/references/training.md @@ -48,16 +48,18 @@ public struct Parameters: Sendable { import MLXLLM import MLXLMCommon -// Load base model -let container = try await LLMModelFactory.shared.loadContainer( +// Load a TRAINABLE model — training needs a mutable model, so use +// loadTrainable(...) (or factory.loadTrainable(...)), NOT load(...). +// load(...) returns a materialized/sealed ModelContext that traps on mutation. +let context = try await LLMModelFactory.shared.loadTrainable( from: HubClient.default, using: TokenizersLoader(), // TokenizersLoader() from MLXLMTokenizers (swift-tokenizers-mlx) configuration: .init(id: "mlx-community/Llama-3.2-3B-Instruct-4bit") ) -// Extract model and tokenizer for training -let model = await container.perform { $0.model } -let tokenizer = await container.tokenizer +// context is a TrainableModelContext; use its members directly. +let model = context.model // a TrainableLanguageModel (mutable) +let tokenizer = context.tokenizer ``` ### 2. Apply LoRA Layers @@ -345,19 +347,19 @@ import MLXLMCommon import MLXOptimizers func trainAdapter() async throws { - // Load model - let container = try await LLMModelFactory.shared.loadContainer( + // Load a TRAINABLE (mutable) model + let context = try await LLMModelFactory.shared.loadTrainable( from: HubClient.default, using: TokenizersLoader(), configuration: .init(id: "mlx-community/Llama-3.2-1B-Instruct-4bit") ) - let model = await container.perform { SendableBox($0.model) }.consume() - let tokenizer = await container.tokenizer + let model = context.model // TrainableLanguageModel + let tokenizer = context.tokenizer - // Apply LoRA + // Apply LoRA — adapters require a TrainableLanguageModel let adapter = try LoRAContainer.from( - model: model as! LanguageModel, + model: model, configuration: LoRAConfiguration( numLayers: 8, loraParameters: .init(rank: 8) @@ -389,6 +391,10 @@ func trainAdapter() async throws { } print("Training complete!") + + // When done, convert to an inference (Sendable, materialized) ModelContext + let inferenceContext = ModelContext(context) + _ = inferenceContext } ``` diff --git a/skills/mlx-swift-lm/references/wired-memory.md b/skills/mlx-swift-lm/references/wired-memory.md index 72e95af31d..f03c8254a0 100644 --- a/skills/mlx-swift-lm/references/wired-memory.md +++ b/skills/mlx-swift-lm/references/wired-memory.md @@ -13,7 +13,7 @@ Core implementation: - `Libraries/MLXLMCommon/WiredMemoryPolicies.swift` - `Libraries/MLXLMCommon/WiredMemoryUtils.swift` - `Libraries/MLXLMCommon/Evaluate.swift` -- `Libraries/MLXLMCommon/ModelContainer.swift` +- `Libraries/MLXLMCommon/ModelContainer.swift` (deprecated; `ModelContext`, which is `Sendable`, is the current entry point) ## Ticket Flow