Skip to content

Sync numen/main with ml-explore/mlx-swift-lm main 6352907 (numen-tech/gemma4-qat#1692) - #9

Merged
jeethu merged 72 commits into
numen/mainfrom
sync-1692
Nov 15, 2026
Merged

jeethu merged 72 commits into
numen/mainfrom
sync-1692

Conversation

@jeethu

@jeethu jeethu commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Syncs numen/main with ml-explore/mlx-swift-lm main 6352907 (committed 2026-11-11, still the head on 2026-11-14): 66 upstream commits since the last sync's base 7eb77ef (numen-tech/gemma4-qat#1692). A merge, as #2 (numen-tech/gemma4-qat#283) was. Merge after numen-tech/mlx-swift#31 or before it: this branch's Package.swift names mlx-swift prism, as numen/main does.

Commits on this branch

  1. a909d85 the merge. Conflicts:

  2. 6237a51 GatedDelta: upstream Use the MLXFast gated delta kernel where mlx core supports it ml-explore/mlx-swift-lm#740 sends every layout mlx core fuses (no mask, head dim 128, (Hk, Hv) in its table, which is every Qwen3.5 PARO and Ternary Bonsai 2 layer) to MLXFast.gatedDeltaUpdate. Here that route is opt-in: GatedDeltaFastRoute.isEnabled, a task-local, default false, read when the graph is built. Decode, speculative verify and the rollback replay keep the custom kernel the host's Qwen3.5 and Bonsai goldens were built on, and gatedDeltaReplayState forces the route off even inside an opted-in region. numen-tech/gemma4-qat#1693 measures it for prefill. Upstream's three fast-path tests run with the route on.

  3. 33d9289 the seam's backboneHidden reads anchorCacheOffset (upstream renamed faCacheOffset; for a model with a full-attention layer, which is every model we ship, it returns the same offset).

  4. d531ffb and its revert 29c3e09: a temporary dependency on catchup-1691, undone. Net change zero; they can be squashed away.

  5. 00149dc fixes from an adversarial Codex review of the merge resolutions and the post-merge commits (three medium findings, all taken):

    Tests: testGatedDeltaFastRouteIsOptInAndMultiRowOnly, testRewindableConvolutionCacheTakesNoTurnCheckpoint.

The fork's 42 commits since 7eb77ef

27 non-merge commits and 15 merges.

Commit(s) What Status
b270df2, d9c767a, 8698f60, e6d354a, 872a4ba Qwen3.5 VLM speculative seam, its rebase onto upstream with the prism dependency, the warm-cache M-RoPE fix, textOnlyContinuationState, the ml-explore#614 continuation test kept (seam re-threaded around optional faIdx, anchorCacheOffset)
866e93b Qwen3VL releaseVisionResources() kept (auto-merged with upstream ml-explore#706)
c49aae7 (ml-explore#437), 2f8612f (ml-explore#462) BaseKVCache.ropeOffset overridable, Olmo3 newCache already upstream: their content was in 7eb77ef (empty diff against it); nothing to carry
bb851d8, fb3d548, 080e461 mlx-swift 0.33 compat in CompiledTrace (Sendable box, shims dropped, comment) superseded by upstream ml-explore#720
c620df7 @Sendable on the stateless compile closures in GPTOSS, Gemma4Text, Gemma4Fusions kept (harmless; upstream builds without it)
e7fcc58 CompiledTraceTests ScaleLayer @unchecked Sendable kept
64387ac, 3da810b MambaCache rollback recording and its commit guard (ml-explore#294) kept
d4055cd, 6272116 MambaCache one-step hold (ml-explore#295) and its Codex fix kept
e0a8e89, 8e5843d, 272c53c, 471393a, 8030051 MambaCache turn checkpoint (ml-explore#296) and its Codex fixes kept
3bf4618, 0edd29a Granite compiled single-token decode (ml-explore#206) and its test kept
cc1c237, 62c907d, 6260f02 Qwen3.5 op-cost probe (ml-explore#316) kept
15 merges (5b7bda9, 0d4bbe8, d2fb29f, 103c161, e008d49, 95a8395, 9e3f7e0, 7561920, 9c1a5fa, c941837, 0103657, fcfee94, 0cb0897, c270aaf, d949227) the earlier syncs and fork PR merges history only

Upstream changes on the host's paths, checked

What ran

On 00149dc (macOS, M3 Max, xcodebuild test -scheme mlx-libraries-Package -skipPackagePluginValidation, Xcode 27.0 / Swift 6.4):

Not run here: the host's model suites. numen-tech/gemma4-qat runs them against this head through its Draft PR, which pins 00149dc in Package.resolved under branch: numen/main; its results go on that PR.

aleroot and others added 30 commits October 12, 2026 09:09
…ncoder (ml-explore#580)

On demand model component loading.  MuseGlimmer perf + cache reuse; exact rewind in speculative decoding

MuseGlimmer
- Fuse the decode-path kernels (centered RMS norm, residual-add + norm,
  attention sigmoid gate, MLP silu * up) with compile(shapeless: true).
  The operations, their order and their dtypes are unchanged, so outputs
  are bit-identical to the eager path.
- Scale queries in fp32 before RoPE, matching the reference.
- Text-only prompts no longer get an all-ones attention mask. That mask
  made ChatSession treat every turn as non-trimmable, so the whole
  conversation was re-prefilled with 0% KV cache reuse. On an M4 Pro with
  the 30B-4bit model, follow-up TTFT in tool-calling sessions drops from
  35-50s to under 1s.

Speculative decoding
- Replace raw KV trim with staged cache rounds (beginRound / commit /
  rewindLastRound). Rejected drafts now rewind exactly, even after a
  RotatingKVCache wraps. Raw trim corrupted the cache in that case.
- If exact rewind isn't supported, fall back permanently to plain
  decoding and record the reason in passthroughReason.
- Support cache-less drafters and models without a main KV cache.
- Emit the prefill-sampled token on the VLM (.logits) prepare path.
  Before, output silently started at the second generated token.

Model loading
- Add ModelConfiguration.excludedComponents to skip components.
- Load components lazily on first use, off the Swift concurrency pool,
  before prefill. State queries don't take the load lock.

Tests: text-only prepare yields mask == nil; staged rounds match plain
generation across a RotatingKVCache wrap (window 16, draft widths 2/3/4);
rejected rounds rewind exactly; passthrough fallbacks; cache-less drafter.
…ens (ml-explore#412)

Generation: honor suppress_tokens and mask multimodal placeholder tokens

Multimodal placeholder tokens (such as audio and image soft tokens) were
occasionally sampled as generated text because generation_config.json's
`suppress_tokens` was unparsed and logits were not masked during sampling.

- GenerationConfigFile: parse `suppress_tokens` across all models
- SuppressedTokensProviding: protocol for models to declare tokens that
  must never be sampled, merged with config-level suppressions
- SuppressTokensProcessor: masks suppressed token IDs to -inf prior to
  sampling in TokenIterator, SpeculativeTokenIterator, and MTP drafts;
  safely ignores negative or out-of-range IDs
- Gemma4 / Gemma4Unified: seed suppressed tokens from config placeholder
  and marker IDs
- Add regression test suite and fix cross-module DocC references

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
`PrefillParameters.progress` counts only the positions a prefill adds, so
an application tracking how full a KV cache is cannot follow a prompt that
resumes on a reused prefix -- as `ChatSession` arranges between turns, and
as a template that re-renders the cached tail (Qwen 3 dropping the
reasoning of past turns) forces it to rewind. The prefix is otherwise
knowable only from the turn's `GenerateCompletionInfo.cachedPromptTokenCount`,
once the turn has ended.

Report it up front instead:

- `PrefillParameters.prefix` is called once, before the first prefill
  forward, with the positions the cache already holds -- `0` when cold. It
  is the figure the same turn's completion info confirms.
- Each token iterator reports it from its own cache progress, so the value
  is the cache's rather than a re-derivation: `TokenIterator`,
  `SpeculativeTokenIterator` and `MTPSpeculativeTokenIterator` each report
  the main cache once, and a draft prefill reports nothing.

`prefix + processed` is what the cache holds while a prompt is prefilled,
which is what a context gauge needs to stay correct mid-turn. Positions are
the units `progress` already reports, so merged embedding positions on VLM
turns count the same way in both.

No model changes: models keep reporting through `progress`, and the new
callback is optional, so existing call sites are untouched.
- TF32 tolerance issues
- TestTokenizer has been replaced by PseudoWordTokenizer
* Complete VLM processor TODOs

---------

Co-authored-by: Antigravity <antigravity@gemini.net>
Co-authored-by: RNT56 <rnt56.2b@gmail.com>
Co-authored-by: David Koski <46639364+davidkoski@users.noreply.github.com>
Support text, images, video, audio, and interleaved embeddings. Load vision
and audio on first use through the shared component loader, preserving an
immutable model tree and keeping text-only checkpoints usable without
processor files. Keep shared encoder implementations package-scoped.

Add reference, component lifecycle, and real-checkpoint integration tests.
…explore#545)

* Add Qwen 3.8 support for text, VLM, and MTP speculative decoding

- Register qwen3_8, qwen3_8_text, and qwen3_8_moe architectures in LLMTypeRegistry and VLMTypeRegistry
- Add qwen3_8_27b_4bit and qwen3_8_27b_8bit model configuration presets to LLMRegistry and VLMRegistry
- Add Qwen3_5VLProcessor and Qwen3_8VLProcessor aliases to VLMProcessorTypeRegistry
- Add dynamic layer_types decoding and faIdx full-attention layer index resolution
- Harden weight sanitization across MLXLLM and MLXVLM for multimodal and text-only checkpoint loading
- Register Qwen 3.8 MTP draft model types in MTPDrafterTypeRegistry
- Add comprehensive Qwen38Tests unit test suite

* Update Qwen 3.8 loading for component-aware checkpoints
* Load Qwen vision on first media use
* Fix Qwen vision loading test fixture
targetLoaderExcludesConvertedMTPComponent(vision: true) has failed on main
since ml-explore#545 made the Qwen 3.5 VLM load its vision tower on first use: the
test counted parameters before the vision tower loads. It now loads with
componentLoading: .immediate and compares key sets, as ml-explore#692 does.

testActiveSpeculativeDecodingReusesAlignedStorageAcrossTurns fails about one
run in a hundred. When the last speculative round accepts every draft, the
iterator leaves the last draft for the next round to feed, so the draft cache
ends one token behind the main cache and the next ChatSession turn rebuilds
both caches. finalizeGeneration now feeds that draft when it was returned,
unless the task is cancelled. Two tests that recorded the lag now expect both
caches at the same offset, and the Harmony tool-call restart now resumes on
both caches.
Current logging produces an enormous amount of logs when using guided generation. This commit addresses that and follows the logic used for other logging in GuidedGenerationLoop.swift: it's logged only when diagnosticLog is enabled. This reduces the amount of logs produced and still leaves the possibility to observe the generation process for debugging.
* Throw MLX errors raised on the loader's own threads

The loader moves work to threads that a caller's withError does not
reach: the concurrentPerform workers that read checkpoint files, the
global queue that runs the async loadWeights, and the global queue that
loads an on-demand component. An MLX error there, such as an allocation
failure or a shape error in sanitize, reached the default handler and
ended the process.

Each of these now runs in its own withError scope. When an MLX error is
followed by a later error it caused, such as a shape mismatch in
update, the MLX error is the one thrown.

* Guard on-demand component loading inside loadModule
* Fix exact prefix rewinds in rotating KV caches

* Fix Gemma3n cross-layer KV sharing
* Drop the attention mask from text-only VLM prompts

FastVLM, Gemma 3, Gemma 4 (both processors), Mistral 3 and SmolVLM
paired every prompt with an all-ones attention mask, including prompts
with no media. `ChatSession` reads any mask as a reason not to resume a
cache (`carriesAttentionMask`), so on these models every text turn and
every tool follow-up prefilled the whole conversation again.

A text-only prompt is one unpadded sequence, so the mask carries
nothing, and none of these models reads it without media. Their
text-only prompts now carry no mask, as Qwen2-VL, Qwen3-VL, GLM-OCR,
LFM2-VL and Muse-Glimmer already do. Prompts with media are unchanged.

Measured on gemma-4-12B-it-4bit (Gemma4UnifiedProcessor), one tool call
and two follow-up turns: the passes after the first reused 175, 226 and
267 cached positions instead of 0, and their prompt time fell from
3.1-3.9 s to about 1.0 s.
* Omit empty text from message content parts

`contentParts(for:layout:)` always appended a text part, so an assistant
tool call without text became `[{"type": "text", "text": ""}]`. Chat
templates test `message.content` for truth: the empty string a text
model receives is false, but a list holding an empty part is true.

Qwen3-VL's template then renders the call as `\n\n<tool_call>` instead
of the `\n<tool_call>` the model generated. The cache no longer matches
the prompt, and a rewind is refused because the model carries M-RoPE
state, so every tool follow-up pass prefilled the whole conversation.

Empty text now gives no part. An empty list is false, as the empty
string is, so the re-rendered prompt extends the cache again.

Checked against the chat templates of every registered model that uses
content parts (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3.5, Qwen3.8,
Muse-Glimmer, Gemma 3, Gemma 4, LFM2-VL, Ministral 3, FastVLM, GLM-OCR):
only the Qwen3-VL template changes output, and it now renders the same
as with string content.

* Limit empty text omission to assistant tool calls
* Support for scripted models (tests)

- add TranscriptKVCache (tests)
- add ability to extend KVCache hierarchy
Reject projections with global scales during fusion preparation. The current fused projection and checkpoint view constructors do not retain those scalars, so keep the original modules and parameters.
transformers 5 writes the LFM2 MLP width as intermediate_size, keeps
rope_theta under rope_parameters, and can untie the output head with a
top-level tie_word_embeddings or tie_embedding. LFM2VL now reads all
three. An untied model gets an lm_head, and sanitize maps a top-level
lm_head into the language model.

With this, LiquidAI/d1-3B loads and chats as an LFM2-VL model.
- LoRA is given N tokens, trims to N-1 to predict N
- if N is 1 it cannot predict from zero
- previously this would fatal error deep inside mlx core
- this adds an error in the typical path
- and a fatal with a more descriptive message if you get to the inner API
- discovered in ml-explore#680
XGrammar generates properties in the order they appear in the schema JSON.
When GenerationSchema is encoded to JSON, its properties are in arbitrary
order, with the declared order in "x-order". MLXLanguageModel now writes
each object's properties in x-order order before passing the schema to
XGrammar.
- handle TF32 vs float32 computations in most recent tests
* switch to MLXLogger

* remove stale import

---------

Co-authored-by: ctymoszek <31750745+ctymoszek@users.noreply.github.com>
* add ScriptedLogitsModel

- this model has a ScriptedScenario (containing a Transcript)
- the Transcript gives the turns to be taken
- this wraps an inner model that provides realistic (real actually) KVCache behavior
…e#706)

Build one shared attention mask from the retained cache window. Preserve absolute M-RoPE positions and add regressions for rotated, windowed, and image continuation.
…ore#714)

Expose ordered token log probabilities from ChatSession

Add a request-scoped streamDetails overload built on ml-explore#640's composed
handler, so callers can inspect the actual cached reply and group tool
passes by completion event. Ordinary streams and existing public enum
cases are unchanged.

Add observe(to:using:) with request-local transformer configuration and
a fresh handler for each generation pass. Base events, cached-prompt
metadata, tool dispatch, and cancellation are preserved.

Add compatibility, cancellation, rejection, cache, and real-model tests.

Developed with Codex assistance.
Each prefill chunk grows the KV cache into new, larger buffers. The
buffers it outgrows return to the MLX buffer cache, but no later chunk
can reuse them, so they stay there until generation clears the cache
on its first token. On long prompts this cache grows by gigabytes.

mlx-lm calls mx.clear_cache() after every prefill chunk. Do the same in
PrefillParameters.forEachChunk, which drives the prefill of every LLM
and VLM, so all models get the fix.
Add hiddenStates(_:) at @_spi(GemmaEncoder) on Gemma4 and Gemma4Unified. It
returns the text decoder's final-norm hidden states for an LMInput, built
through the same helper prepare now uses: soft tokens on their placeholder
rows, per-layer inputs, and the token types that drive bidirectional vision
attention. Clients can read the LM head's input from the loaded VLM without a
second, text-only model.
* mlx-swift 0.33.0

- use compile/@sendable implementation in mlx-swift
* Read Gemma 3 RoPE scaling from rope_parameters

transformers 4.57+ exports set rope_scaling to null and write the
scaling to rope_parameters, either keyed by layer type
({"full_attention": {...}, "sliding_attention": {...}}) or flat.
Gemma3TextConfiguration in MLXLLM and MLXVLM only read rope_scaling, so
for those checkpoints (e.g. TranslateGemma) the global-attention layers
ran without the x8 linear factor. Both now fall back to rope_parameters
when rope_scaling is absent or null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BertConfiguration turned each id2label string key into an Int and built
the dictionary with uniqueKeysWithValues. Keys such as "1" and "01" both
become 1, and Dictionary(uniqueKeysWithValues:) traps.

Read the keys one at a time. Skip a key that is not an integer. Throw
DecodingError.dataCorrupted when an integer id is already in the map.
A test covers colliding keys and a normal id2label.

Co-authored-by: Krish Garg <181051779+krishhgg@users.noreply.github.com>
mattt and others added 24 commits November 4, 2026 09:14
The gated RMS norm passed a float32 identity weight into rmsNorm, which
returns the promoted type of the input and the weight. Mamba outputs, and
the residual stream after the first Mamba layer, became float32.
…ore#763)

EmbeddingGemma2ImageProcessor.pixels creates its array with
`type: Float16.self`. mlx-swift adds `Float16: HasDType` only outside
x86_64 (`#if !arch(x86_64)`), so universal builds, such as an app
Release or archive for "Any Mac", fail with "Initializer
'init(_:_:type:)' requires that 'Float16' conform to 'HasDType'".

Use `dtype: .float16`, which reads the same bytes on every
architecture.
PythonLiteralParser kept the backslash for \x, octal, \a and \v escapes
and for a line continuation, though Python decodes them. A surrogate
pair written as two \u escapes made it reject the whole literal, so the
Pythonic parser passed the raw text, quotes included, to the tool.
* Add production-ready LFM2.5 model support

Support dense and MoE LFM2.5 checkpoints, including mixed-precision quantization, causal hybrid caches, reasoning/tool conventions, and scoped model variants. Harden model subdirectory resolution and add strict real-checkpoint and regression coverage.

* Add LFM2.5 DSpark speculative decoding

* Optimize quantized MoE route grouping

* MLXVLM: fail closed when the LFM2VL image token cannot be resolved

ml-explore#576 replaced the hardcoded 396 with a vocabulary lookup but kept 396 as
the fallback. That fallback is wrong for the LFM2.5 vocabulary, where id
396 is the ordinary BPE token "ab": a tokenizer without an `<image>`
entry makes the processor scan prose for markers instead of reporting the
problem, and the model then aborts the host process.

The processor now resolves the id once in `init` and throws from `prepare`
when the vocabulary has no such token. `mergeInputIdsWithImageFeatures`
throws instead of calling `fatalError`, so a disagreement between the
tokenizer-derived marker and `config.json`'s `image_token_id` is catchable
and names both ids rather than killing the process with no crash report.

Also removes the duplicated magic values. The placeholder text becomes
`LFM2VLProcessorConfiguration.imageToken`, overridable via `image_token`
as Pixtral, Mistral3 and MuseGlimmer already do, and the legacy 396
default now lives only in `LFM2VLConfiguration.defaultImageTokenId`.

* Load LFM2VL vision on demand and harden LFM loading and cache rewinds
* Add mid-turn steering to ChatSession

Queue instructions for active responses and apply them at supported text
or step boundaries while preserving emitted output and completed tools.
Expose steering outcomes through Generation.steering and reuse verified
cache prefixes for continuation.

Handle completion races, cancellation, and caller isolation. Add unit
and real-model coverage, and document scheduling and compatibility.

* Wait for tool recovery before steering

* Defer steering until after tool result continuation
…plore#766)

* Keep Qwen2-VL and Qwen2.5-VL in the model dtype on image prompts

The M-RoPE path rotates queries and keys with float32 cos and sin, so
image prompts promote them to float32. Layer 0 caches float32 keys
beside float16 values and returns a float32 attention output. From
there every layer runs and caches in float32. Decode reads twice the
KV bytes, and SDPA casts layer 0's values on every step.

Cast cos and sin to the hidden-state dtype, as mlx-vlm does and as
Qwen3VL and Qwen3.5 already do here. Text-only prompts take the plain
RoPE path and do not change.

A regression test runs a float16 tiny model through an image prefill
and one decode step. It checks that every cache layer stays float16.

* Keep FastVLM and Mistral3 image features in the model dtype

FastVLM passed float32 pixels to its vision tower, so the image
features came out float32. Concatenating them with the text embeddings
promoted the whole language model and its KV cache to float32. Cast
the pixels to the patch-embed weight dtype, as mlx-vlm does.

Mistral3 cast its image features to bfloat16 before the patch merger.
For a float16 checkpoint this mixed bfloat16 and float16, which
promoted the language model to float32 in the same way. The Pixtral
tower already returns features in its weight dtype, so drop the cast,
as mlx-vlm does. bfloat16 checkpoints do not change.

A parameterized test runs each tiny VLM in that suite in float16
through an image prefill and one decode step, and checks the cache
dtype.
Add LiquidAI LFM3 text model support

- Move the LFM3 configuration, decoder blocks, and backbone to MLXLMCommon so an MLXVLM wrapper can reuse them. `LFM3Model`, its registry entry, and LoRA stay in MLXLLM.
- The backbone accepts token ids or embeddings, uses caller-owned caches, and takes an optional mask per attention type. It exposes `embed(_:)`, `projectLogits(_:lmHead:)` and `newCache(parameters:)`. `LFM3Model` conforms to `HiddenStateLanguageModel`.
- Keep the bare `lm_head` path when stripping the `language_model` prefix, so an untied head keeps its per-layer quantization.
- Declare always-on thinking, honour `enable_thinking`, and declare the LFM3 tool call format.
- Project only the trailing rows in `nextTokenLogits` for quantized heads.
- Read the LFM2 key `tie_embedding` before `tie_word_embeddings`.
- Add a reference-logits test against `modeling_lfm3.py`, plus tests for the untied `lm_head` and per-type mask overrides.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…explore#761)

The VLM rotary built plain M-RoPE and ignored rope_parameters, so a
Qwen3.5 checkpoint with rope_type "yarn" ran with default frequencies and
no attention factor. MLXLLM Qwen35 already applies YaRN through
initializeRope.

RotaryEmbedding now computes inv_freq and the attention factor like HF
`_compute_yarn_parameters` when the type is "yarn", and scales cos and
sin by that factor. This scales only the rotary slice of q and k, as HF
does. Other rope types take the old path unchanged.
A missing original_max_position_embeddings falls back to
max_position_embeddings, as HF does.

On sensenova/SenseNova-6.8-Code2Video (factor 2, original 262144),
YaRN changes 17 of 32 rotary frequencies and the factor is 1.0693. 8-bit
text-position KL against HF bf16 over a 988-token prompt drops from
0.051 to 0.016.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…e#774)

Speculative iterators returned no log probabilities, so ChatSession threw
unsupportedSpeculativeDecoding when an observation requested them. The
verify pass already computes the main model's logits for every emitted
token; the iterators discarded them.

SpeculativeTokenIterator and MTPSpeculativeTokenIterator now record each
emitted token's values from the processed logits row it was sampled from,
the values TokenIterator reports. A round normalizes its emitted rows in
one batch after acceptance and evaluates the per-token views in the same
asyncEval, so reading them does not sync the GPU per token. Rejected
proposals report nothing, and nothing is computed when reporting is off.

The guard and ChatSession.ObservationError (added in ml-explore#714, unreleased)
are removed.
…lore#724)

The MTP verify loop sampled draft rows one at a time: each row cost an argmax kernel plus an eval/item GPU-to-CPU sync, so a round with K drafts stalled the stream up to K+2 times.

For greedy sampling with a stateless processor (nil or SuppressTokensProcessor), verification is now batched: argmax over the whole block, one readback of the draft and target tokens together, then the acceptance scan on CPU. Other samplers and stateful processors keep the per-row loop, since their didSample updates can change later rows. Requested log probabilities come from the same processed rows the batched argmax reads.

Parity is exact: pure-function parity against a sequential reference (ties, dtypes, token suppression), iterator token/cache/telemetry parity on a scripted model across block sizes and stop points, and token plus byte-exact cache parity on Qwen3.5-4B-4bit with the MTP-1 drafter.

Measured on Apple M2: verify stage 1.25-6.4x faster for block sizes 2-8; end-to-end 128-token greedy generation on Qwen3.5-4B-4bit (block 2) 27.7 to 28.5 tok/s. Larger draft blocks benefit more.
* 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.

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.

* Share checkpoint components as values and warn when excludedComponents cannot skip a built-in component
`ModelContainer` and `EmbedderModelContainer` report the buffers of their
model through `ModelMemoryReporting`, but `EmbeddingGemma2Embedding` keeps its
model private and reports nothing. An application that shows what each loaded
model holds cannot measure this embedder, and its vision and audio encoders,
which load the first time an input needs them, stay invisible too.

Conform `EmbeddingGemma2Embedding` to `ModelMemoryReporting`. `memory()`
returns the model's own `memory()`, so a media encoder counts once it has
loaded, as it does for a VLM in a `ModelContainer`.

`MultimodalEmbedding` itself does not require it: the protocol is public, and
adding a requirement would break every other conformer.
A Pythonic tool call that writes a multi-line value as a triple-quoted
string, like content="""...""", was rejected, so the tool got the raw text
with its quotes. The parser now reads triple-quoted strings as Python
does: the string ends at the next three quotes and may contain newlines
and single quotes.
…es (ml-explore#778)

`contains(_:)` answers by name only, so it ignores the `matches`
predicate that `registerModelType(_:matches:creator:)` adds for a
`model_type` shared by several architectures. Once
`LFM2DSparkRegistration` registers its drafter under "qwen3",
`MTPDrafterTypeRegistry.shared.contains("qwen3")` is true for every
Qwen3 checkpoint, and a caller cannot tell a DSpark drafter from a
plain Qwen3 model before it loads one.

The new overload asks whether `createModel(configuration:modelType:)`
would find a creator that accepts the given configuration. It reads no
weights and allocates no model. `contains(_:)` is unchanged.
ml-explore#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. ml-explore#702 then deleted that alias and moved the libraries to
MLXLogger. ml-explore#711 merged on Nov 10 with the checks from before ml-explore#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 ml-explore#702.
Importing os would also build, but it fails on Linux and skips the backend that
apps install through `MLXLogger.factory`.
…ech/gemma4-qat#1692)

66 upstream commits since 7eb77ef. Conflicts:
- Package.swift: keeps numen-tech/mlx-swift `prism` (upstream moved to 0.33.0,
  which prism already carries).
- CompiledTrace.swift: takes upstream ml-explore#720's version (the stateless shims and
  CompileOverloads.swift gone, the trace closure non-Sendable), which
  supersedes the fork's 0.33 compat box (bb851d8/fb3d548/080e461).
- MLXVLM Qwen35.swift: keeps the speculative seam (hiddenStates/applyLMHead
  split, backboneHidden/Logits/Embed, textOnlyContinuationState) and the
  op-cost probe marks, with upstream's optional faIdx/ssmIdx (ml-explore#545/ml-explore#737):
  the SSM mask is built only when a linear layer exists and the MTP
  source-index state is empty without a full-attention layer; adds upstream's
  excludedCheckpointNamespaces (ml-explore#711).
…f by default (numen-tech/gemma4-qat#1692)

Upstream sends the layouts mlx core fuses (no mask, head dim 128, Hk/Hv in
its table: every Qwen3.5 PARO and Ternary Bonsai 2 pack) to
MLXFast.gatedDeltaUpdate in inference and training. Here that route is taken
only inside GatedDeltaFastRoute.$isEnabled.withValue(true) (a task-local,
read when the graph is built), so decode, speculative verify and the ml-explore#294
rollback replay keep the custom kernel the host's goldens were built on;
gatedDeltaReplayState forces it off even inside an opted-in region.
numen-tech/gemma4-qat#1693 measures it for prefill. Upstream's three
fast-path tests run with the route on.
…ch/mlx-swift#31 merges

SwiftPM refuses two branch requirements for one package, so the host
(numen-tech/gemma4-qat, building against the unmerged branch heads) can pin
catchup-1691 only if this package names the same branch. Revert this commit
(back to prism) once numen-tech/mlx-swift#31 is merged, before this merges.
… faCacheOffset)

Upstream ml-explore#545/ml-explore#737 made faIdx optional and renamed the helper prepare uses to
anchorCacheOffset (a full-attention layer's offset, else a linear layer's).
For every model with a full-attention layer, which is every Qwen3.5 and
Ternary Bonsai 2 pack, it returns what faCacheOffset did.
…tom kernel; RewindableConvolutionCache takes no turn checkpoint (Codex review on #1692)

- A compiled single-token decode trace keeps the graph of its first call, so a
  step traced inside a GatedDeltaFastRoute region would have carried the fast
  route into every later step: the route now needs more than one row.
- A rollback-recorded verify (Qwen3.5 VLM) runs the custom kernel even inside an
  opted-in region, matching gatedDeltaReplayState, so a partial accept rebuilds
  the state with the recurrence that produced the verify outputs.
- Upstream's RewindableConvolutionCache subclasses MambaCache with other slot
  meanings and an advancing offset; restoring the fork's turn checkpoint would
  have left the offset behind, so it refuses to capture or install one.
Tests: testGatedDeltaFastRouteIsOptInAndMultiRowOnly,
testRewindableConvolutionCacheTakesNoTurnCheckpoint.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T20:38:43.010545Z 00149dc PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.