Skip to content

Skip the checkpoint components a model does not have - #711

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/skip-unused-multimodal-weights
Nov 10, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/skip-unused-multimodal-weights

Conversation

@aleroot

@aleroot aleroot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

When LLMModelFactory loads a multimodal checkpoint, it reads every tensor, and then the text model's sanitize drops the vision and audio encoders. The dropped tensors stay in the MLX buffer cache until the first generation clears it. The Gemma 4 VLM does the same with its unused audio encoder, and Qwen 3.5 targets with the MTP head that only the drafter loads.

#580 answers when a component loads: on first use. This PR answers the other half: whether the model has the component at all. If it doesn't, its tensors are never read. The #580 rules still hold: the module tree never changes after load(), and apps configure nothing.

Design

A model family declares its checkpoint components once, in a CheckpointLayout, and every model in the family returns that layout:

package enum Gemma4Checkpoint: CheckpointLayout {
    package static let components: [ModelComponent: [CheckpointComponent]] = [
        .vision: modules("vision_tower", "vision_embedder", "embed_vision"),
        .audio: modules("audio_tower", "embed_audio"),
    ]
}

extension Gemma4Model: ModelComponentsProviding {
    public var modelComponents: [ModelComponent: [CheckpointComponent]] {
        Gemma4Checkpoint.components
    }
}

The layout only says what the checkpoint contains. What the model does with each part comes from the model's own type:

The model holds State The loader
an OnDemandComponent on demand (#580) skips it at load and reads it on first use
the module built in loads it with the model
neither absent never reads its tensors
  • No namespace strings in model files and no per-model exclusion lists. A new model in an existing family returns the family's layout. A new family adds one layout next to its shared code.
  • excludedComponents applies only to on-demand components, as its documentation already said. Excluding .vision on a model whose encoder is built in loads it rather than failing.
  • excludedCheckpointNamespaces is back to its Load only the shard the safetensors index maps a key prefix to #632 role. Qwen 3.5 targets use it only to skip the MTP head.
  • If a model doesn't adopt its family's layout, it behaves as it does today: the tensors are read and then dropped by sanitize. Nothing breaks.

Adopters:

  • Gemma4Checkpoint: Gemma4Model (LLM), Gemma4 and Gemma4Unified (VLM), and EmbeddingGemma2, which loses its config-dependent exclusion lists.
  • Qwen35CheckpointPolicy: Qwen35Model and Qwen35TextModel (LLM), and Qwen35 (VLM).
  • MuseGlimmerCheckpoint replaces the inline list in MuseGlimmer.

Some tensors are still read and then released: sanitize drops a few, and preparation replaces others. For example, Qwen 3.5 fuses its GatedDeltaNet input projections, and that left 1.3 GB of source projections in the cache. Two small loader changes free that memory:

  • loadWeights lets the checkpoint go out of scope before it materializes the model.
  • materializeModelForInference clears the buffer cache after eval.

Benchmarks

Process footprint on an M4 Pro (24 GB), main → this PR. Prompts were 4k tokens with two alternating runs each, except where a row says otherwise.

Model After load 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, one run) 11.01 → 10.92 GB MLX peak 10.81 → 9.57 GB
Muse-Glimmer-30B-4bit, VLM (1k prompt) 15.88 → 15.83 GB unchanged
Qwen3-14B-4bit, text only (control) 8.41 → 8.41 GB 12.93 → 12.92 GB
  • Greedy outputs were identical in every run.
  • Time to first token and decode speed stayed within run-to-run noise.
  • The text-only control didn't change, so models with nothing to skip are unaffected.

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:

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

aleroot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

@davidkoski I need your opinion on this. Is the design ok?

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

Makes sense to me -- I think the design looks good. Thank you!

@davidkoski
davidkoski merged commit c9a9a3d into ml-explore:main Nov 10, 2026
5 checks passed
davidkoski pushed a commit that referenced this pull request Nov 11, 2026
#711 added a warning in ModelComponent.swift through `Logger(subsystem:category:)`.
When its CI ran on Oct 19, MLXLMCommon/Linux/Logger.swift still declared
`typealias Logger = os.Logger` for the whole module, so the file compiled
without importing os. #702 then deleted that alias and moved the libraries to
MLXLogger. #711 merged on Nov 10 with the checks from before #702, so main no
longer builds:

    ModelComponent.swift:28:22: error: cannot find 'Logger' in scope

Use `MLXLogger(label:)`, like every other logger in the libraries since #702.
Importing os would also build, but it fails on Linux and skips the backend that
apps install through `MLXLogger.factory`.
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Nov 14, 2026
Apply the upstream commits 22bdf2c..6352907 (the 15 after c8dabc6) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- 22bdf2c Decode surrogate pairs and the remaining Python escapes (ml-explore#769)
- 0877a36 Fix model weight loading progress (ml-explore#551)
- 0dabaf7 Add production-ready LFM2.5 model support (ml-explore#528)
- 173c163 Add mid-turn steering to ChatSession (ml-explore#608)
- 37424a5 Stop image prompts from running VLM language models in float32 (ml-explore#766)
- c48e55e Add LiquidAI LFM3 model support (ml-explore#750)
- 4ab2679 MLXVLM Qwen35: apply YaRN from rope_parameters on the VLM rotary (ml-explore#761)
- 6e3fe5d Report token log probabilities during speculative decoding (ml-explore#774)
- ec4c966 Batch greedy MTP verification into one GPU readback per round (ml-explore#724)
- c9a9a3d Skip the checkpoint components a model does not have (ml-explore#711)
- a8429d0 Measure the memory of an EmbeddingGemma 2 embedding (ml-explore#787)
- 7b0e790 Parse triple-quoted strings in PythonLiteralParser (ml-explore#786)
- 4c91662 Fix the flaky usage test on the tool-calling path (ml-explore#784)
- d7b94ee Add ModelTypeRegistry.contains(_:configuration:) for shared model types (ml-explore#778)
- 6352907 Use MLXLogger for the model component warning (ml-explore#790)

Conflict resolutions:
- ml-explore#551 load progress: `LoadProgressHandlers` and `progress:` are threaded
  through the fork's async `loadWeights`/`installWeights`. The
  progress-aware `MLXLanguageModel.init(...progress:load:)` and the
  `#huggingFaceLanguageModel` macro also take the fork's
  `speculativeDecoding:`. The fork's tests and benchmark helpers move off the
  now-deprecated download-only loader.
- ml-explore#528 LFM2.5: `RewindableConvolutionCache` lives in ArraysCache.swift
  without upstream's extra `offset +=`, because the fork's `advance` moves
  `offset`. Speculative rewind and verify checks trim it like attention, and
  do not select a Mamba snapshot slot for it. It is also
  `PromptCacheRestorable`, so a saved LFM2 prompt cache restores into the
  model's template. `mtpTargetLayerIdsKey` is added to the fork's MTP
  exchange. `shouldSortExpertRoutes` drives the fork's shared switch
  projection. The fork's in-place verify (`verifiesInPlace`) and its
  greedy-only passthrough string are kept. The upstream tests that expect a
  wrapped sliding window to refuse rewind now expect the fork's behavior:
  the window rewinds the verify write and keeps speculating.
- ml-explore#608 steering: the steering boundary goes into the fork's
  `GenerationLoop.runTokenLoop`, and `Generation.steering` and
  `GenerateStopReason.steered` go into GenerationResults.swift. The fork's
  generation worker keeps its own stream synchronization.
- ml-explore#750 LFM3 is added to HybridRecurrentCacheOffsetTests.
- ml-explore#711: the new test awaits the fork's async `loadWeights`.

Dropped:
- ml-explore#774 (speculative log probabilities): the fork's MTP iterator already
  reports log probabilities by decoding plainly when they are requested.
  Upstream's batched recording in the draft-model iterator does not fit the
  fork's `sampleToken` path, so `ChatSession.ObservationError` stays for
  draft-model speculation.
- ml-explore#724 (batched greedy MTP verification): the fork already batches its
  greedy verify (`verifyDrafts`, MTPGreedyVerificationTests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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