Skip to content

Load only the shard the safetensors index maps a key prefix to - #632

Closed
spokvulcan wants to merge 1 commit into
ml-explore:mainfrom
spokvulcan:upstream/indexed-key-prefix-selection
Closed

spokvulcan wants to merge 1 commit into
ml-explore:mainfrom
spokvulcan:upstream/indexed-key-prefix-selection

Conversation

@spokvulcan

Copy link
Copy Markdown
Contributor

Proposed changes

The MTP drafter factory loads with the default file selection, so for a checkpoint that keeps the head in its own shard (model-mtp-head.safetensors, mapped by model.safetensors.index.json) it read and evaluated the whole checkpoint and then dropped every target tensor in sanitize(weights:).

WeightFileSelection.indexedKeyPrefix(prefix) selects only the files the index maps a weight named prefix… to, falling back to automatic when there is no usable index or nothing matches. The MTP factory asks for mtp. unless the configuration sets an explicit selection. Two tests in LoadWeightsTests cover the selection and the fallback.

Qwen3.5-27B 4-bit with its MTP head, measured in the app that embeds this library:

before after
bytes read and evaluated for the head 15.1 GB (every shard) 0.85 GB (the head shard)

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: Written by an AI agent while bisecting load memory, reviewed by me.

`WeightFileSelection.indexedKeyPrefix(prefix)` loads the files that
`model.safetensors.index.json` maps a weight named `prefix…` to, and
falls back to `automatic` when the index maps nothing. The MTP drafter
factory uses it for `mtp.`: the head lives in its own shard beside the
target's, and reading the whole checkpoint materialized every target
tensor its `sanitize` then dropped.

(cherry picked from commit 4bbca60)
spokvulcan added a commit to spokvulcan/tesseract that referenced this pull request Sep 30, 2026
Loading Qwen3.8-27B PARO with its grafted MTP head drove MLX to a 32.5 GB
peak over the 14.2 GB model and pushed the machine into swap on every load.
The PARO release ships one model.safetensors and no index, and the graft
puts the head beside it as model-mtp-head.safetensors, so the drafter's
"read only the mtp.* shard" selection had no index to go by: it fell back to
every model*.safetensors, read the whole 18.8 GB target file, and dropped it
again in sanitize.

The vendor pin moves to a fork commit that, without an index, keeps the
files the automatic selection would read whose safetensors header names an
mtp.* weight, reading only the headers. The head now loads from its own
0.85 GB file: the head adds nothing to the load's 19.0 GB peak (the target
load's own), its load takes 0.16 s instead of 7.0 s, and a whole model load
9.8 s instead of 15.2 s, with no swap growth over two loads. The fork
ledger records the carry; it extends ml-explore/mlx-swift-lm#632.
spokvulcan added a commit to spokvulcan/tesseract that referenced this pull request Sep 30, 2026
…dex (#597)

## Summary

Loading Qwen3.8-27B PARO with its grafted MTP head pushed a 48 GB Mac
into swap on every load: MLX memory peaked at 32.5 GB for a model that
sits at 14.2 GB. The MTP drafter is meant to read only the file that
holds its `mtp.*` tensors, and it finds that file through
`model.safetensors.index.json`. A PARO release ships one
`model.safetensors` and no index, and `scripts/graft_mtp_head.py` puts
the head beside it as `model-mtp-head.safetensors` without writing one.
So the drafter fell back to every `model*.safetensors`, read the whole
18.8 GB target file, and threw it away. The vendor pin moves to a commit
on the fork's `fix/mtp-head-unindexed-checkpoint` branch. When there's
no index, the loader now reads only the headers of the files it would
normally load, and keeps the ones whose header names an `mtp.*` weight.
That extends the fork's existing selection, ml-explore/mlx-swift-lm#632,
and the fork ledger records the carry.

Two loads of the 27B in one process, allocation diagnostics on, MacBook
Pro M3 Max 48 GB:

| | before | after |
|---|---|---|
| MLX peak while the head loads | 32.5 GB | 19.0 GB (the target load's
own peak; the head adds nothing) |
| head load time | 7.0 s | 0.16 s |
| model load time | 15.2 s | 9.8 s |
| swap growth over the two loads | +3.5 GB | none |

Two new vendor tests cover the PARO layout and the fallback;
`LoadWeightsTests` passes 27 of 27. The e2e runner passes on the 27B (34
checks), and every request drafts the same DFlash2 tokens as on main.
Found while checking and not fixed here: once the MTP head actually
drafts on this checkpoint, the app crashes in a fused RMSNorm kernel
(`residual dtypes differ`), on main as well.

## Docs impact

- [ ] New or changed domain term → updated `CONTEXT.md`
- [ ] Structural change (new module, moved seam, renamed file) → updated
`ARCHITECTURE.md`
- [ ] Durable, surprising decision with a real trade-off → added an ADR
in `docs/adr/`
- [x] Test workflow change → updated `docs/testing.md` (the load-memory
notes)
- [ ] No docs impact
@davidkoski

Copy link
Copy Markdown
Member

Take a look at #580 -- that needs a little bit of work per #679 (at the time of this comment, it just merged). I think #580 is the right shape for this, though it is perhaps special purpose right now.

@spokvulcan

Copy link
Copy Markdown
Contributor Author

Closing this as #679 already covers it

@spokvulcan spokvulcan closed this Oct 14, 2026
@spokvulcan
spokvulcan deleted the upstream/indexed-key-prefix-selection branch October 14, 2026 08:57
aleroot added a commit to aleroot/mlx-swift-lm that referenced this pull request Oct 19, 2026
Loading a multimodal checkpoint through LLMModelFactory reads every
tensor, and then the text model's sanitize drops the vision and audio
encoders. The dropped tensors go back to the MLX buffer cache, where
they stay until generation clears it on its first token. The Gemma 4
VLM does the same with the audio encoder it does not run, and Qwen 3.5
targets do it with the MTP head that only the drafter loads.

ml-explore#580 lets a model declare its components, so the loader can skip the
ones that load on first use. This extends it to the components a model
does not have. A model family now declares its components once, as a
CheckpointLayout, and every model of the family returns that layout
from ModelComponentsProviding. The loader handles each declared part in
one of three ways:

- On demand: the model lists the component in onDemandComponents. It
  loads on first use, as before.
- Built in: the model has the part's module. It loads with the model.
- Absent: the model has neither. The loader does not read its tensors.

So model files hold no namespace strings and no per-model exclusion
lists, and a new model of a family behaves correctly by returning the
family's layout:

- Gemma4Checkpoint: Gemma4Model (LLM), Gemma4 and Gemma4Unified (VLM),
  and EmbeddingGemma2, which no longer needs its config-dependent
  component and exclusion lists
- Qwen35CheckpointPolicy: Qwen35Model and Qwen35TextModel (LLM) and
  Qwen35 (VLM). The targets exclude only the MTP head now, through
  excludedCheckpointNamespaces (ml-explore#632).
- MuseGlimmerCheckpoint replaces the inline list in MuseGlimmer

excludedComponents applies only to on-demand components, as its
documentation already said. Excluding .vision on the Gemma 4 VLM, whose
encoder is built in, loads it as before instead of failing.
Preparation still drops these names, so a checkpoint loads into the
same model as before.

Some tensors are still read and then released: sanitize drops a few,
and preparation replaces others. Qwen 3.5 fuses its GatedDeltaNet input
projections after the load, and the 1.3 GB of source projections stayed
in the cache. loadWeights now releases the checkpoint before it
materializes the model, and materializeModelForInference clears the
buffer cache.

Measured on an M4 Pro with a 4k prompt, two alternating runs each. The
first number is the footprint after load, the second is the peak during
prefill:

- gemma-4-e4b-it-4bit LLM: 5.43 -> 4.49 GB, 6.71 -> 6.08 GB
- gemma-4-e4b-it-4bit VLM: 5.44 -> 4.82 GB, 6.76 -> 6.46 GB
- gemma-4-12B-it-qat-OptiQ-4bit (gemma4_unified) LLM: 9.25 -> 9.17 GB,
  11.88 -> 11.80 GB
- Qwen3.5-9B-8bit LLM: 11.93 -> 10.97 GB, 14.04 -> 11.99 GB
- Qwen3.5-9B-8bit VLM, 1k prompt: 11.01 -> 10.92 GB, MLX peak
  10.81 -> 9.57 GB
- Qwen3-14B-4bit (text only): 8.41 -> 8.41 GB, 12.93 -> 12.92 GB
- Muse-Glimmer-30B-4bit VLM, 1k prompt: 15.88 -> 15.83 GB

Greedy outputs are identical, and time to first token and decode speed
are within run-to-run noise.
davidkoski pushed a commit that referenced this pull request Nov 10, 2026
* Skip the checkpoint components a model does not have

Loading a multimodal checkpoint through LLMModelFactory reads every
tensor, and then the text model's sanitize drops the vision and audio
encoders. The dropped tensors go back to the MLX buffer cache, where
they stay until generation clears it on its first token. The Gemma 4
VLM does the same with the audio encoder it does not run, and Qwen 3.5
targets do it with the MTP head that only the drafter loads.

#580 lets a model declare its components, so the loader can skip the
ones that load on first use. This extends it to the components a model
does not have. A model family now declares its components once, as a
CheckpointLayout, and every model of the family returns that layout
from ModelComponentsProviding. The loader handles each declared part in
one of three ways:

- On demand: the model lists the component in onDemandComponents. It
  loads on first use, as before.
- Built in: the model has the part's module. It loads with the model.
- Absent: the model has neither. The loader does not read its tensors.

So model files hold no namespace strings and no per-model exclusion
lists, and a new model of a family behaves correctly by returning the
family's layout:

- Gemma4Checkpoint: Gemma4Model (LLM), Gemma4 and Gemma4Unified (VLM),
  and EmbeddingGemma2, which no longer needs its config-dependent
  component and exclusion lists
- Qwen35CheckpointPolicy: Qwen35Model and Qwen35TextModel (LLM) and
  Qwen35 (VLM). The targets exclude only the MTP head now, through
  excludedCheckpointNamespaces (#632).
- MuseGlimmerCheckpoint replaces the inline list in MuseGlimmer

excludedComponents applies only to on-demand components, as its
documentation already said. Excluding .vision on the Gemma 4 VLM, whose
encoder is built in, loads it as before instead of failing.
Preparation still drops these names, so a checkpoint loads into the
same model as before.

Some tensors are still read and then released: sanitize drops a few,
and preparation replaces others. Qwen 3.5 fuses its GatedDeltaNet input
projections after the load, and the 1.3 GB of source projections stayed
in the cache. loadWeights now releases the checkpoint before it
materializes the model, and materializeModelForInference clears the
buffer cache.

Measured on an M4 Pro with a 4k prompt, two alternating runs each. The
first number is the footprint after load, the second is the peak during
prefill:

- gemma-4-e4b-it-4bit LLM: 5.43 -> 4.49 GB, 6.71 -> 6.08 GB
- gemma-4-e4b-it-4bit VLM: 5.44 -> 4.82 GB, 6.76 -> 6.46 GB
- gemma-4-12B-it-qat-OptiQ-4bit (gemma4_unified) LLM: 9.25 -> 9.17 GB,
  11.88 -> 11.80 GB
- Qwen3.5-9B-8bit LLM: 11.93 -> 10.97 GB, 14.04 -> 11.99 GB
- Qwen3.5-9B-8bit VLM, 1k prompt: 11.01 -> 10.92 GB, MLX peak
  10.81 -> 9.57 GB
- Qwen3-14B-4bit (text only): 8.41 -> 8.41 GB, 12.93 -> 12.92 GB
- Muse-Glimmer-30B-4bit VLM, 1k prompt: 15.88 -> 15.83 GB

Greedy outputs are identical, and time to first token and decode speed
are within run-to-run noise.

* Share checkpoint components as values and warn when excludedComponents cannot skip a built-in component
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