Repository navigation
Conversation
c0a6138 to
5c68d1e
Compare
c15f0fa to
0f63e59
Compare
|
@davidkoski some context on why I built this. On the models I can run today the savings are modest (0.6–1.1 GB on 9B models, about 1.5 GB on gemma-4-e4b). But I have observed a trend recently: models are moving more capacity into lookup tables. An example, [Allosaurus v0.2](https://huggingface.co/OsaurusAI/Allosaurus-v0.2-125B-A6B-JANGHT1.8) has a 53.6 GiB n-gram table, about twice the size of the rest of the model. Tables like that can only run on a Mac if they stay on disk and only the rows used are read, which is what this PR makes the loader do for any model. I would like to have some of your thoughts possibly, because I think this is a big strategic opportunity for this library, even for the iPad ... Thanks. |
Some checkpoints split one very large lookup table by rows into many tensors, such as the 128-shard n-gram table of qwen4_exp. ShardedEmbedding holds the shards as normal embeddings, so a model can declare them input only and each shard maps from the checkpoint like any other table. A lookup takes indices into the whole table. For uniformly quantized shards it gathers packed rows from every shard and dequantizes once; on file-backed shards the gathers stay on the CPU stream.
ModelMemory.model counted file-backed embedding tables as resident weights, although the system reads their pages on use and can reclaim them. Add ModelMemory.fileBacked, the bytes of model held in those tables, so callers can size wired-memory tickets and memory charts. Also log through MLXLogger, like the rest of the libraries since ml-explore#702.
b632c60 to
1d4bdf6
Compare
|
To unlock the full potential this change: ml-explore/mlx#4883 in core mlx project would need to be merged as well. |
No model in the repo uses it yet. It will return in a separate PR together with a model that needs row-sharded lookup tables, so this PR stays scoped to the embedding storage policy.
|
This is really cool -- I love the idea. I do wonder if more of this should be pushed lower in the stack, but I think as long as we keep the API abstract, we can change the implementation over time. Probably most useful and easiest to tweak at the LM level. |
|
Upgrading to yesterday's https://github.com/ml-explore/mlx/releases/tag/v0.32.5 we would be good to go 🎸 |
|
|
It would be nice if MLX's safetensor implementation had this: safetensors/safetensors#148 That would get us in the aligned path more often. |
|
@davidkoski amazing! When everything goes through I am going to try to run Qwen4-35B on the M6 Mac mini. That could run all my experiments 24/7 😅😂 P.S. : Agree 💯on safe tensor |
|
|
||
| package final class FileBackedEmbedding: Embedding { | ||
| package override func callAsFunction(_ x: MLXArray) -> MLXArray { | ||
| weight.take(x, axis: 0, stream: .cpu) |
There was a problem hiding this comment.
This will require cpu/gpu synchronization (correct and per design) which may be a perf hit on fast models and MTP (say Gemma 4 E2B/E4B). I think we should take it as-is and people can try it -- if it is too big a hit on certain models we can switch them from .automatic to .resident in the ModelConfiguration.
There was a problem hiding this comment.
Good point. I will perform some measurements.
There was a problem hiding this comment.
I measured it on an M6 Mac mini: about 0.17 ms per decoded token, whatever the model size, so it does hurt fast models. Reading on the GPU is not an option: a GPU read of the file-backed buffer pages in and wires the whole mapping (I checked with and without a residency set). MLX_METAL_FAST_SYNCH would make the sync cheaper, but mlx-swift doesn't ship its fence kernels yet.
So I changed the default in 84544e8. .automatic now file-backs only when the checkpoint is larger than GPU.maxRecommendedWorkingSetBytes(), so models that fit keep the GPU path and pay nothing. .fileBacked forces it. With this, Qwen4-35B-A3B (#870) runs on a 32 GB Mac at 40–45 tok/s and an 18.3 GB footprint.
| import MLXNN | ||
|
|
||
| #if canImport(Darwin) | ||
| import Cmlx |
There was a problem hiding this comment.
This isn't exported from mlx-swift, but swiftpm seems ok with this anyway 🤷
I wonder if we should move any of this or expose API in mlx-swift? Given that we want the new mlx release it might be best to do a coordinated release here.
As soon as the mlx update PR in mlx-swift goes, I think we can cut a new release there, so it is good timing if this should be moved.
There was a problem hiding this comment.
Sure, I think it is best to move it there as well. During the weekend, I'm going to prepare this PR.
There was a problem hiding this comment.
in the end I just realised there was nothing to move to mlx-swift. Both uses have public equivalents: asData(access: .noCopy) for the data address, and reshaped(value.shape) for a second handle to the same array (reshaping to the same shape returns the array itself). 50e35e8 drops import Cmlx, so this PR no longer needs a coordinated mlx-swift release. Happy to still wait for the new mlx release if you want the other fixes in first.
davidkoski
left a comment
There was a problem hiding this comment.
Change looks great, but see my comments inline:
- potential OOB behavior change
- do we want to wait for mlx-swift to pick up the mlx fixes?
- do we want to move or expose any of the functions here (the Cmlx references)? I worry this may break because Cmlx isn't exported
I won't merge yet, let me know what you think about these.
Sure we can wait new mlx release, no rush. I plan to prepare the PRs for Monday, even #870 will probably be ready for review on Monday. |
File-backed tables must be read on the CPU: when the GPU reads a file-backed buffer, macOS pages in and wires the whole mapping (2 GB of 2 GB in a probe on an M6, with or without a residency set). The CPU read makes each forward pass wait for the GPU and back, a fixed ~0.17 ms per decoded token on an M6 whatever the model size. That is ~3% at 166 tok/s and more on fast models such as Gemma 4 E2B. A CPU read past the table also faults, where a GPU read returns undefined values. - `EmbeddingStoragePolicy.automatic` now resolves per load: `.fileBacked` when the checkpoint files are larger than `GPU.maxRecommendedWorkingSetBytes()`, else `.resident`. - Add `EmbeddingStoragePolicy.fileBacked` to request file-backed storage. - `FileBackedEmbedding` and `FileBackedQuantizedEmbedding` clamp indices on the CPU stream to `[-rows, rows - 1]` (`[0, rows - 1]` for unsigned ids), so negative indices still count from the end as in `take`. - Document the cost and the default in `using.md`. Models that fit keep the original GPU path and pay nothing. Models that do not fit trade the round trip for the memory they need to run at all. `MLX_METAL_FAST_SYNCH` would shorten the round trip, but mlx-swift 0.33 does not ship its fence kernels.
`prepareEmbeddingStorage` swapped the tables with one `update(modules:)` on the model. mlx-swift cannot update an array when its first elements have no entry, so a table under `layers.1` threw `unexpectedStructure` and every table kept normal storage. Qwen4 MoE keeps its 16 n-gram tables (11 GB at 4 bits) under `model.layers.1`. - Swap each table through its direct parent module, and give each changed array all its elements. - Test a table at index 1 of a table array inside a plain `let` layer array.
The PLE n-gram tables are most of a Qwen4 MoE checkpoint: 11 GB of the 31 GB Qwen4-35B-A3B-4bit text model, in 16 tables of 10M rows under `model.layers.1`. A decode step reads one row per table, so these tables are the candidates for file-backed storage (ml-explore#708), which lets the model run on a 32 GB Mac. - Add `Qwen4ExpModelInner.ngramTables`, the tables of every PLE layer. - Test that it returns exactly the PLE tables the module tree holds. The models declare the tables as input-only in ml-explore#708, once both changes are in main.
`CheckpointTensorStorage` and `FileBackedEmbedding` imported `Cmlx`, which mlx-swift does not export, for two things that its public API already does. - Read data addresses with `asData(access: .noCopy)` instead of `mlx_array_data_uint8`. - Take the second handle to a recorded checkpoint array with `reshaped(value.shape)` instead of `mlx_array_new` and `mlx_array_set`. Reshaping to the same shape returns the same array, so the handle shares its buffer. - Test that a recorded source survives an in-place update of the checkpoint array, which is why the second handle exists. No mlx-swift change is needed.
A file-backed row that is not in memory is read from disk on a page fault. All tables read on the one CPU stream, so the faults of a decode step ran one after another. Qwen4-35B-A3B reads 16 n-gram tables per token, which cost ~38 major faults and a ~3 ms GPU gap per token in a Metal System Trace on an M6 Mac mini (32 GB). - Give `FileBackedEmbedding` and `FileBackedQuantizedEmbedding` their own CPU stream. Each stream has its own thread, so the faults of different tables wait for the disk together. On new text, decode goes from 51-53 to 58-59 tok/s and warm prefill from ~197 to ~235 tok/s. With every row in memory, decode is 60.5 tok/s with either layout, so the extra streams cost nothing measurable.
- `EmbeddingStoragePolicy.fileBacked` is now `.backed`, and `ModelMemory.fileBacked` is now `ModelMemory.backed`. - Inkling 2 and Ricursive declare `embed_tokens`. Both always have a separate `lm_head`. DiffusionGemma keeps normal storage, because self-conditioning multiplies by its token table. LFM3 ties its head by default, so it has no table to declare.
976eede to
3da22db
Compare
`ModelMemory.backed` is the size of the file-backed tables, not what is in memory: the system reads their pages on use and can reclaim them later. An app that charts model memory could not tell how much of a table a conversation had read. - Add `ModelMemory.paged`, the bytes of `backed` paged in when measured. `mincore` reports the pages of each table, one byte per page, and each buffer counts once. - Test it on an anonymous mapping, where only written pages are paged in, and after a lookup of every row of a loaded table. These are clean file pages, so they do not count in the process footprint, and another process that reads the same checkpoint shares them.
34ae41f to
a229fa9
Compare
Proposed changes
Nowadays memory is more and more expensive and even buying a Mac Studio is challenging, it seems to be out of stock other than very expensive, so I have started to work on ways to reduce memory footprints of the model to be able to continue to use my current hardware in a decent way. I am starting submitting this work which gave me a good breath room.
File-backed input embeddings
Input embeddings are lookup tables that turn tokens into vectors. Inference reads only the rows for the current tokens, but the whole table normally stays in memory.
This PR keeps eligible tables in file-backed storage, so the system reads only the pages a lookup touches and can reclaim them later. On Apple Silicon this frees unified memory for the rest of the model, the KV cache and other apps.
How it works
Where it applies
ModelConfiguration.embeddingStorage = .residentto keep normal storage.Also in this PR
ShardedEmbedding: a table split by rows into many checkpoint tensors, with each shard file-backed. No model in the repo uses it yet. It is meant for checkpoints with very large n-gram tables. If you prefer, I can move it to a separate PR together with a model that uses it.ModelMemory.fileBacked: the bytes ofModelMemory.modelheld in file-backed tables.modelandtotalstill include them, so apps that size wired-memory tickets can subtract them.Benchmarks
Process physical footprint on an Apple M2, 16 GB, Release builds,
mlx-swift 0.32.3, measured before rebasing onto current main. Both policies used the same weights and token sequences.Generated tokens matched across policies. Ornith decoded at about 12.9 tok/s with both.
Limitations
Why this matters
On today's 9B models the saving is about 0.6 to 1.1 GB. Newer models move more capacity into lookup tables: Allosaurus v0.2 has a 53.6 GiB n-gram table, and DeepSeek-V4.1-Flash has 203 GB of Engram tables, which [Big-MoE-Small-Box](https://github.com/casper-hansen/Big-MoE-Small-Box) also streams from disk. Tables that size can only run on a Mac if they stay on disk and only the rows used are read.
Memory reporting
ModelMemory.backed: the bytes ofModelMemory.modelheld in file-backed tables.modelandtotalstill include them, so apps that size wired-memory tickets can subtract them.ModelMemory.paged: the bytes ofbackedpaged in when measured. These are clean file pages, so the system can reclaim them and they don't count in the process footprint.Notes
Some related MLX changes(neither is required to merge this PR):
as_stridedviews of buffers with more than 2³¹−1 elements. Until it lands, this PR maps only aligned tensors and falls back to normal storage for oversized ones.Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.