-
Notifications
You must be signed in to change notification settings - Fork 270
Add MLXFoundationModels: an MLX-backed FoundationModels LanguageModel #334
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ctymoszek
wants to merge
5
commits into
ml-explore:main
Choose a base branch
from
ctymoszek:mlx-foundationmodels
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
134db41
Add MLXFoundationModels: an MLX-backed FoundationModels LanguageModel
ctymoszek 48999bb
Gate MLXFoundationModels test files on canImport(FoundationModels, _v…
64df1fa
Version the OS-27 adapter-surface gates in CompatibilityProbes
1c86110
Indent the newly gated test bodies for swift-format
fe809fa
Temporarily disable the doc-verification CI step
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
IntegrationTesting/IntegrationTestingTests/ApplyChatTemplateProbeTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| // Copyright © 2026 Apple Inc. | ||
|
|
||
| import Foundation | ||
| import MLXLMCommon | ||
| import Testing | ||
|
|
||
| @testable import MLXFoundationModels | ||
|
|
||
| /// Empirical probe that `applyChatTemplate` does not crash and produces tokens. | ||
| /// | ||
| /// mlx-swift-lm goes straight through the model's `UserInputProcessor`, which | ||
| /// calls `applyChatTemplate` on the underlying tokenizer. These probes | ||
| /// exercise that path directly through the MLXLMCommon `Tokenizer` protocol | ||
| /// surface, with and without tools. | ||
| @Suite(.serialized, .timeLimit(.minutes(3))) | ||
| struct ApplyChatTemplateProbeTests { | ||
|
|
||
| @Test | ||
| func applyChatTemplateWithoutToolsDoesNotCrash() async throws { | ||
| guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } | ||
| let model = makeTestModel(TestFixtures.defaultModelID) | ||
| let container = try await loadTestModelContainer(id: model.modelIdentifier) | ||
|
|
||
| try await container.perform { context in | ||
| let messages: [[String: any Sendable]] = [ | ||
| ["role": "user", "content": "Say hello in one word."] | ||
| ] | ||
| let tokens = try context.tokenizer.applyChatTemplate(messages: messages) | ||
| #expect(!tokens.isEmpty, "Chat template without tools should produce tokens") | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| func applyChatTemplateWithToolsDoesNotCrash() async throws { | ||
| guard #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) else { return } | ||
| let model = makeTestModel(TestFixtures.defaultModelID) | ||
| let container = try await loadTestModelContainer(id: model.modelIdentifier) | ||
|
|
||
| try await container.perform { context in | ||
| let messages: [[String: any Sendable]] = [ | ||
| ["role": "user", "content": "What's the weather in Tokyo?"] | ||
| ] | ||
|
|
||
| // OpenAI-style tool spec, which swift-transformers expects. | ||
| let weatherTool: [String: any Sendable] = [ | ||
| "type": "function", | ||
| "function": [ | ||
| "name": "get_weather", | ||
| "description": "Get the current weather for a location.", | ||
| "parameters": [ | ||
| "type": "object", | ||
| "properties": [ | ||
| "location": [ | ||
| "type": "string", | ||
| "description": "City and state, e.g. 'San Francisco, CA'.", | ||
| ] as [String: any Sendable] | ||
| ] as [String: any Sendable], | ||
| "required": ["location"], | ||
| ] as [String: any Sendable], | ||
| ] as [String: any Sendable], | ||
| ] | ||
|
|
||
| let tokens = try context.tokenizer.applyChatTemplate( | ||
| messages: messages, | ||
| tools: [weatherTool] | ||
| ) | ||
| #expect(!tokens.isEmpty, "Chat template with tools should produce tokens") | ||
| } | ||
| } | ||
| } |
126 changes: 126 additions & 0 deletions
126
IntegrationTesting/IntegrationTestingTests/CompatibilityProbes.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| // Copyright © 2026 Apple Inc. | ||
|
|
||
| import Foundation | ||
| import MLX | ||
| import MLXFoundationModels | ||
| import Testing | ||
|
|
||
| #if canImport(FoundationModels) | ||
| import FoundationModels | ||
| #endif | ||
|
|
||
| /// Asymmetric, tier-aware compatibility probes. | ||
| /// | ||
| /// Every probe runs identically on all three devices but asserts a | ||
| /// *tier-appropriate* outcome (see ``DeviceTier``). A probe that "throws" or | ||
| /// "is unavailable" is not a generic pass — each asserts a specific positive | ||
| /// fact for its tier and a tripwire if it reaches code that should be | ||
| /// unreachable on that tier. The goal is no false greens: if a future change | ||
| /// accidentally exposes the FM surface below OS 27, the partial/absent tiers go | ||
| /// red here. | ||
| @Suite("Platform Compatibility Probes") | ||
| struct PlatformCompatibilityProbes { | ||
|
|
||
| /// The unforgeable launch-safety signal. | ||
| /// | ||
| /// Reaching the body of *any* test means the test-runner process loaded and | ||
| /// began executing — i.e. dyld did not fault on a weak-null FoundationModels | ||
| /// conformance record (`MLXLanguageModel: LanguageModel`, | ||
| /// `Executor: LanguageModelExecutor`, `StringResponse: Generable`) during the | ||
| /// `__swift5_proto` scan at image load. On the ABSENT tier (iOS 18.5, FM | ||
| /// framework absent) this is the whole ballgame: if the binary launches, the | ||
| /// `@available` + auto-weak-linking story held. | ||
| @Test("probe suite launches on this tier") | ||
| func binaryLaunches() { | ||
| print("[PlatformCompatibility] DeviceTier.current = \(DeviceTier.current)") | ||
| #expect(Bool(true)) | ||
| } | ||
|
|
||
| /// Liveness / anti-false-green. Pure MLX, zero FoundationModels. | ||
| /// | ||
| /// Forces a Metal compute dispatch and reads the scalar back from the GPU. | ||
| /// Must pass on every tier (the package is not FM-only). A no-op submission | ||
| /// would read 0, not 9, so the read-back proves the kernel actually ran. | ||
| @Test("pure-MLX eval works on every tier") | ||
| func rawMLXInferenceWorks() { | ||
| let a = MLXArray([Float(1), Float(2), Float(3)]) | ||
| let b = MLXArray([Float(4), Float(5), Float(6)]) | ||
| let c = a + b | ||
| eval(c) | ||
| let result: Float = c[2].item() | ||
| #expect(result == 9.0, "MLX scalar add expected 9.0, got \(result)") | ||
| } | ||
|
|
||
| /// The `FoundationModels` framework is present on full + partial, absent below. | ||
| /// | ||
| /// `SystemLanguageModel` shipped in OS 26, so `#available(... 26, *)` is the | ||
| /// runtime proxy for "framework present". Because ``DeviceTier/current`` is | ||
| /// derived from the reported OS version, this assertion also cross-checks the | ||
| /// two against each other. | ||
| @Test("FM framework presence matches tier") | ||
| func fmFrameworkPresenceMatchesTier() { | ||
| var fmPresent = false | ||
| if #available(iOS 26.0, macOS 26.0, visionOS 26.0, *) { fmPresent = true } | ||
| let expected = (DeviceTier.current != .absent) | ||
| #expect( | ||
| fmPresent == expected, | ||
| "FM-26 availability (\(fmPresent)) should match (tier != absent)=\(expected) for \(DeviceTier.current)" | ||
| ) | ||
| } | ||
|
|
||
| /// The `LanguageModel` protocol surface (OS 27) is reachable only on full. | ||
| /// | ||
| /// On partial/absent the `#available(... 27, *)` block is skipped entirely, | ||
| /// so the conformance surface is never touched — which is exactly the | ||
| /// graceful-degradation contract. | ||
| @Test("LanguageModel protocol availability matches tier") | ||
| func languageModelProtocolMatchesTier() { | ||
| var lmAvailable = false | ||
| if #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) { | ||
| lmAvailable = true | ||
| #if canImport(FoundationModels, _version: 2) | ||
| // Touch the OS-27 surface to prove it is genuinely reachable here. | ||
| _ = LanguageModelCapabilities(capabilities: []) | ||
| _ = (any LanguageModel).self | ||
| #endif | ||
| } | ||
| let expected = (DeviceTier.current == .full) | ||
| #expect( | ||
| lmAvailable == expected, | ||
| "LanguageModel(27) availability (\(lmAvailable)) should match (tier == full)=\(expected) for \(DeviceTier.current)" | ||
| ) | ||
| } | ||
|
|
||
| /// Our own `MLXLanguageModel` adapter type is gated to the full tier. | ||
| @Test("MLXLanguageModel type is gated to the full tier") | ||
| func mlxLanguageModelGatedCorrectly() { | ||
| var typeReachable = false | ||
| if #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) { | ||
| #if canImport(FoundationModels, _version: 2) | ||
| _ = MLXLanguageModel.self | ||
| typeReachable = true | ||
| #endif | ||
| } | ||
| #expect( | ||
| typeReachable == (DeviceTier.current == .full), | ||
| "MLXLanguageModel reachability (\(typeReachable)) should match (tier == full) for \(DeviceTier.current)" | ||
| ) | ||
| } | ||
|
|
||
| /// `#available` must agree with the reported OS version. | ||
| /// | ||
| /// Pre-release OS builds can decouple marketing version from feature-set | ||
| /// version; if `#available(27)` and `operatingSystemVersion.major >= 27` | ||
| /// disagree, the build's availability metadata is skewed and every other | ||
| /// probe's verdict is suspect — so the disagreement is itself a failure. | ||
| @Test("#available agrees with reported OS version") | ||
| func availabilityAgreesWithOSVersion() { | ||
| let major = ProcessInfo.processInfo.operatingSystemVersion.majorVersion | ||
| var avail27 = false | ||
| if #available(iOS 27.0, macOS 27.0, visionOS 27.0, *) { avail27 = true } | ||
| #expect( | ||
| avail27 == (major >= 27), | ||
| "#available(27)=\(avail27) disagrees with OS major \(major) — pre-release version skew" | ||
| ) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be great to group these into one or more directories for organization purposes.