Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 41 additions & 27 deletions Libraries/MLXEmbedders/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@ This directory contains ports of popular Encoders / Embedding Models.
## Usage Example

```swift
import Foundation
import MLX
import MLXEmbedders
import MLXEmbeddersHuggingFace
import MLXLMTokenizers

let modelContainer = try await loadModelContainer(
using: TokenizersLoader(),
configuration: .nomic_text_v1_5
import MLXLMCommon
import MLXHuggingFace
import HuggingFace
import Tokenizers

let modelContainer = try await EmbedderModelFactory.shared.loadContainer(
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
configuration: EmbedderRegistry.nomic_text_v1_5
Comment on lines +16 to +19

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Some stragglers using the old API

)
let searchInputs = [
"search_query: Animals in Tropical Climates.",
Expand All @@ -21,10 +26,9 @@ let searchInputs = [
]

// Generate embeddings
let resultEmbeddings = await modelContainer.perform {
(model: EmbeddingModel, tokenizer: Tokenizer, pooling: Pooling) -> [[Float]] in
let resultEmbeddings = await modelContainer.perform { context -> [[Float]] in
let inputs = searchInputs.map {
tokenizer.encode(text: $0, addSpecialTokens: true)
context.tokenizer.encode(text: $0, addSpecialTokens: true)
}
// Pad to longest
let maxLength = inputs.reduce(into: 16) { acc, elem in
Expand All @@ -36,54 +40,64 @@ let resultEmbeddings = await modelContainer.perform {
MLXArray(
elem
+ Array(
repeating: tokenizer.eosTokenId ?? 0,
repeating: context.tokenizer.eosTokenId ?? 0,
count: maxLength - elem.count))
})
let mask = (padded .!= tokenizer.eosTokenId ?? 0)
let mask = (padded .!= context.tokenizer.eosTokenId ?? 0)
let tokenTypes = MLXArray.zeros(like: padded)
let result = pooling(
model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask),
let result = context.pooling(
context.model(padded, positionIds: nil, tokenTypeIds: tokenTypes, attentionMask: mask),
normalize: true, applyLayerNorm: true
)
result.eval()
// MLXArray is not Sendable; convert before returning from perform
return result.map { $0.asArray(Float.self) }
}
```

Load from a local directory:

```swift
import Foundation
import MLXEmbedders
import MLXLMTokenizers
import MLXLMCommon
import MLXHuggingFace
import Tokenizers

let modelDirectory = URL(filePath: "/path/to/embedder")
let modelContainer = try await loadModelContainer(
let modelContainer = try await EmbedderModelFactory.shared.loadContainer(
from: modelDirectory,
using: TokenizersLoader()
using: #huggingFaceTokenizerLoader()
)
```

Use a custom Hugging Face client:

```swift
import Foundation
import MLXEmbedders
import MLXEmbeddersHuggingFace
import MLXLMTokenizers

let hub = HubClient(token: "hf_...")
let modelContainer = try await loadModelContainer(
from: hub,
using: TokenizersLoader(),
configuration: .nomic_text_v1_5
import MLXLMCommon
import MLXHuggingFace
import HuggingFace
import Tokenizers

// HubClient comes from the HuggingFace module; wrap it with #hubDownloader(_:).
let hub = HubClient(host: HubClient.defaultHost, bearerToken: "hf_...")
let modelContainer = try await EmbedderModelFactory.shared.loadContainer(
from: #hubDownloader(hub),
using: #huggingFaceTokenizerLoader(),
configuration: EmbedderRegistry.nomic_text_v1_5
)
```

Use a custom downloader:

```swift
import Foundation
import MLXEmbedders
import MLXLMCommon
import MLXLMTokenizers
import MLXHuggingFace
import Tokenizers

struct S3Downloader: Downloader {
func download(
Expand All @@ -98,9 +112,9 @@ struct S3Downloader: Downloader {
}
}

let modelContainer = try await loadModelContainer(
let modelContainer = try await EmbedderModelFactory.shared.loadContainer(
from: S3Downloader(),
using: TokenizersLoader(),
using: #huggingFaceTokenizerLoader(),
configuration: .init(id: "my-bucket/my-embedder")
)
```
Expand Down
16 changes: 13 additions & 3 deletions Libraries/MLXLLM/Documentation.docc/evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,16 @@ The simplified LLM/VLM API allows you to load a model and evaluate prompts with
For example, this loads a model and asks a question and a follow-on question:

```swift
import Foundation
import MLXLLM
import MLXLMCommon
import MLXHuggingFace // macros: #hubDownloader / #huggingFaceTokenizerLoader
import HuggingFace
import Tokenizers

let model = try await loadModel(
using: TokenizersLoader(),
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
id: "mlx-community/Qwen3-4B-4bit"
)
let session = ChatSession(model)
Expand All @@ -30,7 +38,8 @@ a stream:

```swift
let model = try await loadModel(
using: TokenizersLoader(),
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
id: "mlx-community/Qwen3-4B-4bit"
)
let session = ChatSession(model)
Expand Down Expand Up @@ -137,7 +146,8 @@ to the `ChatSession`:

```swift
let model = try await loadModel(
using: TokenizersLoader(),
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
id: "mlx-community/Qwen2.5-VL-3B-Instruct-4bit"
)
let session = ChatSession(model)
Expand Down
6 changes: 5 additions & 1 deletion Libraries/MLXLLM/Documentation.docc/using-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ let modelFactory: ModelFactory
// e.g. LLMRegistry.llama3_8B_4bit
let modelConfiguration: ModelConfiguration

// e.g. TokenizersLoader() from MLXLMTokenizers
// e.g. #hubDownloader() from MLXHuggingFace
let downloader: any Downloader

// e.g. #huggingFaceTokenizerLoader() from MLXHuggingFace
let tokenizerLoader: any TokenizerLoader

let container = try await modelFactory.loadContainer(
from: downloader,
using: tokenizerLoader,
configuration: modelConfiguration
)
Expand Down
9 changes: 6 additions & 3 deletions Libraries/MLXLLM/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,16 @@ See [llm-tool](../../Tools/llm-tool)
Using LLMs and VLMs from MLXLMCommon is as easy as:

```swift
import Foundation
import MLXLLM
import MLXLMCommon
import MLXLMHuggingFace
import MLXLMTokenizers
import MLXHuggingFace
import HuggingFace
import Tokenizers

let model = try await loadModel(
using: TokenizersLoader(),
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
id: "mlx-community/Qwen3-4B-4bit"
)
let session = ChatSession(model)
Expand Down
26 changes: 9 additions & 17 deletions Libraries/MLXLMCommon/Documentation.docc/porting.md
Original file line number Diff line number Diff line change
Expand Up @@ -600,11 +600,12 @@ Now we can load the model using `llm-tool` or the `LLMEval` example application,
```swift
let modelConfiguration = ModelConfiguration(id: "mlx-community/quantized-gemma-2b-it")

// e.g. TokenizersLoader() from MLXLMTokenizers
// e.g. #huggingFaceTokenizerLoader() from MLXHuggingFace
let tokenizerLoader: any TokenizerLoader

// This will download the weights and load the model
let container = try await MLXModelFactory.shared.loadContainer(
let container = try await LLMModelFactory.shared.loadContainer(
from: #hubDownloader(),
using: tokenizerLoader,
configuration: modelConfiguration
)
Expand All @@ -613,23 +614,14 @@ let container = try await MLXModelFactory.shared.loadContainer(
let generateParameters = GenerateParameters()
let input = UserInput(prompt: "Are cherries sweet?")

// 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
}
// Convert the UserInput into LMInput and run inference
let lmInput = try await container.prepare(input: input)
let stream = try await container.generate(input: lmInput, parameters: generateParameters)
for await generation in stream {
if let chunk = generation.chunk {
print(chunk, terminator: "")
}
}

print(result.output)
```

## Notes
Expand Down
49 changes: 34 additions & 15 deletions Libraries/MLXLMCommon/Documentation.docc/upgrade.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ let model = try await loadModelContainer(configuration: modelConfiguration)
you would convert that like this:

```swift
import Foundation
import MLXLLM
import MLXLMCommon
import MLXHuggingFace
Expand All @@ -59,6 +60,7 @@ If you want a little more control over the downloader or the tokenizer loader, t
expands to this:

```swift
import Foundation
import MLXLLM
import MLXLMCommon
import MLXHuggingFace
Expand Down Expand Up @@ -93,14 +95,17 @@ let model = try await loadModelContainer(configuration: modelConfiguration)
becomes:

```swift
import Foundation
import MLXLLM
import MLXLMCommon

import IntegrationPackage

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is it desired to remove this? I'm a little confused by this example - with the proposed changes, it now shows a generic HuggingFace macro example (identical to the previous section) rather than an IntegrationPackage-specific example.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, when the 3.x mlx-swift-lm was cut we had an integration package to document. We no longer have that (the author stopped supporting it and retracted it).

@aleroot is working on one that could be documented here when he wants to promote it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@davidkoski sure, after the release I will add a PR(probably after #619) with the option for https://github.com/aleroot/swift-tokenizers , on my app is working well already for awhile now. The only thing is that: I do not plan to add any downloader to that library. The library is however fully drop in replacement for the swift-transformers.

import MLXHuggingFace
import HuggingFace
import Tokenizers

let modelConfiguration = LLMRegistry.gemma3_1B_qat_4bit
let model = try await loadModelContainer(
from: HubClient(),
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
configuration: modelConfiguration
)

Expand Down Expand Up @@ -132,6 +137,7 @@ now, using the <doc:#Using-MLXHuggingFace-Macros> (see
packages):

```swift
import Foundation
import MLXEmbedders
import MLXLMCommon
import MLXHuggingFace
Expand All @@ -149,7 +155,7 @@ let loader = #huggingFaceTokenizerLoader()
let container = try await EmbedderModelFactory.shared.loadContainer(
from: hub,
using: loader,
configuration: configuration
configuration: defaultModelConfiguration
)

// use it ...
Expand Down Expand Up @@ -186,7 +192,12 @@ let container = try await loadModelContainer(
)

// After (3.x) – Using HuggingFace integration macros
import Foundation
import MLXLLM
import MLXLMCommon
import MLXHuggingFace
import HuggingFace
import Tokenizers

let model = try await #huggingFaceLoadModelContainer(
configuration: LLMRegistry.gemma3_1B_qat_4bit
Expand All @@ -202,28 +213,36 @@ Loading from a local directory:
let container = try await loadModelContainer(directory: modelDirectory)

// After (3.x)
let container = try await loadModelContainer(from: modelDirectory)
let container = try await loadModelContainer(
from: modelDirectory,
using: #huggingFaceTokenizerLoader()
)
```

Loading with a model factory:

```swift
let container = try await LLMModelFactory.shared.loadContainer(
from: HubClient.default,
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
configuration: modelConfiguration
)
```

Loading an embedder:

```swift
import Foundation
import MLXEmbedders
import MLXLMCommon
import MLXHuggingFace
import HuggingFace
import Tokenizers

let container = try await EmbedderModelFactory.load(
let container = try await EmbedderModelFactory.shared.loadContainer(
from: #hubDownloader(),
using: #huggingFaceTokenizerLoader(),
configuration: .configuration(id: "sentence-transformers/all-MiniLM-L6-v2")
configuration: EmbedderRegistry.minilm_l6
)
```

Expand All @@ -243,11 +262,11 @@ let text = tokenizer.decode(tokenIds: ids)

### Loading API

The `hub` parameter (previously `HubApi`) has been replaced with `from` (any `Downloader` or `URL` for a local directory). Functions that previously defaulted to `defaultHubApi` no longer have a default – callers must either pass a `Downloader` explicitly or use the convenience methods in `MLXLMHuggingFace` / `MLXEmbeddersHuggingFace`, which default to `HubClient.default`.
The `hub` parameter (previously `HubApi`) has been replaced with `from` (any `Downloader` or `URL` for a local directory). Functions that previously defaulted to `defaultHubApi` no longer have a default – callers must pass a `Downloader` explicitly (for example the `#hubDownloader()` macro from `MLXHuggingFace`) or use the `#huggingFaceLoadModelContainer` / `#huggingFaceLoadModel` convenience macros.

For most users who were using the default Hub client, adding `import MLXLMHuggingFace` or `import MLXEmbeddersHuggingFace` and using the convenience overloads is sufficient.
For most users who were using the default Hub client, adding `import MLXHuggingFace` (together with `import HuggingFace` and `import Tokenizers`) and using `#hubDownloader()` + `#huggingFaceTokenizerLoader()` — or the `#huggingFaceLoadModelContainer` macro — is sufficient.

Users who were passing a custom `HubApi` instance should create a `HubClient` instead and pass it as the `from` parameter. `HubClient` conforms to `Downloader` via `MLXLMHuggingFace`.
Users who were passing a custom `HubApi` instance should create a `HuggingFace.HubClient` instead and wrap it with `#hubDownloader(_:)` to pass as the `from` parameter.

### `ModelConfiguration`

Expand All @@ -257,18 +276,18 @@ Users who were passing a custom `HubApi` instance should create a `HubClient` in

### Tokenizer loading

`loadTokenizer(configuration:hub:)` has been removed. Tokenizer loading now uses `AutoTokenizer.from(directory:)` from Swift Tokenizers directly.
`loadTokenizer(configuration:hub:)` has been removed. Tokenizer loading is now done by the `TokenizerLoader` passed to the load functions. `#huggingFaceTokenizerLoader()` uses `AutoTokenizer.from(modelFolder:)` from Swift Transformers.

`replacementTokenizers` (the `TokenizerReplacementRegistry`) has been removed. Use `AutoTokenizer.register(_:for:)` from Swift Tokenizers instead.
`replacementTokenizers` (the `TokenizerReplacementRegistry`) has been removed. To load a tokenizer class that `AutoTokenizer` does not support, pass your own `TokenizerLoader`.

### `defaultHubApi`

The `defaultHubApi` global has been removed. Hugging Face Hub access is now provided by `HubClient.default` from the `HuggingFace` module.
The `defaultHubApi` global has been removed. Hugging Face Hub access is now provided by the `#hubDownloader()` macro from `MLXHuggingFace`, which wraps a default `HuggingFace.HubClient`.

### Low-level APIs

- `downloadModel(hub:configuration:progressHandler:)` → `Downloader.download(id:revision:matching:useLatest:progressHandler:)`
- `loadTokenizerConfig(configuration:hub:)` → `AutoTokenizer.from(directory:)`
- `loadTokenizerConfig(configuration:hub:)` → `TokenizerLoader.load(from:)`
- `ModelFactory._load(hub:configuration:progressHandler:)` → `_load(configuration: ResolvedModelConfiguration)`
- `ModelFactory._loadContainer`: removed (base `loadContainer` now builds the container from `_load`)

Loading
Loading