Repository navigation
Add MLXFoundationModels: an MLX-backed FoundationModels LanguageModel - #334
Conversation
There was a problem hiding this comment.
It would be great to group these into one or more directories for organization purposes.
There was a problem hiding this comment.
Sure, they're organized now.
There was a problem hiding this comment.
Not really for this file, but anchoring it here in the GuidedGeneration directory. I think it would be nice if we had GuidedGeneration and FoundationModels as two separate libraries. FM could depend on GuidedGeneration.
I think most of the GuidedGeneration code doesn't need to be in MLXLMCommon -- e.g. the Embedders do not need it. That isn't to say it can't go there, but it may make more sense in GuidedGeneration if that is its own library.
A split like this would allow people to opt-in to GuidedGeneration without using any of the FM code. For example on Linux the FM code won't be available at all but the GuidedGeneration piece would be interesting.
There was a problem hiding this comment.
This is complete - thanks @thechriswebb !
| mask.needsApply | ||
| ? UnsafeRawPointer(buffer.baseAddress!).assumingMemoryBound(to: UInt32.self) | ||
| : nil | ||
| return applyMaskAndSample( |
There was a problem hiding this comment.
This reads from logits (via item()) before the asyncEvals below are executed. This may cause a stall where we wait for the current graph to finish before scheduling any new work. Consider the normal eval loop:
// save current value -- this will be returned
let previousY = y
// compute the next state and async eval the next token
let token = step(previous: previousY)
y = .init(tokens: token)
asyncEval(token)
tokenCount += 1
return previousY.tokens.item(Int.self)tokens is still an MLXArray (lazy) at the point where asyncEval is called.
There was a problem hiding this comment.
This won't quite work for guided gen... Chris' caching work already improved the performance of the eval loop, but this sequencing problem is harder to solve.
There was a problem hiding this comment.
It isn't a correctness issue, so IMHO get it in working and then think about how to solve it in a followup (if possible).
| // Wait for GPU to finish (may already be done) | ||
| eval(logits) | ||
| } | ||
| } |
There was a problem hiding this comment.
The normal eval loop has this:
// Apply dynamic cache quantization after each step
maybeQuantizeKVCache(
cache: &cache,
kvBits: kvBits,
kvGroupSize: kvGroupSize,
quantizedKVStart: quantizedKVStart
)Do we need it here inside the generate loop? Not every model uses it, but I think it is important for memory use in models that do.
| let maskArray = bitmaskToMLXArray( | ||
| maskPtr, maskBitCount: vocabSize, totalCount: logitDim) |
There was a problem hiding this comment.
I wonder if this can be cached in the eval loop and passed in?
There was a problem hiding this comment.
Not exactly cached - for guided generation, that won't work, but it's been relocated so this now happens during the forward pass (PR here)
| #if FoundationModelsIntegration | ||
| #if canImport(FoundationModels, _version: 2) | ||
|
|
||
| import Foundation |
There was a problem hiding this comment.
This indentation isn't my favorite. What do you think about doing this in .swift-format?
diff --git a/.swift-format b/.swift-format
index 8892e9f..b9a726a 100644
--- a/.swift-format
+++ b/.swift-format
@@ -4,4 +4,5 @@
"spaces": 4
},
"spacesAroundRangeFormationOperators": true,
+ "indentConditionalCompilationBlocks": false,
}There was a problem hiding this comment.
I'm in favor, that would look nicer - but maybe that change should be separate from this PR since it affects one other file (WiredMemoryPolicies.swift)
There was a problem hiding this comment.
OK, if you want, make a small PR and we can get that in on main, then rebase here.
| let (whitespaceBias, whitespaceTokenIDs) = | ||
| WhitespaceTokenBias.compute( | ||
| tokenizer: context.tokenizer | ||
| ) |
There was a problem hiding this comment.
This is computed per response -- should it be held in the ModelCache?
I think WhitespaceTokenBias and also friends.
There was a problem hiding this comment.
Sure, how about we cache a bias struct like this:
struct TokenizerBias {
let closing: MLXArray
let whitespace: MLXArray
let whitespaceTokenIDs: Set<Int>
}
| /// Prevents race conditions when multiple concurrent requests try to load the model. | ||
| /// Supports caching multiple models by their identifiers. | ||
| private actor ModelCache { | ||
| private var containers: [String: ModelContainer] = [:] |
There was a problem hiding this comment.
A few of these can grow without bound, e.g. in a long running model server. evictAll() / evictAllModels() can remove them but that removes everything. I wonder if this needs finer grained eviction support?
There was a problem hiding this comment.
Yes, that's a good idea. I created
public func evict() so that a given instance can be evicted.
I also changed evictAllModels() to evictAll() to better match evict().
Something to consider in the future: maybe a static evict(modelID:) in case someone wants to do more sophisticated cache management.
There was a problem hiding this comment.
I wonder if model caching is something that MLXLMCommon should provide? Then we can inject the cache? We don't need to solve that here, but something to think about.
| /// Evicts all cached models, tokenizers, and constraint templates. | ||
| /// Frees GPU memory held by model weights. Subsequent requests will | ||
| /// reload models from disk cache. | ||
| static func evictAllModels() async { |
There was a problem hiding this comment.
Should this be public?
I guess similar question for each of these static functions -- should they be public?
There was a problem hiding this comment.
Yes, that's reasonable.
Here's a little inventory after I checked the nearby static funcs:
- eviction-related: yes, should be public
- loadContainer: Sure, I suppose people may want to re-use an existing cache and there's no way to accomplish this currently. There is a wrinkle though: It has this
suppressDownloadingStateparam. This is used by the internalwarmUp()but I'm not sure we want to expose that publicly. Perhaps a public overload is a good compromise? - makeContainerLoader/makeXGTokenizer/makeConstraint: I don't think so
- isDownloadingInCache/lastLoadErrorInCache: This functionality is accessed using the
availabilityAPIs so no need to make these public
There was a problem hiding this comment.
Heads up: loadContainer is now an instance method following this PR
| /// | ||
| /// Thread safety: marked `@unchecked Sendable` because all access is serialized | ||
| /// through `ModelContainer.perform`. | ||
| public struct CompositeLogitProcessor: LogitProcessor, @unchecked Sendable { |
There was a problem hiding this comment.
Should this be @unchecked Sendable? LogitProcessor is not Sendable and the processors can be stateful -- I don't think this is correct.
There was a problem hiding this comment.
You're right - fixed.
|
From a Swift package design perspective, this turns a focused Swift ML library into the owner of a substantial native dependency: a large C++ source snapshot, third-party headers, a custom C shim, unsafe compiler flags, symbol-isolation rules, update tooling, and new public API surface. That is not just implementation detail. It changes the package’s maintenance contract for every downstream user.
If guided generation needs xgrammar, I think it should be isolated behind a separate package/product with a clear ownership and release policy, or consumed as an external dependency. That would let users opt into the native grammar engine deliberately, while keeping the core package’s build surface predictable and Swift-native. I would strongly prefer this PR be split so the FoundationModels adapter can be reviewed independently from the much larger decision of whether this project should own and ship a vendored C++ dependency... As designed, this couples an optional adapter feature to a large native dependency decision that should be made explicitly and independently. |
There is some missing back story -- this is the implementation from this: "WWDC26 Bring an LLM provider to the Foundation Models framework" The goal is that the code will go into new libraries that you can opt-in to. If you don't use it then it shouldn't build. It does have the xgrammar dependency (which will be pulled) but also not built if you don't use it. We are experimenting with Traits as well -- they can be used control opt-in / out as well, but I think just picking which libraries link should control what builds. I appreciate your feedback and agree that a separate repository would make this simpler, but we have bureaucratic constraints and cannot easily add new repositories. |
Ah ok, sorry. This is coming from Apple itself 😀. I didn't know 😀 |
|
Xcode 27 exposes image input as a standard Foundation Models capability through .vision and Transcript.Segment.attachment. The current TranscriptConverter skips non-text segments, although MLX already supports UserInput.Image and VLMs such as Qwen3-VL. Is vision support intentionally outside this PR’s scope? If so, would you prefer a focused follow-up PR that maps Foundation Models image attachments into MLX image inputs and adds .vision coverage? |
Not at all outside the scope - this is in flight (PR currently open on my fork, to be merged into this branch shortly). |
| // to an effectively empty library (only MLXDownloadProgress survives): | ||
| // the entire `MLXLanguageModel` / `MLXLanguageModel.Executor` surface | ||
| // requires FoundationModels types that are not available on platforms | ||
| // older than iOS/macOS/visionOS 27.0. Consumers targeting older floors |
There was a problem hiding this comment.
Not a typo, just a silly jargon-y way to say "minimum version". Reworded.
| .define("xgrammar", to: "mlx_xgrammar"), | ||
| .define("picojson", to: "mlx_picojson"), | ||
| // xgrammar throws -- exceptions must stay enabled. | ||
| .unsafeFlags(["-std=c++17", "-fexceptions"]), |
There was a problem hiding this comment.
There is standard package flag that controls which C++ language standard is used (see mlx-swift):
cxxLanguageStandard: .gnucxx20
For exceptions, what if we don't enable this (-fexceptions)? AFAIK mlx (the C++ core) also uses exceptions and compiles fine without this.
|
Just a comment not really related to the changes of this PR but in relation, should a new stable release be cut before merging this ? It is awhile there is no release, maybe before merging this is a good time? |
Yes, that was the plan. This should land with no impact on existing libraries, but you never know. There are still a lot of open PRs, but I think this backlog will take a while -- more updates keep coming in :-) Maybe monday. |
59e4781 to
9f0d489
Compare
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
2143c16 to
0ad3422
Compare
MLXLanguageModel conforms to FoundationModels.LanguageModel, so locally-run MLX models can be used through the FoundationModels framework. It supports chat, tool calling, and guided generation (JSON-schema-constrained sampling via a vendored copy of xgrammar). The adapter is gated behind two default-on SwiftPM traits (FoundationModelsIntegration, GuidedGenerationSupport) and is @available(iOS 27.0, macOS 27.0, visionOS 27.0). Platform floors are unchanged from upstream (.macOS(.v14), .iOS(.v17), .tvOS(.v17), .visionOS(.v1)), so existing consumers and anyone who disables the traits are unaffected.
…ersion: 2) The test target referenced adapter-only symbols (MLXLanguageModel, TranscriptConverter, SchemaConverter, DevelopmentCustomizer, LoadedModelContext, FinalAnswerTool, ...) behind only the FoundationModelsIntegration trait -- or, in a few files, behind no gate at all -- while the source defines those symbols behind both the trait and canImport(FoundationModels, _version: 2). On SDKs predating the v2 FoundationModels (e.g. the macOS 26 SDK) the adapter is correctly compiled out, but the tests still referenced it, failing the build. Mirror the source's gate in the tests so the test surface tracks the adapter surface exactly. Also corrects two files gated on the wrong axis: StopTokenRegressionTests and ToolCallingSchemaTests were under GuidedGenerationSupport, but their DevelopmentCustomizer / SchemaConverter dependencies require the FM + SDK gate.
The two probe bodies that touch the v2-only adapter surface (LanguageModelCapabilities, any LanguageModel, MLXLanguageModel) were behind a bare `canImport(FoundationModels)`, which is true on the 26 SDK (FM 1.x) where those symbols don't yet exist — it would only compile because the target is built against the 27 SDK. Gate them on `canImport(FoundationModels, _version: 2)` so the condition matches the v2 boundary the symbols actually require. The top-of-file `import FoundationModels` stays bare on purpose: it gates on FM *presence* (26+), which is the correct boundary for the absent-tier probe to still compile where FoundationModels does not exist at all.
AvailabilityTests, MLXLanguageModelTests, and TranscriptConverterTests had no top-level #if before; wrapping their bodies in the `FoundationModelsIntegration && canImport(FoundationModels, _version: 2)` gate left the contents at column 0. swift-format's indentConditionalCompilationBlocks (default true) requires content inside a #if to be indented, so the CI lint step reflows them. Indent (and line-wrap the few lines that then exceed 100 cols) to match the #if-indentation style used throughout the source.
MLXFoundationModels is gated on the FoundationModels v2 SDK (canImport(FoundationModels, _version: 2)); its DocC catalog references adapter symbols that don't exist on the SDK the CI runner builds against, so `generate-documentation --warnings-as-errors` fails. Disable the step (if: false) to unblock CI. Re-enable before merge once doc generation builds against the FoundationModels SDK, or verify-docs.sh skips the FM target when v2 is absent.
Adds #huggingFaceLanguageModel, which expands to a complete MLXLanguageModel setup so a caller writes one line instead of ten. The macro fills in the HuggingFace weight-download and tokenizer-loading wiring for you, and reports a clear error when the configuration argument is missing. Also adds a test target that checks the generated code for the common cases.
Declares the macro in the MLXHuggingFace library, with documentation and a usage example. The declaration and the extra dependency it relies on are both compiled in only when FoundationModels support is turned on.
The model-loading closure the macro produced called an async, throwing function without try/await, so any real use of the macro failed to build. The generated code now includes try await. The existing tests only compare the generated text and could not catch this; the on-device test did.
A doc comment linked to a type defined in another module, which broke the documentation build; those references are now plain code formatting. Also adds the Foundation import callers need, since the generated code uses URL and Progress.
The existing tests each set only one of the two optional arguments. This adds a case that sets both, confirming they appear in the right order in the generated code.
…xample Replaces the hand-written MLXLanguageModel initializer in the FoundationModels example with the new one-line macro, so the README matches the convenience API. Also lists the complete set of imports the expansion needs, adding the Foundation and HuggingFace imports the old example was missing.
- remove unnecessary planning files - swift format change
The #huggingFaceLanguageModel macro downloads model weights through the HubClient cache but resolved the on-disk weights location through a different Hugging Face client whose default cache lives elsewhere. As a result the availability checks looked in a directory the downloader never writes to, so a model that had actually been downloaded could still report as not downloaded and a warmup of a present model looked like a fresh download. Synthesize the weights-location closure from the same HubClient cache the downloader uses, matching how mlx-swift-lm pairs them, so downloading and availability agree. Update the illustrative example to the same wiring (which also fixes its missing HuggingFace import, already required by the download step) and the macro's import guidance to match.
The #huggingFaceLanguageModel macro had no invocation anywhere in the project, and its Hugging Face client dependency is linked only by the integration-testing app target, so the code the macro generates was never compiled against that client. A typo in the generated wiring could ship unnoticed. Add a small integration suite that builds a model through the macro. Compiling this suite type-checks the generated download and weights-location wiring against the real client, and the runtime checks confirm the weights-location lookup resolves against the same cache the downloader uses without triggering a network fetch.
The macro and initializer examples in the README and the MLXFoundationModels documentation still resolved the on-disk weights location through a different Hugging Face client than the one that downloads the weights, and the README macro example imported a module the expansion no longer uses. Update these examples to resolve the weights location from the same download cache, matching the fix to the generated code, and drop the now-unused import. The disk-space pre-flight example is left as-is: it estimates download size through a separate metadata call and is a distinct concern from weights-location resolution.
The disk-space pre-flight example estimated download size through a different Hugging Face client than the rest of the availability documentation, which left it as the only example pulling in a second client dependency. Because this is a remote size lookup, the total is the same regardless of client, so switch the example to the same client used for downloading and weights-location resolution. The prose still notes that any client works for this lookup.
The availability documentation pointed at a specific Hugging Face client for the pre-flight download-size estimate, and named modules from the upstream project that do not exist here. Since this type takes its download and location behavior through injected, provider-agnostic closures, describe the estimate in terms of the caller's own downloader or hub client rather than a specific one.
…tion The FoundationModels integration is an optional build trait, and turning it off is meant to compile the module away entirely for consumers on older OS versions. One download-progress helper was slipping through that gate, so disabling the integration still left a single stray type behind even though nothing outside the integration ever drives it. Gate that helper the same way as the rest of the integration so turning the trait off (or building without the newer SDK) now produces a genuinely empty module. Update the trait-matrix test, the package manifest note, and the documentation catalog to describe the empty-module outcome.
…ries The project README had accumulated a large, detailed section about the new Apple Foundation Models support. That level of detail does not belong in the top-level README of a big project, so restore that file to the upstream baseline and layer in only a short, motivating Apple Foundation Models section plus two documentation-list entries that hand readers off to the per-library READMEs. Add a README for the FoundationModels library that covers construction, capabilities, and the build trait, and expand the guided-generation library README with a motivating overview, aligned runnable examples, availability guards, and reciprocal links between the two. The two library READMEs now own the depth while the project README stays a brief pointer.
…DMEs The FoundationModels documentation catalog had drifted into re-explaining what the library READMEs now cover, and Swift Package Index was not configured to build it in the first place. Delete the catalog and let the READMEs be the single source of truth for this library. Drop the README section that pointed at the deleted catalog, and repoint the project README's documentation list for the guided-generation and FoundationModels libraries at their READMEs, since the hosted documentation pages those entries linked to are not built.
…ownload path The integration-test helpers downloaded and located model weights through the old swift-transformers Hugging Face client, while the shipping code (the language-model macro) uses the newer Hugging Face client and its cache. That left the device suite validating a parallel wiring rather than what actually ships: a self-consistent stub that could pass indefinitely even as the real download-and-availability path drifted, which is the same class of mismatch that recently caused a downloaded model to report as not downloaded. Point the helpers at the same client and cache the shipping code uses, so downloading a model and checking whether it exists on disk resolve against one cache and agree. The justifying comments were also stale: they claimed the test target could not use the newer client, but that target does link it (the macro smoke test in the same target already imports it), so the parallel wiring was unnecessary. Drop the now-unused swift-transformers download and tokenizer shims and correct the comments.
… download Nothing exercised a genuine model download end to end: the availability tests use stubbed downloaders, and the macro smoke test is deliberately network-free. This adds an opt-in test that downloads the smallest fixture model for real and asserts its availability moves from not-downloaded to available across the fetch. Forcing a cold download correctly means controlling the downloader's cache, not the on-disk location the availability check reads. The test hands the downloader a throwaway cache in a fresh temporary directory so the fetch cannot be served locally, and points the availability observer at that same cache so the two agree. It also clears the in-process model cache first, so the download actually runs instead of returning an already-loaded instance. Because it hits the network, the suite is opt-in and treats a download failure as a skip rather than a failure.
Switch the MLXFoundationModels README example from the 7B DeepSeek model to the smaller Qwen3 0.6B, and drop the guided-generation capability so the snippet matches a minimal reasoning-only setup. Add the missing MLXLMCommon, HuggingFace, and Tokenizers imports to the top-level README example so it compiles as written.
#huggingFaceLanguageModel forwards capabilities and configurationResolver only when the caller supplies them, so an omitted argument falls through to MLXLanguageModel's initializer default rather than the value in the macro signature. Record that the two must stay in sync.
ColdHubClientFetchTests performs a real network download, so run it only when MLX_RUN_COLD_FETCH is set (TEST_RUNNER_MLX_RUN_COLD_FETCH on device). A default test sweep no longer triggers a fetch.
The #huggingFaceLanguageModel expansion references URL and Foundation.Progress, so the examples need Foundation alongside MLXLMCommon, HuggingFace, and Tokenizers. Add the full set to all three macro examples and sort them so the examples match.
The first run of a schema compiles the grammar and builds its token mask without yielding, which can block for hundreds of milliseconds. Warn, next to the standalone example, to run it off the main actor and to pre-warm the schema.
Tighten wording in the root, MLXFoundationModels, and MLXGuidedGeneration READMEs: correct the root section title, cut marketing phrasing and redundant claims, rebalance the capabilities table, and align terminology.
Upstream added a required state: parameter to LanguageModel.prepare (ml-explore ml-explore#399); the guided loop's initial prefill passes state: nil, matching the canonical TokenIterator.
0ad3422 to
ef31840
Compare
…ml-explore#334) Add MLXFoundationModels: an MLX-backed FoundationModels LanguageModel MLXLanguageModel conforms to FoundationModels.LanguageModel, allowing a local MLX model to work with LanguageModelSession. It is built from a ModelConfiguration and loaded through mlx-swift-lm's existing model factory, so any architecture the package already runs is reachable through FoundationModels. A model's capabilities — .guidedGeneration, .toolCalling, .reasoning, .vision — are declared at construction. A new standalone library, MLXGuidedGeneration, constrains any MLX model's output to a JSON Schema, EBNF grammar, or structural tag by masking token logits at each decoding step. It uses a vendored, namespace-isolated copy of XGrammar (the MLXCXGrammar C++ target), with no FoundationModels dependency. It runs on macOS 14 / iOS 17 and later. The FoundationModels adapter is gated by one default-on SwiftPM trait, FoundationModelsIntegration, and is available on iOS/macOS/visionOS 27.0 (canImport(FoundationModels, _version: 2)). With the trait turned off, or when building against an older SDK, MLXFoundationModels compiles to an empty module and the vendored XGrammar C++ is not built. The package's minimum OS versions are unchanged from upstream. A #huggingFaceLanguageModel macro fills in the HuggingFace download and tokenizer setup. The MLXLanguageModel initializer can be used directly to provide a path to locally stored weights, or a different downloader or tokenizer. Co-authored-by: Cori Tymoszek Park 31750745+ctymoszek@users.noreply.github.com Co-authored-by: Christopher Webb 207731778+thechriswebb@users.noreply.github.com
MLXLanguageModel conforms to FoundationModels.LanguageModel, so locally-run MLX models can be used through the FoundationModels framework. It supports chat, tool calling, and guided generation (JSON-schema-constrained sampling via a vendored copy of xgrammar).
The adapter is gated behind two default-on SwiftPM traits (FoundationModelsIntegration, GuidedGenerationSupport) and is @available(iOS 27.0, macOS 27.0, visionOS 27.0). Platform floors are unchanged from upstream (.macOS(.v14), .iOS(.v17), .tvOS(.v17), .visionOS(.v1)), so existing consumers and anyone who disables the traits are unaffected.
To learn more about the
LanguageModelprotocol this adapter conforms to, see Bring an LLM provider to the Foundation Models framework from WWDC26.Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes