Skip to content

Keep frozen input embeddings in file-backed storage - #708

Open
aleroot wants to merge 14 commits into
ml-explore:mainfrom
aleroot:alessio/file-backed-embeddings
Open

aleroot wants to merge 14 commits into
ml-explore:mainfrom
aleroot:alessio/file-backed-embeddings

Conversation

@aleroot

@aleroot aleroot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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

  • The loader maps eligible tensors straight from the checkpoint. Tables that are not suitably aligned there are copied once, at load time, into an unlinked temporary file.
  • Lookups gather rows on the CPU stream, so the GPU never touches the whole table. Quantized rows are then dequantized on the GPU, as before.
  • Weights, precision and quantization do not change.

Where it applies

  • Apple platforms only. Other platforms keep their current behavior.
  • Input-only, frozen tables in Llama/Mistral, Qwen2, Qwen3, Qwen3 MoE, Qwen3.5 (LLM and VLM), Phi3, PhiMoE and Gemma 4 (LLM and VLM, including the per-layer table). Model factories do not freeze unquantized embeddings, so in a normal load this means quantized tables.
  • Tied output tables, custom embedding classes and unsupported quantization modes keep normal storage.
  • It is on by default. Set ModelConfiguration.embeddingStorage = .resident to keep normal storage.
  • Do not rewrite or truncate the checkpoint files while the model is loaded.

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 of ModelMemory.model held in file-backed tables. model and total still 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.

Model Resident File-backed Saved
Ornith-1.5-9B-OptiQ-4bit 7.25 GB 6.17 GB 1.08 GB / 14.9%
Qwen3.5-9B-4bit 5.20 GB 4.63 GB 0.57 GB / 10.9%

Generated tokens matched across policies. Ornith decoded at about 12.9 tok/s with both.

Limitations

  • When an app sets a wired limit, current MLX wires buffers that wrap caller memory, which reads and pins the whole table. Do not wire user provided buffers mlx#4883 fixes that.
  • Any GPU work on a file-backed table pages all of it in. That is why lookups run on the CPU stream.
  • Copying unaligned tables costs load time and temporary disk space for as long as the model is loaded.

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 of ModelMemory.model held in file-backed tables. model and total still include them, so apps that size wired-memory tickets can subtract them.
  • ModelMemory.paged: the bytes of backed paged 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):

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure:

@aleroot

aleroot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@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.

@aleroot aleroot mentioned this pull request Nov 11, 2026
9 of 19 tasks
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.
@aleroot

aleroot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

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.
@davidkoski

Copy link
Copy Markdown
Member

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.

@aleroot

aleroot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Upgrading to yesterday's https://github.com/ml-explore/mlx/releases/tag/v0.32.5 we would be good to go 🎸

@davidkoski

Copy link
Copy Markdown
Member

Upgrading to yesterday's https://github.com/ml-explore/mlx/releases/tag/v0.32.5 we would be good to go 🎸

ml-explore/mlx-swift#532 :-)

@davidkoski

Copy link
Copy Markdown
Member

It would be nice if MLX's safetensor implementation had this: safetensors/safetensors#148

That would get us in the aligned path more often.

@aleroot

aleroot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point. I will perform some measurements.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sure, I think it is best to move it there as well. During the weekend, I'm going to prepare this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@aleroot

aleroot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

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.
aleroot added a commit to aleroot/mlx-swift-lm that referenced this pull request Dec 6, 2026
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.
@aleroot aleroot mentioned this pull request Dec 6, 2026
5 tasks done
`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.
@aleroot
aleroot requested a review from davidkoski December 6, 2026 08:54
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.
@aleroot
aleroot force-pushed the alessio/file-backed-embeddings branch from 976eede to 3da22db Compare December 6, 2026 12:11
`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.
@aleroot
aleroot force-pushed the alessio/file-backed-embeddings branch from 34ae41f to a229fa9 Compare December 6, 2026 12:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants