Skip to content

Sync with upstream release 3.33.0; carry #716 and #813 - #19

Merged
Satchitananda merged 75 commits into
mainfrom
sync/upstream-release-20261126
Nov 27, 2026
Merged

Satchitananda merged 75 commits into
mainfrom
sync/upstream-release-20261126

Conversation

@Satchitananda

Copy link
Copy Markdown
Owner

Proposed changes

Rebase the fork on upstream release 3.33.0 (ca661dc). Supersedes #18, which tracked upstream main. Pairs with mlx-swift sync/upstream-release-20261126.

Details: UPSTREAM_RELEASE_SYNC.md, top section. Plan: plans/wip/MLX_FORKS_UPSTREAM_SYNC_20261125_PLAN.md (umbrella).

Proof

Built with swift build --build-system native --build-tests -Xswiftc -strict-concurrency=complete against the release-sync mlx-swift (e31ba6d9), with mlx.metallib staged:

Regime XCTest Swift Testing
default TF32 1,081 executions, 9 skipped, 0 failures 1,893 tests / 185 suites (2 upstream withKnownIssue)
MLX_ENABLE_TF32=0 same same

There are no concurrency warnings. The catalog kit --core (2,426 passed) and model suites pass against this branch.

Risk: medium. Guided generation and Gemma 4 back processing and the Director. Mitigated by the kit's 640-case grammar corpus and model gates. Privacy/storage/egress: none. UI: none.

davidkoski and others added 30 commits October 23, 2026 10:14
- 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>
…l-explore#735)

Keep image sentinels out of the repetition-penalty history

VLM prompts carry negative placeholder IDs (FastVLM uses -200). The
penalty processors loaded them into their token history and then
indexed logits with them. loadPrompt now drops negative IDs, so
sampled tokens are unaffected.

To keep loading cheap on long prompts, it reads the prompt back to
front, starting with `capacity` tokens and then doubling the window
size, until it has `capacity` tokens. Each window is converted on the
CPU stream to skip a GPU round trip. Loading no longer scales with
prompt length (0.01 to 0.04 ms, down from about 2 ms per processor
for a 1M-token prompt).

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

* 🐞 Fix attention masks sized from the absolute cache offset

A capacity-limited cache evicts keys while the absolute offset keeps
growing, so a mask sized from that offset describes more keys than the
cache presents and attention rejects the shapes. Qwen3VL fixed its own
case in ml-explore#706. createAttentionMask(h:cache:) still built the array from
the raw offset, and Qwen3VLMoE used that and then sliced it again.

Both cache-list overloads now delegate to the cache makeMask, and
Qwen3VLMoE builds one shared mask from the retained window, as ml-explore#706
does. M-RoPE positions stay absolute. Qwen3.5-VL no longer slices its
mask to an offset-derived length. That slice ended past the mask and
MLX clamps it, so the results do not change. The Qwen3 embedder folds
key padding across the same retained width.

Regressions cover warm continuation after rotation for Qwen3VLMoE and
Qwen3.5-VL, the padding fold, and the mask width of the shared helper.

* Gemma2: suppress boolean attention masks like mlx-lm

Gemma2 attention added its mask to the scores unconditionally, so a
boolean mask boosted the kept scores instead of hiding the masked keys
and multi-token prefill never matched token-by-token decode. Route it
through applyAttentionMask (bool masks suppress, float masks add),
matching mlx-lm gemma2.py, and expose that helper to model code.

* Gemma2: build the attention mask from the first layer cache
…xplore#703)

attentionWithCacheUpdate sent every query length to
quantizedScaledDotProductAttention when the cache is quantized. That path
materializes [B, H, L, N] scores through quantized matmuls, which is the
right trade at decode (L = 1 reads a quarter of the key bytes) but loses to
the fused kernel once the query block is long enough to be compute-bound.

For L >= 64 and head dims the fused kernel handles on every GPU generation
(64, 72, 80, 96, 128), dequantize the returned keys and values once and
call MLXFast.scaledDotProductAttention. Head dims 192 and 256 stay on the
quantized route because MLX runs them unfused outside NAX, where the
quantized matmuls are within ~1.1x. MLA-style caches with narrower values
than queries also stay on the quantized route.

Measured on M4 Pro with Qwen3-14B-4bit, kvBits 4, step 512:
- 16k prefill from an empty cache: 171 -> 199 tok/s (fp16 cache: 200),
  peak memory 11.3 -> 9.8 GB
- 2k turn over 8k history: 170 -> 195 tok/s (8-bit cache: 173 -> 182)
- decode at 8k unchanged (quantized route still used at L = 1)
- SDPA microbenchmark, D = 128, L = 512: quantized path 1.45-1.7x slower
  than fused at N = 2.5k..33k, and 135 MB..1.4 GB of scores vs 24..99 MB
…re#563)

Add reasoning support: Gemma 4 channels and Generation.reasoning

* Support Gemma 4's labeled reasoning channels

Gemma 4 delimits thoughts with special tokens (<|channel>, <channel|>)
and a role label after the opener (<|channel>thought\n ... <channel|>).
A delimiter pair cannot express that.

Add an optional ReasoningConfig.channel (ReasoningChannel) and a label
state in ReasoningEventEmitter. nil keeps the pair protocol unchanged,
so Qwen3 and DeepSeek-R1 are unaffected.

- The label is consumed as metadata; unknown labels route to reasoning.
- Hold-back covers the longest watched delimiter.
- An unterminated label settles into a visible body.
- A stray end delimiter with no opener is swallowed.
- "content" is listed as a response label defensively, not from
  observation.

The four Gemma 4 model types declare the protocol through
ChatConventionsProviding (ml-explore#502). Also add a token-id overload of
promptEndsInsideReasoning.

* Resolve the think-then-call gate through the template default

The constrained-generation path read the reasoning level as
`thinkingEnabled(for:) != false` for the gate, but rendered the prompt
with `?? defaultOn`. For Gemma 4 (`defaultOn: false`) these disagree:
the gate opens a thinking phase, the template prefills an empty closed
channel, and a `.required` tool call never arrives.

Add `thinkingEnabled(for:defaultOn:)` and use it for both. No change
for `defaultOn: true` models. The tests need a macOS 27 host to run.

* Expose reasoning as Generation.reasoning

Nothing on the standard path read ModelConfiguration.reasoningConfig,
so raw reasoning reached Generation.chunk with delimiters attached and
ChatSession replayed it into later prompts.

- StandardTokenStreamDecoder takes an optional ReasoningEventEmitter,
  applied after the stop-string filter and before the tool-call parser,
  so a tool call in a scratchpad cannot fire. finish() drains the
  scanner first.
- Add Generation.reasoning(String) and update all in-repo switches.
  This is a source-breaking change for downstream exhaustive switches.
- Framed protocols (Harmony, Onyx) keep decoding their own reasoning.
- generate() computes priming from the prompt (needed for DeepSeek-R1,
  which prefills
…#712)

Support Nemotron 3.5 (Lightning, Bolt) text models

- Read the layer stack from layers_block_type or block_configs when
  hybrid_override_pattern is absent; omit num_hidden_layers if the
  config does.
- Add moe_latent_size: routed experts run in a latent space between
  fc1_latent_proj and fc2_latent_proj, as in mlx-lm.
- Add per-layer block_configs overrides (expert count, expert size,
  experts per token) and register nemotron_h_puzzle (Bolt).
- Skip MTP head weights (mtp.*) at load.
- Declare the Nemotron-H reasoning config (enable_thinking), which the
  Nemotron 3 and 3.5 chat templates use; previously the flag was ignored.

Tested: Nemotron-3.5-Lightning-30B-A3B-4bit and Bolt-74B-A9B-MLX-3bit
load and generate; Lightning with thinking off now answers directly.
AI-assisted (Claude Code); reviewed against mlx-lm.
* Expose Qwen 3.5 text geometry read-only

Applications that plan memory for a Qwen 3.5 target and its MTP drafter need the text dimensions before running either. Make the dimension fields of Qwen35TextConfiguration and the models' configuration readable, as the VLM's TextConfiguration already is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Add GrammarConstraint.freshMatcher()

Return a new constraint over an existing compiled grammar, at its
initial state, using xg_matcher_new. Unlike clone(), it does not need
GrammarMatcher::Fork(), which the vendored xgrammar lacks. Also correct
the xgrammar version that added Fork() to v0.1.33 in three notes.

Co-authored-by: ctymoszek <31750745+ctymoszek@users.noreply.github.com>
* Feed the sampled token before its fast-forward tokens

When xgrammar returned fast-forward tokens after a sampled token, the
guided loop fed only the fast-forward tokens to the model, so later
logits conditioned on a sequence missing the sampled token. Feed the
sampled token first, still one token per forward pass.


Co-authored-by: ctymoszek <31750745+ctymoszek@users.noreply.github.com>
An application can read how much memory a conversation's KV cache holds
(`KVCacheStatus.memoryBytes`), but not the model itself. Summing `nbytes`
over `parameters()` is the documented workaround. It can count a buffer
shared by several tensors more than once, and it misses on-demand
components, such as a VLM vision tower that loads on the first image.

Measure it from the buffers instead:

- Add `ModelMemory` and `BaseLanguageModel.memory()`. It passes
  `innerState()` to `Memory.bufferSize` from mlx-swift 0.33, which counts
  each buffer once. Loaded on-demand components are added in name order,
  and each gets the bytes it adds over what is already counted.
- Add `ModelMemoryReporting`, adopted by `ModelContainer` and
  `EmbedderModelContainer`. `RerankerContainer` takes an optional
  `memoryReporter`, which the reranker factory sets. A custom reranker
  without one reports `nil`.
- `bufferSize` throws for an array that was never evaluated. Factory
  models are evaluated before they are returned, so this only affects
  modules built by hand.

The wired-memory article and the model-container skill reference now use
`memory()` for weight bytes and point to `KVCacheStatus.memoryBytes` for
the cache.
…lore#740)

* Use the MLXFast gated delta kernel where mlx core supports it

mlx core now has a fused gated delta kernel with a gradient,
MLXFast.gatedDeltaUpdate. It covers the head layouts of every
Qwen3.5 and Qwen3-Next checkpoint. gatedDeltaUpdate still ran the
custom Metal kernel for inference and, because that kernel has no
gradient, a per-step ops graph for training.

Take the MLXFast kernel when mlx core has a fused kernel for the
inputs: no mask, head dim 128 and a supported (Hk, Hv) pair. Other
inputs keep the custom kernel or the ops path, because mlx core
would run a per-step fallback for them.

mlx core casts g and beta to the dtype of q and k. In bf16 a decay
just below 1 rounds to 1, so the state stops decaying
(ml-explore/mlx#4725). Pass q and k in float32 until mlx-swift
includes ml-explore/mlx#4760. On Qwen3.5-9B this keeps perplexity at
the custom kernel's value, where bf16 inputs raise it by 0.9%.

A training step is 6.5x to 8.4x faster per gated delta layer, with a
third to a half of the peak memory. Prefill is up to 1.9x faster per
layer. Decode is unchanged.

* Time the fastest of 8 decode steps in the 32K KVarN smoke test
* Add MiniCPM5 tool call parser

* Skip CDATA sections when finding MiniCPM5 tags

A `</param>` inside a CDATA value ended the value early, so the tool
got `<![CDATA[print("` instead of `print("</param>")`.

* Test MiniCPM5 `</function>` inside CDATA as a known issue

ToolCallProcessor ends the call at the first `</function>`, even
inside CDATA.
…-explore#743)

* integration tests to run using xcode 27 (now that it is released)

- partial for ml-explore#739
- also switch PR tests to use the same form of xcodebuild (it was that other form form issues with headless runners)

* handle NAX delta
* remove unneeded CPU tests -- these should run on the gpu
* disable failing tests (for now)
embed(inputIds:attentionMask:softTokens:) took soft tokens for a single
row only, so image sequences were embedded one at a time. Placeholders
are now numbered across the batch, row by row, with one cumsum over the
flattened ids, so a [B, L] batch takes [B, n, hidden] soft tokens in one
call. A batch of one is unchanged.

Tested: a batch of two image sequences equals each embedded alone
(within 1e-5 in IEEE float32, within upstream's TF32 bound by default).
…plore#715)

* Show the response schema to the model during guided generation

The response schema is added to the system prompt for guided generation, so
@Guide descriptions inform the response. The tool-aware prompt is unchanged.

* Document that the response schema goes in the system prompt

Explains when to pass includeSchemaInPrompt: false.
…l-explore#747)

* RotatingKVCache: keep the pinned prefix visible in multi-token masks

makeMask applied a plain maxSize window over the cache rows for multi-token
writes. Once rows had been evicted, every query after the first lost the
`keep` prefix that one-token decoding keeps, so chunked prefill and
multi-token writes after a wrap attended to a different context.

With keep > 0 and the default window, the prefix now takes `keep` slots and
the most recent rows take the rest. A different window size keeps the old
mask. This matches ml-explore/mlx-lm#1978.

Fixes ml-explore#742.
…explore#692)

* Fix EmbeddingGemma 2 image orientation and batch text embeddings
* Add MultimodalEmbedding contract and factory for media embedding models
* ⚡ Embeddings: Reduce EmbeddingGemma 2 image preprocessing memory

Keep source pixels in half precision and cast samples during the antialiased
resize. This removes full-resolution float32 staging while preserving JPEG's
extended range and the CPU path.

Add pixel comparisons for PNG/JPEG, CPU/GPU execution, and resize shapes.

AI assistance: Codex implemented the code and tests.
…e#581)

feat: add MTP speculative decoding to ChatSession (Qwen, Gemma)                                  
                                                                                                 
- Keep drafter state, target state, KV cache, and transcript together across                     
  turns and tool restarts, with Qwen text and VLM adapters                                       
- Check that target hidden/vocab sizes match the drafter (Qwen), and check                       
  the shared KV layout (Gemma)                                                                   
- Fall back to target-only generation when MTP is unsupported, and expose                        
  the fallback reason as a typed value                                                           
- Rebuild MTP state from the transcript when MTP becomes eligible again                          
- Model cache reuse as an enum and move drafter finalization into MLXLMCommon
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.
ykhrustalev and others added 27 commits November 16, 2026 12:20
swift-jinja throws on NSNull, so once a tool call with a null argument was in
history every later prompt failed. Tool-call arguments now reach the template
with null as Optional.none, which swift-jinja renders as null.
**Add DiffusionGemma support**

- Add production-ready DiffusionGemma support.
- Rename `LanguageModelCapabilities` to `LMModelCapabilities` to avoid a FoundationModels clash.
- Fix DiffusionGemma review issues.
- Expose live K/V from `VarianceNormalizedKVCache`. DiffusionGemma's decoder reads the prompt through `currentKeyValues()`, which the cache left as the default `nil`. Decoding therefore ran without the prompt in those layers and produced wrong answers. The cache now returns its dense, chronological K/V (completed tiles plus the raw tail, trimmed to the offset). The output now matches the default cache.
- Use the Gemma 4 image geometry. Images and frames were resized to 224x224 with a fixed 280 soft tokens. That size is not a multiple of 48 (`patch_size * pooling_kernel`), so only 21 of the 280 tokens carried image content.
  - `DiffusionGemma4Processor` now resizes each image within `image_seq_length` cells and each video within `video_processor.max_soft_tokens`. It keeps the aspect ratio and gives each placeholder its item's own token count.
  - `DiffusionGemma` encodes each image and frame at its own size and batches neighbouring items of the same size.
  - The fixed-length padded encoder path and its `-inf` mask are removed, which restores `Gemma4Encoders.swift` to upstream.
  - On diffusiongemma-26B-A4B-it-mxfp4, the COCO "two cats" photo (000000039769) now reports 2 cats instead of 1. A text-only image reads the same as before.
…n tests (ml-explore#756)

* Add LiquidAI LFM3 text model support

* Share the LFM3 text backbone for multimodal wrappers

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 takes token ids or embeddings through the same code path, uses
caller-owned caches for positions, and accepts an optional mask per attention
type. It exposes embed(_:), projectLogits(_:lmHead:) for tied and untied
heads, and newCache(parameters:). LFM3Model conforms to
HiddenStateLanguageModel.

Keep the bare lm_head module path when stripping the language_model prefix,
so an untied lm_head keeps its per-layer quantization.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(lfm3): harden implementation and expand regression coverage

* chore(lfm3): remove incorrect Apple attribution from new tests

* fix(lfm3): align validation and tests with review feedback

* fix(lfm3): address backbone and generation review feedback

* Move tokenizer validation to BaseLanguageModel

---------

Co-authored-by: pHequals7 <ce17b115@smail.iitm.ac.in>
Co-authored-by: Pranav Hari <39328505+pHequals7@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
MoEGate gathered the routing weights from the bias-corrected,
group-masked scores, applied routed_scaling_factor only when it
normalised them, and computed the scores in the activation dtype.
mlx-lm uses e_score_correction_bias only to choose the experts, gathers
the weights from the sigmoid scores, always applies the scaling factor,
and scores in float32. With a bfloat16 bias near 4, bfloat16 selection
scores take about a third as many distinct values as there are experts
and change which experts are selected.

Score in float32 and return the weights in the input dtype, as
DeepSeek's inference Gate does with weights.type_as(x), so the MoE
output keeps the activation dtype. Add tests with expected values from
mlx-lm's MoEGate in float32 and bfloat16.
…ml-explore#799)

A Pythonic tool call that writes a regex or a Windows path as a raw
string, like pattern=r"\d+", was rejected, so the tool got the raw text
with the r and the quotes. With a declared string parameter the parser
was not even tried. Python also joins adjacent string literals, as in
('part one ' 'part two'). The parser now reads r and u prefixes and
adjacent literals as ast.literal_eval does.
…tSize (ml-explore#764)

* Scale up GLM-OCR images with a side under 28 px

GlmOcrProcessor threw for images with a side under patch_size * merge_size.
QwenVL.targetSize now takes a scaleUpSmallSides flag that scales such images
up first, as Glm46VImageProcessor.smart_resize and mlx-vlm do. Only GLM-OCR
sets it, so the Qwen processors keep throwing like their transformers
counterparts.

* Match smart_resize's rounding and checks in QwenVL.targetSize

Comparing QwenVL.targetSize with the Python smart_resize it ports
(transformers' Qwen2-VL and GLM-4.6V processors, and mlx-vlm's GLM-OCR
port) over ~12k image sizes found these differences:

- Python's `round` rounds halves to even; Swift's `round` rounds them
  away from zero. Any side that's an odd multiple of `factor / 2` (e.g.
  70 or 1022 px with factor 28) came out one factor larger.
- The aspect-ratio check used integer division, so ratios just over 200
  (10010 / 50) weren't rejected.
- When scaling down for maxPixels, a side wasn't clamped to at least
  `factor` as it is in Python.
- The arithmetic was done in Float instead of Double.

With these fixed, the results match the Python implementations for every
size in the comparison (GLM-OCR and Qwen2-VL budgets).

* Spell out height and width in the GLM-OCR small-image test
* Keep Qwen2-VL vision attention inside each image

Two still images each have t == 1, so the vision tower treated every patch
row as one attention block. Each image could attend to the other. Attention
now follows the cu_seqlens boundaries, which is what one image or one video
already produced.

* Run swift-format

* update tests and comments to reflect fix

---------

Co-authored-by: David Koski <dkoski@apple.com>
* Steer reasoning models and framed protocols at the next safe point

ml-explore#608 ends a steered step at the next text boundary only when the model
declares no reasoning protocol. Reasoning models and the framed Harmony
and Onyx protocols finish their whole step instead, even in the middle
of a thought. In an app that steers Qwen3.8-27B, an instruction sent
while the answer streamed reached the model 190-217 chunks later
(6.9-8.1 s), and one sent while the model was thinking waited 23.8 s
for the rest of the thought and the whole answer.

A step can now end at the next safe point, in the answer or inside a
thought, with every decoder:

- The standard decoder accepts a reasoning model while its emitter
  holds nothing back: no partial delimiter, no unresolved label, and no
  trailing whitespace of a thought.
- Harmony and Onyx end inside an analysis, private, or visible frame,
  never in a header or a tool frame.
- A safe point never follows whitespace. Templates commonly trim a
  message's trailing whitespace, so a step that ended on "\n\n" left
  the cache holding tokens the re-render dropped. Caches that cannot
  rewind, as in Qwen 3.5 hybrids and M-RoPE VLMs, then rebuilt the
  whole conversation: 2 of 8 cuts on Qwen3.8-27B did.
- A thought that steering cuts short is recorded as finished, so a
  template that replays reasoning renders what the cache holds and the
  next step prefills only the new message. A thought cut by the length
  limit is still dropped.

Measured in the app on an M5 Max:

- Qwen3.8-27B-4bit: 0.22-0.30 s from the instruction to the first new
  text in the answer, 0.22 s inside a thought. All 11 cuts continued
  the cache append-only, and so did the turn after each.
- Muse-Glimmer-30B-8bit (Onyx): the step ends 0.06-0.12 s after the
  instruction and new text follows in 0.50-0.67 s, from its private and
  visible frames alike.
- LFM2.5-24B-A2B-OptiQ-4bit, which declares no reasoning protocol:
  0.11-0.17 s, as before.

Harmony is covered by scripted tests only.

* Interrupt a response at its next safe point

A client can stop a ChatSession response only by cancelling its
consumer. That rolls the turn back: the prompt and the partial reply
leave the transcript and the token ledger is cleared, so the next call
prefills the whole conversation again. An app that keeps the stopped
reply on screen also ends up with a transcript the model never saw.

`interrupt(response:)` ends the response at its next safe point, the
one a steered step uses, inside a thought too. The step reports the new
`GenerateStopReason.interrupted`, the reply is recorded, and the stream
finishes normally. Instructions the response has not applied are
reported as failed with `responseEnded`. With `toolDispatch`, calls the
model already made run first, and the step that answers them stops at
its first safe point, so no tool result is left without an answer.

Interrupting needs no structured conversation, so the token loop now
receives the mailbox of a response from a raw restored cache too. Its
steering is still rejected up front.

Measured in the app on Qwen3.8-27B-4bit with thinking on: the response
ends 0.04-0.05 s after the call in the answer or in a thought, and
0.41 s after a call made during prefill, which lets the model write its
first token. Each time the next turn continued the cache and prefilled
25-28 tokens; after cancelling, it prefilled the whole conversation.

`.steered` from ml-explore#608 is not in a release yet, so clients update their
exhaustive switches over `GenerateStopReason` once for both cases.

* Decide interruption inside the steering mailbox's take

The runner checked `isInterrupted` and then called `take(closeIfEmpty:)`,
two separate lock acquisitions. An interrupt that landed between them let
`take` drain instructions queued before it, so the response added a user
turn and ran one more step before it stopped at the next safe point.
Nothing was lost, but the interrupt was not as prompt as it promises.

Make the decision atomic:

- `SteeringControl.take(closeIfEmpty:)` returns no instructions once the
  response is interrupted, under the same lock that drains the mailbox.
  The pending batch stays for `closeAndTake()`, which reports it as
  `responseEnded`, as `interrupt(response:)` documents.
- `ChatSession` no longer checks `isInterrupted` before `take`.
  `isInterrupted` remains only for the token loop's stop reason.

The mailbox owns its state, so the question "may this batch be applied"
belongs with it rather than with a caller that reads the state twice.
…-explore#630)

PrismML's Bonsai 2 27B ships as a Qwen3.8-27B whose language-model weights
are ternary, packed in MLX affine 2-bit form in a Hadamard-rotated input
basis: R = H·S/√n with n = 1024 and a ±1 sign vector per module. The config
declares `model_type: prism_hadamard_qwen35`, `base_model_type: qwen3_5` and
a `modules` manifest naming every packed module. The weights carry ordinary
`.scales`, so a loader that skips the rotation accepts them and decodes
fluent nonsense instead of failing.

MLXLMCommon gains `HadamardQuantized.swift`, built on stock ops
(`hadamardTransform` and the quantized layers' own forwards):

- `SignedBlockHadamard`: the blockwise signed transform and its inverse, in
  float32 and cast back to the input dtype, as the reference runtime does.
- `HadamardQuantizedLinear` rotates the input before the packed matmul.
  `HadamardQuantizedEmbedding` un-rotates looked-up rows and rotates the
  input when the table serves as a tied head. `signs` is a frozen
  parameter, so the pack's `.signs` tensors load like any other weight.
- `HadamardQuantizedManifest` decodes the pack's declaration.
- `HadamardQuantizedCheckpointPolicy` validates the manifest (schema, base
  model type, tensor namespace, activation layout and dtype, duplicate
  paths), replaces exactly the manifest's `Linear` / `Embedding` leaves
  with rotated placeholders before the weights load (rejecting a block that
  does not divide the layer's width), and prepares the checkpoint: it
  rejects sign vectors other than ±1 and casts the unpacked float32 tensors
  to the activation dtype, except `A_log`, as mlx-vlm's converter does.

MLXLLM and MLXVLM each gain `Models/PrismHadamardQwen35.swift`:
`PrismHadamardQwen35Model: Qwen35Model` and `PrismHadamardQwen35: Qwen35`
substitute the manifest modules in `init` and override `prepareCheckpoint`
to run the policy after the base class maps the checkpoint names. The
vision class inherits `Qwen35`'s on-demand vision tower, whose deferred
load runs through the same override. Both registries map
`prism_hadamard_qwen35`, and `LLMRegistry` and `VLMRegistry` gain
`bonsai2_27B_ternary_2bit`.

`HadamardQuantizedTests` (16) cover the transform, both layers, the
substitution and its rejections, the loader's quantize pass, manifest and
sign validation, both registries, the vision tower loading only for media,
and the exact-class guards that keep upstream's projection fusion and
prefill trimming away from rotated layers.
The SwiGLU clipped with MLXArray(limit) bounds. MLXArray(Float) is a
float32 array, so clip promoted bfloat16 activations to float32. From the
first MLP on, the residual stream, the later layers' KV caches and the
logits ran in float32.

Plain Float bounds follow the activation dtype, as the scalar bounds in
mlx-lm's swiglu_oai do. The new tests check that a bfloat16 MLP block
keeps bfloat16, and that the whole model, with and without affine
quantization, keeps bfloat16 in the prefill, in a decode step and in the
keys of each layer's cache.
…explore#734)

A hard reasoning budget ends the span with the model's declared
budgetTransition, or with ReasoningBudgetTransition.immediate when it
declares none. Only QwenReasoningProtocol.qwen3 declared one, so every
other reasoning model relied on an untested fallback.

Measure the fallback and declare it where it holds. Muse Glimmer answers
the user after a forced <|eom|>: over 20 cuts it never resumed reasoning
and never ended the turn, while forcing an answer header instead pushed
scratch work into the user-visible answer. Qwen3.5 answers after a bare
</think> just as well as with Qwen3's early-stop text, and far better
than unbounded reasoning, which runs past the generation limit.

Express a validated transition as a delta on one protocol definition.
ReasoningConfig.declaringBudgetTransition(_:) returns a copy that adds
the transition, so QwenReasoningProtocol.qwen3 and .qwen35 both derive
from .tagged and a new OnyxReasoningProtocol.glimmer derives from
.frames. Delimiters keep a single definition, a family adapter restates
only what it measured, and a later model cannot inherit a transition by
sharing the control vocabulary. A test asserts the transition is the
only difference between a family and its base protocol.

Mellum and DeepSeek-R1 distills were measured too and are deliberately
left undeclared: .immediate is measurably worse for them than ending the
span with text, so they need their own evidence before they get a
declaration.

Developed with Filo assistance.
…l-explore#733)

Add optional logitSampler: and logitProcessor: parameters to
GuidedGenerationLoop.run. Nil keeps greedy sampling. The processor gets
the same lifecycle calls as in TokenIterator, and a sampler that picks
a token the grammar excludes throws instead of ending the run.
On Apple silicon with neural accelerators (M5 and later) MLX runs float32
matmuls as TF32 unless MLX_ENABLE_TF32=0, and five tests fail there with
default settings.

- HadamardQuantizedTests (2 tests), EmbeddingGemmaMaskTests G7 and
  LFM2DSparkMetalTests.rotatingHybridCacheMatchesGreedyAcrossWindow use
  MatmulPrecision.tolerance: the float32 bound is unchanged, the reduced
  bound applies only where the probe measures TF32.
- EvalTests speculative log-probability test runs on the CPU, which pins
  IEEE float32: it compares top-k order exactly, and TF32 reorders
  near-ties.
Nothing in SightRoll uses DFlash2, and upstream's Qwen 3.5/3.8 MTP now
drafts for both the text and vision models. Remove the DFlash2 drafter,
its factory, registration, speculative iterator, the generate and
generateTokens overloads that take a DFlash2 drafter, and
SameInputProjectionStacking. Qwen35.swift and Qwen3Next.swift return to
the upstream merge-base versions; the verify pass, rope-in-trace segments
and stacked projections existed only for DFlash2.

QWEN38_INTEGRATION.md described the fork's Qwen 3.8 and DFlash2 work;
Qwen 3.8 has been upstream's since the 2026-10-23 sync. The last fork
commit carrying DFlash2 is tagged fork/dflash2-last-20261125.
Conflict resolutions reuse the 2026-11-25 main-based merge (d22adec) minus the six upstream commits after 3.33.0. The fork's .github is kept.
- StopStringTests handles the Generation.reasoning and .steering cases.
- UnreadCheckpointTowersTests checks that a Gemma 4 VLM with an
  audio_config still reads and loads its audio tower under ml-explore#711's
  component skipping.
- GatedDeltaTests: the near-one decay bound no longer depends on TF32.
  The 1.4e-3 drift comes from the chunked NAX kernel in both TF32
  regimes, so MLX_ENABLE_TF32=0 failed the 1e-3 IEEE bound on M5;
  a lost decay drifts 1.2e-1.
GrammarTokenizer gains init(vocab:vocabType:stopTokenIds:), which validates the set (non-empty, in range, unique) and registers each id with xgrammar, so the grammar masks all of them until it can terminate. The single-EOS init delegates to it. GuidedGenerationLoop adds the registered ids to its stop set and treats any other stop id sampled before the grammar can terminate as prematureEOS instead of a successful stop.
GrammarConstraint(tokenizer:jsonSchema:) gains a format: JSONSchemaFormat parameter (anyWhitespace, indent, separators, strictMode), passed through the new xg_compile_json_schema_with_format shim entry point to XGrammar's CompileJSONSchema. The default is XGrammar's defaults, the grammar this init compiled before. JSONSchemaFormat.compact gives single-line JSON with no whitespace.
…rim back) (ml-explore#716)

* Restore a prompt checkpoint when a cache cannot trim back

Reasoning templates such as Mellum 2.1 and Qwen3 drop the reasoning of
past replies when they render the next prompt. The new prompt then
diverges right after the previous prompt's assistant header, or earlier
when that prompt ended with a prefilled reasoning block (thinking off).
Reusing the cache means rewinding the whole previous reply. A sliding
window that has wrapped, or recurrent state, cannot trim that far, so
ChatSession rebuilt the cache and every follow-up reported 0 cached
prompt tokens.

Approach

mlx-lm reuses an untrimmable cache only through an exact-prefix
snapshot, taken at segment boundaries such as the start of the
assistant tail. vLLM lets each cache type answer which prefix it can
restore, and splits prefill at those boundaries so the state exists
there. This change follows the same idea: keep one checkpoint of the
cache at the end of the prompt a later render keeps, and prefer, in
order, a trim that reaches the common prefix, a restore of that
checkpoint, then a rebuild.

Design

- KVCacheStorage.Checkpoint is a value. checkpoint() copies only the
  entries a trim may not return (!isTrimmable(after: .max): wrapping
  windows, recurrent state). restore(_:) trims the other entries and
  puts back copies of the copies, so it can be restored again. It
  changes nothing and returns false when it cannot restore. The storage
  keeps no checkpoint state of its own.
- TokenIterator(checkpointAt:) pauses prefill at a position, records
  prefillCheckpoint (cache checkpoint plus carried model state), then
  prefills the rest. The head goes through a new prefill-only
  LanguageModel.prefill(_:into:state:parameters:).
  PrefillParameters.pass(after:of:) keeps progress and prefix reports
  as one prefill. The iterator still owns the whole input, so timing,
  prompt counts and logit processors see the full prompt.
- PromptCacheReuseDecision gains .restoreCheckpoint(prefixLength:),
  decided by a new RestoreCheckpointRule.
  RewindToCommonPrefixRule now declines instead of returning .rebuild,
  and the policy's fallback still rebuilds. A restore also returns the
  carried model state, which a trim cannot. Like a trim, a refused
  restore is downgraded to .rebuild before prefilling.
- ChatSession checkpoints only turns that answer a user message, since
  templates drop reasoning from every reply after it. The checkpoint
  sits before any prefilled reasoning block and before the token the
  iterator samples from. ReasoningConfig.prefilledBlock finds the block
  and replaces the old prefilledReasoningStartDelimiter scan. The
  checkpoint is used only while the token ledger still starts with its
  tokens and the storage can restore it.

Costs and limits

Memory is one copy of each window or recurrent entry per session,
bounded by window and state size. Models whose caches all trim take
no checkpoint and run no extra forward. Sessions with a draft cache,
and inputs with media or an attention mask, take no checkpoint and keep
the previous behavior.

* Bound prompt checkpoints to the state a trim cannot restore

The first version copied whole top-level entries and probed
isTrimmable(after: .max). A variance-normalized tail overflowed on that
probe, and a CacheList kept its global attention history next to the
recurrent state. Automatic splitting also overrode an explicit unchunked
prefill.

Copy leaves instead. Rotating and recurrent state is snapshotted, global
attention is trimmed in place, and a variance-normalized cache keeps only
its raw tile after that compression has run. One asyncEval materializes
the copies so an oversized prefill buffer is not pinned. Explicit
unchunked and remainder schedules stay one forward.

Restore still requires an exact token prefix. The checkpoint reproduces
that prefix; it does not change the model's answers.

* Report prompt checkpoint memory in cache status

* Keep checkpoints across append-only turns and count batch metadata

* Size the checkpoint numerics test for TF32 matmuls

testRestoredMellumAndRecurrentQwenMatchFreshPrefill compares a restored
checkpoint with a cold prefill whose chunk boundaries differ, at 1e-4
relative. On Apple silicon with neural accelerators (M5 and later) MLX runs
float32 matmuls as TF32, and the float32 cases reach 1.2e-4 (Mellum) and
2.9e-4 (Qwen 3.5). With MLX_ENABLE_TF32=0 they measure 3e-7, and the test
passes unchanged.

The float32 bound now comes from MatmulPrecision.tolerance (ml-explore#802): 1e-4
where float32 is IEEE, 1e-3 where the probe measures TF32. The exact
restore-against-replay checks (atol 0) and the bfloat16 bound are unchanged;
both pass under TF32.

* Compare the EXIF orientation test's renders within a tolerance

imagesTurnUprightByTheirExifOrientationOnce renders one JPEG through two
paths, orienting it either in EmbeddingGemma2ImageProcessor.prepared or in
the decoder, and required the two pixel arrays to be exactly equal. The
paths decode and resample at different stages, so a different GPU or
decoder can round them apart: the CI runner failed orientation 4 while it
passes locally and on main.

Compare the maximum difference against 0.05 instead. Pixels are in 0...1,
and a wrong orientation moves the blue square over red, a difference near
1: forcing the mirrored orientation in prepared fails all seven non-upright
cases at this bound.

* Keep a checkpoint before the latest reply to tool results

A checkpoint was taken only for a turn that answers a user message, so a
tool loop kept the one before its first reply. A Qwen template renders
the call in a reply differently from how the model wrote it, with its
arguments sorted by name and its whitespace canonical. Each tool step
after a call that did not render back exactly therefore restored that
first checkpoint and prefilled every tool result since. vLLM, SGLang
and llama.cpp save recurrent state along the prompt and resume from the
last state saved before the mismatch.

Keep two checkpoints:

- `turn`, before the reply to the last user message, as before. A user
  turn keeps it until a prompt rewrites the turn.
- `step`, before the latest reply to tool results. Every tool step moves
  it, because the next step rewrites the call this one makes. A new user
  turn checkpoint drops it.

A turn restores the longest checkpoint the new prompt starts with, and
a checkpoint the new token ledger no longer starts with is dropped. A
user turn after a tool loop still resumes before its first reply, since
the template drops the reasoning of every reply after the last user
message. `KVCacheStatus.checkpoint` reports the longest prefix and the
memory of both. The cost is a second copy of the window and recurrent
state for a session in a tool loop.

`QwenReasoningTemplateTests` still expected a mismatching Qwen 3.8
continuation to rebuild, and one prepare per turn, which a checkpoint
splits. Its scripted model now ends a pass at end-of-sequence, and the
mismatching variants check that the session prefills only the tokens
after the last match: the first step from before the first reply, the
next from before the latest one. Without the step checkpoint that check
fails for reordered arguments, non-canonical whitespace and an implicit
reasoning end.

(cherry picked from commit 4daac23)
…xplore#813)

With use_bidirectional_attention: "vision" (31B, 26B-A4B, 12B unified),
the soft tokens of one image attend to each other in both directions.
Once the cache held tokens, the attention mask spanned cached + new keys
but the token types covered only the new tokens. The overlay's length
check failed and it returned the causal mask, so image tokens in a warm
prefill attended only causally among themselves. No error was raised;
the output was just different.

The overlay now gives cached keys block id -1 and matches blocks over the
whole key axis. It takes the cached length from the mask, since a
rotating cache can present fewer rows than its offset. The .causal and
.none base masks use the cache offset. This holds only when the cache
does not end inside an image, which prepare now documents.

Gemma4 and Gemma4Unified conform to PreparedInputSplitting. A split
keeps the images whose placeholder runs lie in the suffix (Gemma4Unified
also slices their position ids), so ChatSession can reuse the cache when
a later turn adds an image. It returns nil for video, audio, a padding
mask, a cut inside an image, or a payload that does not hold one image
per placeholder run.

Unit tests compare warm and cold prefill over every suffix position on
tiny models, with and without the flag, and check the mask on plain and
rotating caches. A cache-gated integration test does the same at the
last position on gemma-4-31b, gemma-4-12B (unified) and gemma-4-e2b
(control), bounded by the drift of a text-only split.

AI usage: Claude Opus 5.5 wrote the code, tests and this
message from a bug report, and ran the unit, integration and DocC
checks.

Co-authored-by: Jean-Matthieu Schaffhauser <jeanmatthieu@apple.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6759555)
Two fork patches had no covering test: the E2B/E4B/12B assistant entries in MTPDrafterRegistry and ModelContext.generationConfig, which the catalog kit reads.
Upstream's validateCompatibility (ml-explore#581, in 3.33.0) refuses a target whose sliding window is wider than the drafter's, and every MTP entry point (MTPSpeculativeTokenIterator, ChatSession) validates first. The fork's else branch for a sliding KV wider than the drafter window can no longer run, so Gemma4Assistant.swift returns to 3.33.0.
With core v0.32.5 the chunked NAX kernel drifts 9.2e-7 under MLX_ENABLE_TF32=0 (1.4e-3 with TF32 on, as before), so upstream's MatmulPrecision bound holds in both regimes and the fork's flat 1e-2 is no longer needed.
@Satchitananda
Satchitananda marked this pull request as ready for review November 27, 2026 05:22
@Satchitananda
Satchitananda merged commit 13e968f into main Nov 27, 2026
2 checks passed
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.