Skip to content

feat: LFM2.5 MoE (lfm2_moe / LFM2.5-8B-A1B) inference support - #64

Merged
Brooooooklyn merged 51 commits into
mainfrom
feat/lfm2-moe
Jun 2, 2026
Merged

Brooooooklyn merged 51 commits into
mainfrom
feat/lfm2-moe

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds inference support for the LFM2.5 MoE variant (model_type: "lfm2_moe", e.g. LiquidAI/LFM2.5-8B-A1B), which previously failed to load with Unsupported model_type "lfm2_moe".

The MoE architecture is identical to dense LFM2.5 except the per-layer FFN: the first num_dense_layers layers use a dense SwiGLU MLP; every layer after uses a sparse top-k MoE block. Implemented by extending the existing lfm2 module (no new model class — lfm2_moe routes to the same Lfm2Model), so the conv+attention backbone, RMSNorms, caches, paged adapter, and all chat/session/streaming machinery are reused unchanged.

  • Rust core (crates/mlx-core/src/models/lfm2/): optional MoE config fields + is_moe_layer; new sparse_moe.rs (Lfm2SparseMoeBlock); decoder_layer.rs FeedForward { Dense(MLP), Moe(..) } enum; persistence expert-stacking, router gate + expert_bias, and quantized-expert loading (MXFP8/MXFP4/NVFP4) reusing the qwen3_5_moe SwitchGLU/quant builders.
  • Routing mirrors mlx-lm/mlx_lm/models/lfm2_moe.py exactly: softmax over experts → add expert_bias (post-softmax, pre-top-k) → top-4 → scores gathered from the biased gates → norm_topk_prob renormalize → weighted sum. No shared expert, no routed_scaling_factor.
  • Fail-loud loading: partial/mixed quantized checkpoints are rejected (complete .weight+.scales groups required; quant detection keys on any projection's .scales); use_expert_bias=false is honored even if a stale expert_bias tensor is present.
  • Tokenizer: the chat-template renderer now neutralizes the HF Jinja {% generation %}/{% endgeneration %} tags (region-aware: skips {{ }}, {# #}, {% raw %}) that LFM2.5-8B-A1B's chat_template.jinja uses — previously this aborted chatSessionStart. Fixes any model using these tags.
  • TypeScript: lfm2_moe added to the loader (ModelType, SUPPORTED_MODEL_TYPES, loadModel → Lfm2Model); lfm2.5-8b-a1b entry added to LFM2_CONFIGS.

Quantized loading (affine, end-to-end tested)

A standard mlx_lm.convert --quantize checkpoint quantizes the embedding + all linears (the model's own quant_predicate does so), not just the MoE experts — which the original loader didn't cover, so a fully quantized checkpoint failed at the embedding. Commits 32f97e8, 181bd5a, 015aa4c, 6bf94fe add affine quantized loading for the non-MoE tensors (embedding, attention q/k/v/o, conv in/out, dense-MLP), make non-affine non-MoE tensors fail loud, correct the cache-limit weight accounting to include the dense dequant copies a quantized embedding / dense-MLP leave resident, and close a w1/w2/w3 quant-alias normalization hole.

Known limitation (documented in code): under this minimal affine path a quantized embedding (and the tied lm_head it feeds) resides as a dense bf16 table — no embedding memory savings; mxfp4/mxfp8/nvfp4 for non-MoE tensors fails loud. Full per-tensor savings + non-affine modes for non-MoE tensors require moving the lfm2 modules to a quant-capable type (deferred fast-follow). The MoE experts + router gate already support all four quant modes.

Test Plan

  • yarn build:native (regenerates index.d.cts)
  • cargo test -p mlx-core — new sparse_moe unit tests (incl. bias-flips-top-k, no-renorm), persistence validation tests (partial-quant rejection, stale-bias ignore, non-MoE quant groups, w1/w2/w3 alias, weight_bytes accounting), and tokenizer region-aware tests pass. The only failures are pre-existing f32 Metal-tolerance / random-weight equivalence tests (banded_attention_matches_reference_f32, two attention_vjp_finite_diff_f32_*, utils::functional equivalence) — confirmed failing identically on main, unrelated to this change.
  • cargo clippy --all-targets -- -D warnings clean; cargo fmt --check clean
  • Full TS suite (vp test) — 1245 passed; yarn typecheck clean
  • End-to-end greedy parity vs mlx-lm on the real LiquidAI/LFM2.5-8B-A1B (bf16): identical 24-token prompt render and token-for-token match for 73/80 generated tokens (lone divergence is a bf16 greedy tie-break that re-converges) → routing is numerically correct.
  • Quantized path end-to-end tested (affine) — converted a 4-bit affine lfm2_moe checkpoint with mlx_lm.convert --quantize and load-tested it through Lfm2Model: it loads (no embedding shape-mismatch), produces coherent output, and matches mlx-lm greedy for a 26-token prefix (divergence = benign tie-break). MXFP4/MXFP8/NVFP4 for non-MoE tensors remains fail-loud (deferred); MoE experts/gate support all modes.

Reviewed

Multiple rounds of Codex adversarial review across the bf16 routing core and the quantized-loading commits; all findings — partial-quant fail-loud, use_expert_bias honoring, single-sentinel quant detection, region-aware tag scanner, cache-accounting undercount (embedding + pure-dense + packed-retained dense-MLP), and w1/w2/w3 quant-alias normalization — fixed and re-verified.

🤖 Generated with Claude Code


Note

High Risk
Large changes to model conversion, quantization predicates, and MoE/compiled inference paths; mistakes could produce unloadable checkpoints or wrong generation, though heavily test-covered.

Overview
Adds end-to-end support for lfm2_moe (LFM2.5 MoE): model detection tests, MoE config fields, a sparse top-k Lfm2SparseMoeBlock, and FeedForward { Dense | Moe } in decoder layers. Attention and conv projections move to mode-aware LinearProj so affine/mxfp/nvfp quantization can apply outside MoE experts.

Convert pipeline (convert.rs): New sanitize_lfm2_moe (HF w1/w2/w3 → gate/up/down, conv transpose, expert stacking into switch_mlp, tied lm_head drop, loud rejects for pre-quantized per-expert sources). Removes the prior affine-only gate for LFM2 mxfp/nvfp on non-MoE linears. embed_quantizable lets lfm2 families quantize embeddings; feed_forward.gate is an 8-bit affine router override; depthwise conv.conv.weight stays unquantized. Quantizer skips already-quantized or non-float weights to avoid double-quant.

Compiled path: Large compiled_parity_test suite compares native Rust forwards to C++ probes (attn, conv, dense/MoE decode, compiled-vs-eager MoE, A→B compile-epoch invalidation).

Risk: Touches weight conversion, quantization rules, and a new MoE routing path—incorrect sanitize/stacking or compile caching would corrupt checkpoints or logits; mitigated by extensive unit/integration tests.

Reviewed by Cursor Bugbot for commit d619ee7. Bugbot is set up for automated code reviews on this repo. Configure here.

Brooooooklyn and others added 5 commits May 29, 2026 16:10
Extend the existing lfm2 module with a per-layer feed-forward branch so
`model_type: "lfm2_moe"` routes to the same Lfm2Model: dense SwiGLU MLP
for the first `num_dense_layers` layers, sparse top-k MoE for the rest.
The conv+attention backbone, RMSNorms, caches, paged adapter, and all
chat/session/streaming machinery are reused unchanged.

The new `Lfm2SparseMoeBlock` mirrors mlx-lm `lfm2_moe.py` exactly:
softmax over experts -> add `expert_bias` after softmax and before top-k
-> argpartition tail-k -> gather post-bias scores -> optional
`/(sum+1e-20)` renorm -> switch_mlp -> weighted sum. No shared expert /
shared_expert_gate / routed_scaling_factor. Dense-in-MoE layers use
`intermediate_size` directly (no computed_ff_dim shrink); experts use
`moe_intermediate_size`. Expert stacking happens after FP8 dequant with
no re-quant; `expert_bias` stays f32.

Supports bf16/f16 and quantized experts (MXFP8/MXFP4/NVFP4/affine) by
reusing qwen3_5_moe's SwitchGLU/QuantizedSwitchLinear/quant builders and
the shared quant_dispatch PLQ machinery. The router-gate PLQ is resolved
via a direct per_layer_quant lookup since effective_plq_for hardcodes the
`.mlp.gate` prefix.

- config.rs: 7 optional MoE fields + is_moe/is_moe_layer + tests
- sparse_moe.rs: Lfm2SparseMoeBlock + inline gate math + unit tests
  (zero-bias parity, bias-flips-top-k, norm_topk_prob=false, >=64-index
  gather-sort branch) with hand-computed references
- decoder_layer.rs: FeedForward{Dense,Moe} enum + per-layer dispatch
- persistence.rs: expert rename+stacking, MoE config parse, dense/MoE
  apply + validate branches, quant builders, quant-config threading
- mod.rs: pub mod sparse_moe
- model.rs: struct-literal updates; dense_mlp_mut() in paged test
- tests/lfm2_moe_session.rs: env-gated on MLX_TEST_LFM2_MOE_MODEL_PATH

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…=false

Two load-time robustness fixes for LFM2.5 MoE, both upholding the
fail-loud-on-inconsistent-checkpoint principle:

Finding 1 (high): a truncated/mixed quantized checkpoint missing one
half of a switch-linear pair (`.weight` xor `.scales`) previously slipped
through validation (`has_proj` accepted EITHER half) and then either
loaded a lone plain `.weight` or left random init — corrupting
generations instead of erroring. Validation now treats each MoE
projection (router gate + stacked gate/up/down) as a COMPLETE group: a
plain layer needs `.weight`; a quantized layer (detected via
`switch_mlp.gate_proj.scales`, same predicate as the apply path) needs
the full `.weight`+`.scales` pair on every projection, gate included. The
apply path's quantized branch now `ok_or_else(...)?`s every builder
instead of falling back to plain/random init, so a builder that can't
consume the group fails loud.

Finding 2 (medium): the loader unconditionally applied a checkpoint
`expert_bias` whenever the tensor existed, so a version-skewed checkpoint
with a stale bias plus `use_expert_bias=false` would still bias routing
(the block leaves `expert_bias = None` and `forward` adds bias whenever
Some). `set_expert_bias` is now gated on `config.use_expert_bias`.

Tests (all pass): loader ignores stale bias when disabled / applies it
when enabled; validation accepts complete bf16 and complete quantized
groups, rejects a lone `.scales` (missing `.weight`) and a quantized
layer with a scales-less projection. Scoped entirely to models/lfm2/;
qwen3_5_moe and the verified bf16 routing math are untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Add 'lfm2_moe' to ModelType union and SUPPORTED_MODEL_TYPES set
- Add case 'lfm2_moe' in loadModel switch, routing to Lfm2Model.load()
  (same native class as 'lfm2'; detectModelType passes through unchanged)
- Add 'lfm2.5-8b-a1b' entry to LFM2_CONFIGS with exact checkpoint values
  for LiquidAI/LFM2.5-8B-A1B (vocabSize 128k, 24 layers, MoE fields)
- Patch 'lfm2.5-1.2b-thinking' to supply normTopkProb/useExpertBias (now
  required by the NAPI-derived Lfm2Config after the Rust MoE fields landed)
- Add loader detection test in __test__/models/lfm2-moe-detection.test.ts

Co-Authored-By: Claude Opus 4.8 <[email protected]>
LFM2.5-8B-A1B's chat_template.jinja uses the HuggingFace `{% generation %}`
/ `{% endgeneration %}` Jinja statement tags to mark assistant-generated
token spans (for return_assistant_tokens_mask during training). minijinja
does not implement these statement tags, so render_chat_template_jinja2
aborted at parse time with `unknown statement generation`, blocking
Lfm2Model.chatSessionStart before any forward pass.

These tags render their body verbatim and never change the output string,
so rewriting them to no-op `set` statements is byte-identical to HF's
renderer (preserving numerical parity with mlx-lm). The new
neutralize_generation_tags scanner rewrites only a bare-keyword
`generation`/`endgeneration` statement tag, preserving the exact
leading/trailing whitespace-control dashes, and never touches the
`add_generation_prompt` variable or any identifier merely containing
"generation". Hand-rolled (no regex dep added).

Tests: transparency (tags present == tags removed by hand),
add_generation_prompt untouched, all dash/whitespace variants + negative
cases, and an end-to-end render of the real LFM2.5 template ending with
`<|im_start|>assistant`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… region-aware

Finding A (high): MoE quant detection keyed on the single sentinel
`switch_mlp.gate_proj.scales`. A truncated/mixed checkpoint missing exactly
that one tensor but still carrying packed uint32 `.weight`s plus other
`.scales` misclassified DENSE and silently loaded packed weights through the
bf16 SwitchLinear setters (corrupt output). Add shared `moe_layer_is_quantized`
(any router/expert projection's `.scales`) used by BOTH `apply_weights` and
`validate_mandatory_weights` so they cannot diverge; the dense branch now fails
loud on any stray `.scales`.

Finding B (medium): `neutralize_generation_tags` walked raw bytes with no
state for `{{ ... }}` expressions, `{# ... #}` comments, or
`{% raw %}...{% endraw %}` blocks, so literal `{% generation %}` text inside
them was rewritten, breaking the byte-identical guarantee. Make the scan
region-aware: skip those three regions (dash/whitespace variants of raw/endraw
handled like the existing matcher) and only rewrite real top-level statement
tags. Dependency-free, no regex.

Tests: reject a quantized layer missing only gate_proj.scales; reject a dense
layer with a stray lone .scales; preserve literal generation tags inside
expressions/raw/comments byte-identically while still neutralizing real
top-level tags. Existing lfm2/qwen3_5_moe/tokenizer tests and the real
LFM2.5-8B-A1B template test still pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bfb681ab-f8d4-41a2-9db0-d453bdadfbc3

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/lfm2-moe

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread crates/mlx-core/src/tokenizer.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0a10f32356

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +301 to +305
let clean_key = if clean_key.contains("feed_forward") {
clean_key
.replace("w1.weight", "gate_proj.weight")
.replace("w2.weight", "down_proj.weight")
.replace("w3.weight", "up_proj.weight")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rename quantized expert sidecars before stacking

When loading a quantized lfm2_moe checkpoint that still uses HF per-expert names, this only rewrites the .weight keys (w1.weight/w2.weight/w3.weight) while leaving their .scales/.biases sidecars under the old w1/w2/w3 names. The later quantization detection only scans switch_mlp.*.scales, so those layers can be classified as bf16 and have packed expert weights installed through the dense setters, producing corrupted output instead of the intended fail-loud behavior. Apply the same projection rename to quantization sidecars before stacking/validation.

Useful? React with 👍 / 👎.

Brooooooklyn and others added 4 commits May 30, 2026 00:08
A fully quantized `mlx_lm.convert --quantize` checkpoint quantizes ALL
linears plus the embedding, not just the MoE router gate + expert
switch_mlp. Loading such an lfm2_moe (or dense lfm2) checkpoint failed
with `Embedding weight shape mismatch: expected [128000, 2048], got
[128000, 256]` because the embedding, attention q/k/v/out_proj, conv
in/out_proj, dense-MLP gate/up/down_proj, and lm_head were all loaded
through plain bf16 setters that reject packed-uint32 quantized tensors.

Wire those NON-MoE tensors through `nn::Linear::load_quantized` /
`nn::Embedding::load_quantized` when a `{base}.scales` companion is
present, keyed per-tensor (each non-MoE linear is quantized
independently), else fall back to the plain bf16 load. Resolution uses
`effective_plq_for` against the top-level affine default + any per-layer
override. The embedding loader pre-dequantizes the full table, so the
tied lm_head matmul keeps reading a dense `get_weight()` unchanged.

SCOPE: `nn::Linear`/`nn::Embedding::load_quantized` are affine-only and
the canonical `--quantize` default IS affine, so only affine is
supported for non-MoE tensors. If a non-MoE tensor ships `.scales` but
its resolved mode is non-affine (mxfp4/mxfp8/nvfp4), the loader now FAILS
LOUD naming the tensor rather than feeding a non-affine packed weight
into the affine dequant kernel and emitting garbage. The MoE router gate
+ expert switch_mlp path (all 4 modes) is untouched. The depthwise
`conv.conv.weight` is never quantized and stays bf16. Module field types
are unchanged; small `&mut Linear` accessors were added to
attention/short_conv and (additively, non-breaking) to the shared
`transformer/mlp.rs`.

Verified end-to-end on a real 4-bit affine lfm2-8b-a1b checkpoint: loads
without the embedding error, produces coherent greedy output, and
token-for-token matches the mlx-lm reference for a 26-token prefix before
a benign greedy tie-break divergence (` However` vs ` So`).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lization, tidy-ups

Follow-up to the affine-quant loading commit, addressing Codex review findings.

Cache-accounting undercount (high): the cache-limit coordinator sized the MLX
allocator cap from the naive packed-tensor sum, which undercounts a quantized
checkpoint's resident memory. A quantized + tied embedding pre-dequantizes a
full dense bf16 table (~vocab*hidden*2 bytes), and quantized dense-MLP
projections (first num_dense_layers) materialize dense copies via the legacy
MLP forward path — neither is visible in the packed sum, risking
overcommit/OOM when multiple models load. Factored the computation into a
testable `compute_weight_bytes` helper that starts from the packed sum and
conservatively adds the dense-dequant deltas for the quantized embedding and
quantized dense-MLP projections. Attention/conv quantized linears stay
packed-only (forward uses the quantized backend; get_weight is never read), so
no delta is added for them.

w1/w2/w3 quant-alias hole (medium): sanitize_weights renamed the dense-form
LFM2 FFN aliases (w1->gate_proj, w2->down_proj, w3->up_proj) only for `.weight`
keys, orphaning `.scales`/`.biases` companions of a quantized dense-form
checkpoint and silently flipping the loader to the bf16 path for a packed
weight. Extended the rename to all affine quant suffixes (.weight/.scales/
.biases), and validate_mandatory_weights now rejects any surviving
feed_forward.w{1,2,3}.{scales,biases} alias (fail loud on an unhandled alias).
Per-layer quant OVERRIDE keys never arrive under w{1,2,3} (dense lfm2 has no
quant_predicate; lfm2_moe only specializes feed_forward.gate), so the override
map needs no alias normalization — noted in code.

Tidy-ups: removed the dead set_{q,k,v,out}_proj_weight (Lfm2Attention) and
set_{in,out}_proj_weight (ShortConv) shims (zero callers after the *_mut
switch; verified across the crate); documented the 4-bit affine tolerance in
the dequant test; corrected the nn::Linear::load_quantized doc to say the
dequant graph is built eagerly (materializing lazily on first use) — comment
only, shared primitive behavior unchanged.

Documented residual limitation: a quantized embedding (and the tied lm_head it
feeds) resides as a dense bf16 table, so the embedding gets no memory savings
under this minimal affine path; full per-tensor savings / mxfp4/mxfp8/nvfp4 for
non-MoE tensors require the deferred quant-capable-module refactor.

Tests: 6 new mlx-core unit tests (3 cache-accounting, 3 alias normalization +
rejection); all 52 lfm2 lib tests pass. End-to-end: the existing 4-bit affine
lfm2.5-8b-a1b checkpoint still loads and generates coherently (Paris).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ckpoints

compute_weight_bytes derived the dense-MLP dequant byte delta from
config.num_dense_layers.unwrap_or(0). That is correct for MoE configs
(only the leading num_dense_layers layers are dense MLPs; the rest are
packed-resident MoE experts), but a PURE-DENSE lfm2 checkpoint has
num_dense_layers == None (a MoE-only field) while EVERY one of the
num_hidden_layers layers is a dense MLP. Affine-quantizing such a
checkpoint materializes a dense bf16 dequant copy per dense-MLP
projection via the legacy MLP get_weight() forward path, so the resident
footprint was undercounted for the whole class (e.g. lfm2.5-1.2b).

Derive the dense-MLP layer count as num_hidden_layers when !is_moe()
(all layers are dense MLPs) and num_dense_layers when is_moe(). The
per-layer dense-MLP dim selection (intermediate_size for dense-in-MoE,
computed_ff_dim() for pure-dense) is unchanged and already matches
decoder_layer.rs. Embedding-delta logic unchanged. Saturating/
conservative throughout.

Adds a regression test (pure-dense config: num_experts=None,
num_dense_layers=None, quantized layers.*.feed_forward.{gate,up,down}_proj
with .scales) asserting the counted total exceeds the packed-only sum by
the dense-MLP delta across ALL num_hidden_layers layers. Existing MoE
weight_bytes_* tests still pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nting

`Linear::load_quantized` retains the packed backend AND materializes the
dense `self.weight` (read by the legacy `MLP::forward` get_weight path),
so a quantized dense-MLP projection is resident as packed + dense. The
prior `compute_weight_bytes` added only `dense - packed` on top of the
packed baseline, netting to `dense` and undercounting by the retained
packed bytes for every quantized gate/up/down projection (pure-dense
checkpoints and MoE dense-prefix layers). Add the FULL dense size on top
of the baseline for dense-MLP; the embedding stays a replacement delta
(`Embedding::load_quantized` frees its packed tensors). Tighten both
dense-MLP weight_bytes tests to require `packed + full_dense` (the old
formula fails this bound).

Resolves the final Codex adversarial-review finding on the lfm2 quant
cache-accounting path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6bf94fed6e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/core/index.d.cts Outdated
Comment on lines +3474 to +3476
normTopkProb: boolean;
/** Add the learned per-expert bias to the post-softmax gates BEFORE top-k. */
useExpertBias: boolean;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make defaulted MoE booleans optional

When TypeScript users construct a dense Lfm2Config, these MoE-only/defaulted flags can legitimately be omitted (the Rust struct defaults both to true, and the other new MoE fields are optional). Publishing them as required here turns otherwise valid existing dense configs into TypeScript errors after this update, even though runtime loading still supports missing values. Please mark these as optional/boolean | undefined in the generated/public declaration, consistent with the serde defaults.

Useful? React with 👍 / 👎.

Brooooooklyn and others added 4 commits May 30, 2026 10:16
Add `mlx convert` support for LiquidAI LFM2 / LFM2-MoE models so our own
tool can convert the bf16 LFM2.5-8B-A1B to an affine-quantized checkpoint
that `Lfm2Model` loads.

New `sanitize_lfm2_moe` is inverse-consistent with the lfm2 loader's
`sanitize_weights`: keeps the on-disk `model.` prefix, renames
`feed_forward.{w1,w2,w3}` -> `{gate_proj,down_proj,up_proj}`, transposes
the depthwise short conv `[C,1,K]` -> `[C,K,1]`, stacks per-expert
projections into `feed_forward.switch_mlp.{proj}` of shape
`[num_experts, out, in]`, preserves `expert_bias` as f32, and drops the
tied `lm_head`.

Predicate updates (model-type-safe): `is_router_gate` now matches
`.feed_forward.gate` so the LFM2 router is quantized 8-bit affine, and
`should_quantize` explicitly skips `conv.conv.weight`.

Quantization is gated to affine only for lfm2/lfm2_moe: the non-MoE
loader path dequantizes through the affine-only `Linear::load_quantized`,
so mxfp4/mxfp8/nvfp4 (and --q-mxfp) are rejected with a clear message
until a quant-capable non-MoE loader lands.

CLI: auto-detect `model_type: lfm2_moe`/`lfm2` and document the new types.

Verified end-to-end: converted LFM2.5-8B-A1B to affine 4-bit (564
tensors, 4.9 GB) and loaded it with `Lfm2Model`; greedy generation
produces coherent output identifying Paris as the capital of France.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nears

Make lfm2's NON-MoE linears (attention q/k/v/out_proj, conv in/out_proj,
dense-MLP gate/up/down_proj) quant-capable for ALL modes (affine + mxfp4 /
mxfp8 / nvfp4) by REUSING qwen3_5's existing types — zero changes to shared
nn::Linear / nn::Embedding / transformer::MLP, and no changes to
qwen3_5 / qwen3_5_moe / gemma4. The embedding + lm_head stay on their
affine/dense path (out of scope; #1b).

- attention.rs / short_conv.rs: q/k/v/out_proj and conv in/out_proj fields
  switch from concrete `Linear` to `LinearProj` (Standard | Quantized). new()
  wraps `LinearProj::Standard(Linear::new(..))`; the `*_proj_mut()` accessors
  now expose `&mut LinearProj`. Conv layer biases are threaded across both
  arms (a quantized projection uses `QuantizedLinear::set_bias`).
- decoder_layer.rs: `FeedForward::Dense(MLP)` → `FeedForward::Dense(MLPVariant)`
  (Standard default; quantized arm = 3× QuantizedLinear + swiglu, packed-only).
- persistence.rs: replace the affine-only `load_linear_affine_or_bf16` with a
  mode-dispatching `load_linear_proj_quantized_or_bf16` +
  `load_dense_mlp_variant` (resolve plq via `effective_plq_for`, dispatch to
  the matching `try_build_*_quantized_linear`). lm_head keeps a dedicated
  affine-only loader. `compute_weight_bytes` drops the dense-MLP dense-residency
  adder (quantized dense-MLP is now packed-only resident like attn/conv); the
  embedding delta is kept.
- convert.rs: remove the lfm2 affine-only gate so `--q-mxfp` / `--q-mode
  {mxfp4,mxfp8,nvfp4}` emit quantized non-MoE linears; the embedding/lm_head
  stay excluded via `should_quantize`.

Tests: extend the non-MoE loader tests to mxfp8 (+ standard-arm), update the
weight_bytes dense-MLP tests to assert packed-only residency. All lfm2 loader/
validation tests green; cargo test -p mlx-core passes (only the documented
pre-existing f32 Metal banded-attn / attention-vjp flakies fail).

End-to-end: converted the local LFM2.5-8B-A1B bf16 checkpoint to mxfp8 via the
CLI (`-q --q-mxfp --q-bits 8`) — mxfp8 experts + attn/conv/dense-MLP, bf16
embedding — loaded with Lfm2Model and got coherent greedy output ("Paris is the
capital of France."). The prior affine 4-bit checkpoint still loads.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…r tied head)

lfm2's quantized token embedding now stays PACKED-resident instead of being
pre-dequantized into a full dense bf16 table — real memory savings (~254 MB on
LFM2.5-8B-A1B) with mode-awareness (affine + mxfp4/mxfp8/nvfp4) and a correct
tied-head logits path.

nn::Embedding (additive):
- New `QuantizedEmbeddingBackend` + `quantized_packed` field.
- `load_quantized_packed(weight, scales, biases, group_size, bits, mode)` retains
  the packed tensors AS-IS (no dequant); `forward` gather-then-dequantizes only
  the looked-up rows (matching MLX's QuantizedEmbedding.__call__); `as_linear`
  runs `mlx_quantized_matmul` (transpose) for the tied lm_head and falls back to
  `x @ weight^T` for a dense embedding (numerically identical to the prior
  tied-head matmul). Legacy `load_quantized`/`get_weight`/`load_weight` untouched
  — qwen3_5/qwen3_5_moe/gemma4 tied heads keep their eager-dense behavior.

lfm2 loader/model:
- `load_embedding_affine_or_bf16` now installs the packed backend for ALL modes
  (removed the affine-only rejection); plain bf16 → `load_weight`.
- All three tied-head logits sites (flat forward, paged prefill, paged decode)
  route through `embed_tokens.as_linear(hidden)`.
- `compute_weight_bytes` drops the embedding dense-delta — every quantized lfm2
  tensor class is now packed-only resident, so resident footprint = packed sum.

convert: `should_quantize` gains an `embed_quantizable` flag (true for
lfm2/lfm2_moe only) so our converter quantizes the embedding; qwen3_5/gemma4
behavior unchanged. Tied lm_head is dropped at sanitize, never quantized.

Tests: embedding gather-dequant vs dequant-then-gather (affine + mxfp8),
as_linear vs dense matmul (packed + dense-equivalence), packed-only weight_bytes,
embed_quantizable gating. cargo test green (known-flaky f32 Metal/random-weight
tests excluded). E2E: mxfp8 + affine-4bit checkpoints with quantized embedding
both load coherent ("Paris"); weight_bytes 8.37→8.13 GB (mxfp8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…pert quant

Two Codex findings on the quantized lfm2 load path:

[high] Packed embedding kept the full random [vocab,hidden] table.
load_quantized_packed installed the packed backend but never touched
self.weight, leaving the full-shape random_normal graph from new() as a
latent landmine: get_weight() returned stale random data for a packed
embedding and any eval could materialize ~vocab*hidden*2 bytes of garbage.
Now replace self.weight with a [1,1] placeholder (drops the full-shape
graph) and make get_weight()/weight() dequantize the full table on demand
from the packed backend — correct data, materialized only if a caller
actually evals it (the production logits path uses as_linear and never
does). Regression test asserts the placeholder is [1,1] and get_weight()
returns the correct [vocab,hidden] dequantized table.

[medium] Orphaned per-expert quant companions loaded silently wrong.
sanitize_weights stacks only experts.{e}.{proj}.weight into switch_mlp.*;
the matching .scales/.biases have no stacking path. A per-expert
pre-quantized checkpoint would stack packed uint32 weights, misclassify the
layer as dense (no switch_mlp.*.scales), and install packed weights via the
bf16 setters as garbage. validate_mandatory_weights now fails loud naming
any surviving feed_forward.experts.*.{scales,biases}. Regression test added.

Also correct the now-stale compute_weight_bytes residency comment in
load_from_dir: after the packed embedding (#1b) the resident footprint is
exactly the packed-tensor sum with no dense dequant deltas.

cargo test -p mlx-core: embedding 5/5, lfm2 persistence 24/24; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9a67a945be

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

let up_base = format!("{prefix}.up_proj");
let down_base = format!("{prefix}.down_proj");

if params.contains_key(&format!("{gate_base}.scales")) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Detect quantized dense MLPs from any projection scale

When a dense LFM2 MLP checkpoint is truncated or mixed so up_proj.scales or down_proj.scales is present but gate_proj.scales is missing, this sentinel takes the plain bf16 branch and then installs the packed up_proj.weight/down_proj.weight through the dense setters. That silently produces corrupted MLP output instead of failing loud or loading the remaining quantized projections; use any of the three projection .scales keys for detection, as the MoE path now does.

Useful? React with 👍 / 👎.

Lay the build/FFI/dispatch scaffolding for a compiled C++ forward path for
lfm2_moe (modeled on the qwen3.5 compiled path), with ZERO runtime behavior
change — the model keeps running its Rust-native forward.

C++ (crates/mlx-sys/src/):
- mlx_lfm2_common.h: shared header; Lfm2MoeConfig POD for the future graph.
- mlx_lfm2_moe.cpp: inert extern "C" stubs — mlx_lfm2_get_model_id()/
  mlx_lfm2_weight_count() return 0, init/reset are no-ops, forward writes a
  null *output_logits sentinel. build.rs auto-globs the new .cpp.

FFI (mlx-sys/src/lib.rs): declarations for the five lfm2 entry points.

Rust (mlx-core lfm2/model.rs):
- LFM2_COMPILED_MODEL_ID_COUNTER + per-model `model_id` field (assigned in new()).
- Lfm2Inner::compiled_path_active() = (C++ active id == model_id); ALWAYS false
  in Phase 0 (stub returns 0). forward() probes it as an inert dispatch hook.

Deliberately deferred to Phase 1 (keeps Phase 0 truly inert): register_weights_
with_cpp. The compiled path shares qwen3.5's process-global g_weights() map under
identical key names, so registering lfm2 weights would clobber a co-loaded qwen
model. Weight registration lands with the real graph, guarded by model-id
ownership reconciliation (documented in mlx_lfm2_moe.cpp + the counter doc).

Verified: cargo build -p mlx-core OK; yarn build:native OK (.node links the new
C++); cargo clippy -p mlx-core -p mlx-sys -D warnings clean; fmt clean;
cargo test -p mlx-core models::lfm2 55/55.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c7fff58ad4

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2880 to +2883
let new_key = if key.contains("feed_forward") {
key.replace("w1.weight", "gate_proj.weight")
.replace("w2.weight", "down_proj.weight")
.replace("w3.weight", "up_proj.weight")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rename quantized LFM2 sidecars during conversion

When the converter is run on an already-quantized LFM2/LFM2-MoE source (or a re-conversion of quantized mlx-lm output), these replacements move only w1/w2/w3.weight to gate_proj/down_proj/up_proj.weight and leave the matching .scales/.biases under the old w* names. The sanitizer later explicitly tries to preserve pre-quantized groups, but the output will contain orphaned feed_forward.w*.scales sidecars; the LFM2 loader now rejects those aliases during validation, so the converted checkpoint fails to load instead of being usable. Apply the same rename to .scales and .biases here as the load-time sanitizer does.

Useful? React with 👍 / 👎.

…gated)

Implement the parity-critical novel C++ for the lfm2 compiled forward path —
the attention pure-fn and the dense SwiGLU MLP — and validate them in isolation
against the Rust-native single-layer forward. The full compiled forward is not
end-to-end runnable until ShortConv lands (Phase 2), so this component-parity
gate is how the hard math gets verified early.

C++ (mlx_lfm2_common.h):
- lfm2_attn_pure_fn: single-token decode attention. GQA, per-head q/k RMSNorm
  (none on V), neox RoPE base 1e6 over full head_dim, NO q-gating, NO proj bias,
  scale head_dim^-0.5, out_proj. dynamic_kv mode slices KV to [0..offset+1] +
  no mask (matches native decode). Reuses qwen35_common linear_proj/get_weight.
- lfm2_dense_mlp: down_proj(swiglu(gate_proj(x), up_proj(x))).

CORRECTNESS: RoPE is applied AFTER the transpose to [B,H,T,D] (position axis =
T), NOT on the pre-transpose [B,1,H,D] — roping pre-transpose assigns per-HEAD
positions and corrupts the rotation (caught by the probe: max_abs 0.106 -> pass).
The qwen35 attn_pure_fn template ropes pre-transpose; that ordering is NOT
directly copyable for lfm2, which ropes post-transpose (attention.rs:107,129).

Test-only probe FFI (mlx_lfm2_moe.cpp + lib.rs): mlx_lfm2_probe_attn_seq runs a
T-step decode sequence (so multi-key softmax + RoPE offset + qk-norm are
exercised, not a trivial single-key softmax); mlx_lfm2_probe_dense_mlp runs the
MLP. Each registers one layer into the shared g_weights() map, runs, clears.

Rust parity test (models/lfm2/compiled_parity_test.rs): both probes vs native
(Lfm2Attention over a shared KVCache; transformer::MLP), bf16, max_abs < 2e-2.
In the --lib test binary nothing else touches g_weights(), so it's race-free.

Gate still OFF: no weight registration / model-id ownership wired (Phase 2,
together with ShortConv + the first end-to-end dense-backbone parity gate).

Verified: cargo test models::lfm2 57/57 (2 new); clippy -D warnings clean; fmt
clean; yarn build:native OK (release addon links the new C++).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…robe

Add the depthwise-conv operator to the lfm2 compiled C++ forward path,
completing per-operator parity (attention, dense-MLP, ShortConv) ahead of
the Phase-2 decode-loop assembly. Compiled gate still OFF (inert).

- mlx_lfm2_common.h: `lfm2_conv_pure_fn` — single-token decode port of native
  `ShortConv::forward` (short_conv.rs) / lfm2.py: in_proj(+bias) -> split B,C,x
  -> Bx=B*x -> concat(conv_state, bx, axis=1) -> depthwise conv1d(groups=hidden,
  W[H,K,1]) -> C*conv_out -> out_proj(+bias). Conv-state cache [B, l_cache-1,
  hidden]; weight keys layers.{i}.conv.* incl. the doubled conv.conv.weight.
- mlx_lfm2_moe.cpp: `mlx_lfm2_probe_conv_seq` test probe (T-step decode threading
  the conv state), mirroring the attn / dense-mlp probes.
- compiled_parity_test.rs: two parity tests (conv_bias off/on) vs native
  `ShortConv` over a 4-step ArraysCache decode, bf16 max_abs < 2e-2.

Probe-registry safety (Codex adversarial-review): the probes are destructive on
the process-global g_weights() registry (clear also resets the active model id)
— the SAME registry the production compiled paths own under
COMPILED_WEIGHTS_RWLOCK, and qwen compiled tests share this --lib binary. All
probe tests now hold that write lock for the whole clear->store->run->clear
(replacing a module-local mutex), and the C++ probes document the caller
contract. Build-time symbol gating was rejected: mlx-sys compiles once
independent of mlx-core's test cfg (would break `cargo test --release`) and the
symbol is unreachable dead-code in the production addon.

Verified: cargo test models::lfm2::compiled_parity_test 4/4 (2 new); clippy
-D warnings clean; cargo fmt --check clean; yarn build:native OK.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 4 total unresolved issues (including 3 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 267dbb2. Configure here.

Comment thread crates/mlx-core/src/convert.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 267dbb25d6

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/convert.rs Outdated
Comment on lines +2949 to +2950
if v.dtype()? == DType::Float32 {
let converted = v.astype(target_dtype)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor target dtype for non-f32 LFM2 tensors

When converting LFM2 with this custom sanitizer, the generic dtype conversion has already been bypassed, so this f32-only cast leaves any existing bf16/f16 tensors unchanged even if the user requested a different --dtype (for example --dtype float32 on a bf16 checkpoint, or --dtype bfloat16 on an f16 checkpoint). The converted output can therefore silently ignore the requested dtype for most weights; this branch should cast every non-quantized tensor whose dtype() differs from target_dtype, not only Float32 inputs.

Useful? React with 👍 / 👎.

Brooooooklyn and others added 4 commits May 30, 2026 14:50
…ate OFF)

Wire the per-operator compiled pure-fns (attention, ShortConv, dense-MLP —
each individually parity-proven in fdb1ac2/267dbb2) into a single per-layer
`lfm2_decode_fn`. Still inert: `mlx_lfm2_get_model_id()` returns 0, no real
model registers weights — validated only by synthetic-weight probes.

- mlx_lfm2_common.h: `lfm2_attn_pure_fn_arr` — array-offset attention variant
  (fixed padded KV cache + per-step static additive mask + post-transpose RoPE
  + slice_update at the array offset), modeled on qwen35 `attn_for_compile`.
- mlx_lfm2_moe.cpp: file-globals `g_lfm2_config`/`g_lfm2_is_attn`
  (`g_lfm2_active_model_id` kept 0 — gate OFF); `lfm2_decode_fn` assembling
  operator_norm -> (attn|conv per is_attn) -> +res -> ffn_norm -> dense_mlp ->
  +res, final embedding_norm + tied head, uniform stride-2 cache layout;
  probes `mlx_lfm2_probe_attn_arr_seq` + `mlx_lfm2_probe_decode_seq` (synthetic
  [conv,attn,conv] dense model, run EAGERLY since compile() freezes topology).
- lib.rs: FFI decls for both probes (27-param decode probe, layer-indexed
  pointer arrays, null for the irrelevant op-kind per layer).
- compiled_parity_test.rs: `compiled_attn_arr_seq_matches_native` +
  `compiled_decode_seq_matches_native` vs a hand-assembled native
  [conv,attn,conv] stack (bf16 max_abs < 2e-2). All 6 parity tests green.

FFN is dense-only (Phase 2 scope): correct for the dense lfm2 backbone
(LFM2.5-1.2B), wrong for lfm2_moe sparse layers. Phase 2b-2's gate flip MUST
gate on `!config.is_moe()` until Phase 3 adds sparse-FFN dispatch — documented
at the dispatch site and flagged by Codex adversarial-review.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Foundational ownership reconciliation for the lfm2 compiled C++ path, ahead of
wiring production registration + the live decode dispatch. No behavior change:
nothing registers an lfm2 id yet, so compiled_path_active() stays false and the
native forward runs.

- lfm2/model.rs: draw model_id from the SHARED qwen3.5 QWEN35_MODEL_ID_COUNTER
  instead of a private LFM2_COMPILED_MODEL_ID_COUNTER (deleted). The compiled
  path keys ownership on ONE process-global atom shared with qwen3.5; two
  per-family counters both starting at 1 could mint equal ids and false-positive
  the id-equality gate, decoding the other family's weights. One counter makes
  every live id globally unique. Documents the hard invariant.
- mlx_lfm2_moe.cpp: mlx_lfm2_get_model_id() now reads the SHARED
  g_active_model_id atom (qwen35_common::g_active_model_id, the same one
  mlx_set_model_id writes), and mlx_lfm2_weight_count() returns the real shared
  mlx_weight_count(). Removed the vestigial file-local g_lfm2_active_model_id.
- qwen3_5/model.rs: promote DENSE_COMPILED_MUTEX to pub(crate) and rename it
  COMPILED_LIFECYCLE_MUTEX — it must serialize the compiled lifecycle across
  model FAMILIES (qwen3.5 + lfm2 run on separate OS threads over the shared
  g_weights() map), so lfm2 will lock this same instance, never a private one.

Verified: cargo test -p mlx-core --lib compiled (10 passed/0 failed),
cargo fmt --check, cargo clippy --all-targets -D warnings — all clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ense+flat)

Wire the lfm2 compiled C++ decode path live for dense, flat-cache
checkpoints. The per-operator pure-fns (attention, dense-MLP, ShortConv)
assembled in 2b-1 now run end-to-end for a real registered model: the
load path registers weights into the shared compiled map and flips the
gate, and decode threads the stride-2 conv/KV cache layout through
lfm2_decode_fn.

Correctness fixes (from two adversarial-review rounds):
- Seed the compiled decode position from the LIVE attention KVCache
  offset (get_offset()), NOT seq_len. seq_len is only the final chunk's
  logits length on a chunked prefill, or the uncached tail delta on a
  warm strict-extend hit; the KV offset accumulates prefix+delta across
  chunks and reuse, so it is the true position. All attention layers must
  agree on the offset or we fall back to native rather than seed a wrong
  position (wrong causal mask / KV write index).
- export_compiled_caches evaluates the rebuilt temp caches BEFORE
  assigning them to self.caches, so a mid-export failure can't leave the
  model holding half-evaluated cache state.
- Verify the C++ seed actually initialized (mlx_lfm2_moe_is_initialized)
  after init_from_prefill; fall back to native if it didn't.

Scope gating (deferred to Phase 4):
- Quantized dense checkpoints (any `.scales` tensor) are excluded from
  the compiled path: it stores no quant-info and would mis-dispatch
  MXFP4/NVFP4 as MXFP8. Compiled quant decode is deferred to Phase 4.
- conv_bias=true checkpoints are excluded: the compiled lfm2_decode_fn
  hardcodes conv_bias off, so a biased ShortConv would silently drop the
  bias term. Threading conv_bias through the FFI is deferred to Phase 4.
- MoE checkpoints (is_moe) are excluded — Phase 3 scope.
- The flat compiled path remains opt-in via use_block_paged_cache=Some(false);
  the default paged-native path is unchanged.

Validation: cargo test -p mlx-core --lib compiled (10 passed); env-gated
real-model e2e (LFM2_COMPILED_E2E=1) covers flat-vs-paged parity,
eager-vs-compiled byte-identity (separate-process MLX_NO_COMPILE=1),
>4096-token chunked-prefill offset, and warm strict-extend reuse
(asserts cached_tokens>0 so the warm KV-offset-reuse path is exercised).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e OFF)

Add the sparse mixture-of-experts FFN branch to the compiled lfm2 decode
graph. Until now lfm2_decode_fn ran a dense MLP for every layer; it now
branches per layer: dense for the first num_dense_layers (and for any
pure-dense checkpoint), sparse MoE thereafter. bf16 experts only;
quantized experts and the real-model gate flip are Phase 3b/3c. The
production gate stays OFF — this increment is validated only by a
synthetic-weight decode probe vs the native Lfm2SparseMoeBlock.

Routing mirrors native sparse_moe.rs op-for-op (parity-critical — these
are the usual sources of garbage output):
- sigmoid gating by default (softmax only when score_func == "softmax"),
  computed in f32.
- expert_bias is added to a SELECTION-ONLY routing copy; the top-k
  indices come from the biased copy but the combine weights are gathered
  from the UNBIASED sigmoid scores.
- top-k via argpartition(routing, E-k-1, -1) then the LAST k entries
  (top-k largest), matching the native convention.
- norm_topk_prob renorm is a plain /sum with NO epsilon.
- weights cast back to x.dtype after renorm; SwiGLU silu(gate)*up then
  down via gather_qmm; weighted sum over the k axis.
- no shared expert, no routed_scaling.

Mechanics:
- Lfm2MoeConfig gains num_experts, num_experts_per_tok, num_dense_layers,
  moe_intermediate_size, intermediate_size, norm_topk_prob,
  use_expert_bias, use_sigmoid, plus quant_mode/bits/group_size (default
  0/inert now so the FFI ABI is stable across 3a->3b). store_config and
  its Rust extern + persistence call site are extended to match; a
  pure-dense checkpoint sets num_dense_layers=num_hidden_layers so every
  layer routes dense (belt-and-suspenders with the C++ num_experts==0
  short-circuit, so dense-lfm2 Phase 2 behavior is unchanged).
- New mlx_lfm2_probe_moe_decode_seq registers a synthetic [conv,attn,moe]
  model and drives lfm2_decode_fn eagerly; same clear-on-every-path /
  eval-before-return memory discipline as the dense probe.

Test: compiled_moe_decode_seq_matches_native compares the compiled
MoE-layer decode against a hand-assembled native Lfm2SparseMoeBlock stack
(the shipping routing code) at bf16 max_abs < 2e-2. Experts carry a
distinct monotonic per-expert output scale so a top-k selection-convention
bug diverges well past tolerance — a plain compiled==native check is
otherwise invariant to a selection bug shared by both sides. Validated by
an adversarial Codex review (argpartition convention, unbiased-weight
gather, FFI ABI, probe memory safety, no gate flip / no shared-state
corruption). 11 compiled lib tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Brooooooklyn and others added 25 commits June 1, 2026 12:19
Codex No-shipped the lfm2 MoE compiled-flat golden harness on two findings;
this is TEST-ONLY hardening (no production source touched). It gives the MoE
oracle real teeth and backs the benign-tie diagnosis with committed evidence.

H1 — assert FULL generation in BOTH golden tests. Both goldens were captured at
80 mid-reasoning ids (no EOS), so the correct decode finishes by LENGTH at 80.
Pin num_tokens == max_new and finish_reason == "length" so an early EOS/stop
can no longer shrink the oracle window and pass a short prefix while hiding a
downstream bug.

H2 — MoE teeth. Raise GOLDEN_MIN_PREFIX_BYTES_MOE from 120 to the PROVEN 138
(the full byte-identical agreement) so the floor sits AT the divergence, not
below it, and add GOLDEN_MOE_DIVERGENT_TAIL = "So" + a post-prefix pin: when our
output diverges, the divergent continuation MUST begin with the documented
benign one-ULP flip (' So', mlx-lm rank #2). Floor catches an EARLY divergence
(a real routing/rope/eps bug diverges at token 1-3); the pin catches a CHANGED
pick exactly at the known benign tie — together: fail on unexplained tail
divergence.

H3 — vacuous-pass fix. Add resolve_moe_model(): when LFM2_MOE_MODEL_PATH is set,
MoE coverage was REQUESTED and the MoE tests must run + hard-FAIL (never skip) if
the checkpoint is missing or non-MoE. Both MoE tests now resolve through it; the
existing is_moe SKIP stays as the UNSET-fallback (dense default) path so hosts
without the 16G 8B remain green.

H4 — reproducible evidence. Commit scripts/probe_lfm2_divergence.py and rewrite
the GOLDEN_MIN_PREFIX_BYTES_MOE doc so the benign-tie claim cites the COMMITTED
probe: real top-3 at generated step 33 is ' One'=-1.50 (#1), ' So'=-1.75 (#2,
ours), ' That'=-1.75 (tied #2); 0.25 logprob gap == 0.25 raw-logit gap == 1 bf16
ULP, the tightest near-tie in all 80 steps; 33 byte-identical tokens INCLUDING
exact-tie steps 24 & 26 resolved identically to mlx-lm; compiled===eager rules
out a compile-tracing artifact. Corrects the prior wrong 'That/One tied at
37.75' wording (self-reported, not in any artifact).

H5 — latent harness bug. lfm2_eager_flat_vs_compiled_capture read the
dense-named lfm2_e2e_compiled_flat.txt unconditionally; against the 8B that
diffed MoE-eager vs a STALE dense-compiled artifact (common_prefix=0 => spurious
"REAL compile bug" panic). Make the compiled-artifact read topology-qualified
(lfm2_moe_e2e_compiled_flat.txt when src is an lfm2_moe checkpoint).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Second Codex adversarial No-ship on the lfm2 compiled-parity golden harness
(Phase 4 Piece 2). TEST-ONLY: no production source touched.

R1 [HIGH] full compiled self-golden replaces the 2-byte "So" pin. Add
GOLDEN_RAW_TEXT_MOE_OURS / GOLDEN_RAW_TEXT_DENSE_OURS (byte-reproducible
80-token compiled-flat raw_text; their 138B/314B prefixes == the mlx-lm
golden) and assert_eq! the ENTIRE compiled output in both golden tests, so a
regression flipping any token after the prefix gate now fails. Remove
GOLDEN_MOE_DIVERGENT_TAIL. Correct the GOLDEN_MIN_PREFIX_BYTES_MOE doc: the
"compiled === eager byte-identical" claim held only on the GREEDY 48-token
trajectory; on the GOLDEN 80-token trajectory eager appends ~10 trailing
newlines at a late benign tie (now proven by the new test).

R2 [MED] golden-trajectory eager-vs-compiled. Add
lfm2_moe_golden_eager_vs_compiled and lfm2_dense_golden_eager_vs_compiled
(MLX_NO_COMPILE=1, run_flat_golden, max_new=80) so the compile()-faithfulness
evidence is captured on the GOLDEN thinking trajectory where the step-33 ' So'
divergence happens, not the prior 48-token greedy path.

R3 [MED] fail-closed MoE coverage. Add is_moe_config(&Path) helper and rewrite
resolve_moe_model to HARD-FAIL when neither LFM2_MOE_MODEL_PATH nor
LFM2_SKIP_MOE_E2E is set and the resolved checkpoint is not MoE, so a forgotten
env var can no longer skip green on the dense default. Dedupe the inline
config.json/is_moe predicate in the two MoE tests + the eager-capture artifact
pick through the helper; drop the now-unreachable is_moe skip blocks while
keeping the structural pins.

R4 [MED] self-checking probe + committed fixture. Rewrite
scripts/probe_lfm2_divergence.py into a reproducible PASS/FAIL oracle: it now
asserts the committed invariants (mlx-lm 0.31, prompt ids, gen_ids[:34], and
the exact step-33 one-bf16-ULP tie: lp[' One']-lp[' So'] in [0.20,0.30],
|lp[' So']-lp[' That']| <= 0.06) and sys.exit(1) on any mismatch, printing
"PROBE SELF-CHECK PASSED" only when all hold. Commit the captured probe output
fixture.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…was blind)

lfm2's chat template ignores `enable_thinking`, so reasoningEffort 'low'/'none'
resolved enable_thinking=false → the ReasoningTracker was built with
starts_in_thinking=false → permanently blind (observe_token early-returns) → the
thinking-token budget was NEVER enforced, even when thinkingTokenBudget was set
explicitly. The model kept thinking unbounded until maxNewTokens (e.g. a haiku
prompt burned all 400 tokens inside <think> and never answered).

Fix (lfm2-only; qwen3.5 deliberately untouched — its template DOES honor
enable_thinking, so reasoningEffort gates thinking there correctly):
- All 6 lfm2 ReasoningTracker construction sites now set thinking_enabled=true
  unconditionally — lfm2 always emits a <think>…</think> block, so reasoning is
  always tracked AND parsed; reasoningEffort controls the BUDGET, not whether.
- New lfm2-only helper `default_thinking_budget_for_effort`: none→Some(0),
  low→Some(256), medium/high/unset→None. Threaded as
  effective_budget = thinkingTokenBudget.or_else(derive) so an explicit caller
  thinkingTokenBudget still wins.

Verified live on lfm2.5-8b-a1b (haiku rabbit-hole, temp 0): 'low' now force-closes
</think> and answers (was 400-tok/never-closed); 'none' → ~empty think + answer
(89 tok); 'medium' generous; explicit budget=64 overrides the low-derived 256.
qwen3.5/model.rs byte-unchanged; helper has zero non-lfm2 callers. Adds a unit
test for the mapping; clippy -D warnings + fmt clean; 72 lfm2 lib tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lfm2 + qwen3.5)

Streaming paths emitted every token as a chunk carrying an is_reasoning flag and
only the FINAL (non-stream) result honored include_reasoning. So a streaming
consumer (and the Responses SSE mapper, which routes isReasoning -> reasoning
summary deltas) received live <think>...</think> reasoning even when the caller
set include_reasoning=false (the default for reasoningEffort='none'). Pre-existing
cross-model gap; Codex flagged it on the lfm2 think-budget fix (32ce895).

Fix: gate the user-facing stream SEND on `include_reasoning || !is_reasoning` at
every streaming emit site (main loops + residual flushes) so reasoning deltas are
discarded while include_reasoning=false; only post-</think> content streams. The
final result already nulls `thinking`, so this aligns streaming with it. Applied
across the ReasoningTracker-based models: the shared decode_loop! macro (qwen3.5
dense/MoE + qwen3 non-paged) plus the per-site paged/flat/delta loops in lfm2,
qwen3_5, qwen3_5_moe, qwen3 -- 19 emit sites. gemma4 uses a different mechanism
(and its non-stream path also doesn't suppress thinking) -- left as a follow-up.

CRITICAL: only the cb.call SEND is gated; step_decode_stream + streamed_text_len
advance + observe_token stay OUTSIDE the gate so the streaming detokenizer sees
every token (BPE/UTF-8 merge state) and the residual-flush offset stays correct.

Verified live (temp 0, thinkingTokenBudget 48): lfm2.5-8b-a1b + qwen3.5-0.8b both
yield ZERO is_reasoning deltas and no <think>/</think> text when
include_reasoning=false (content still streams; final thinking=null), and reasoning
deltas present when true. Unit test for the gate predicate; clippy -D warnings +
fmt clean; chat_common 46 + lfm2 72 lib tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ning=false

Codex F1 follow-up on 4a5bef8. include_reasoning=false already suppressed the
parsed `thinking` field and the streamed reasoning deltas, but the terminal
raw_text still carried the full <think>…</think> span — a direct @mlx-node/lm
consumer reading finalEvent.rawText could still recover the chain-of-thought.

Add raw_text_with_reasoning_suppressed in qwen3_5/chat_common.rs: mirrors
parse_thinking_and_tools' boundary logic and returns the VERBATIM post-</think>
slice (preserving tool-call markup, whitespace, exact bytes) when
include_reasoning=false, and the full text otherwise. Truncated generations
(no </think>) scrub to empty; no-thinking mode stays verbatim. Wired into the
finalize_chat_result chokepoint (non-stream + lfm2/qwen3.5/qwen3.5_moe paged)
and the 8 inline streaming sites (qwen3_5/qwen3_5_moe/qwen3/lfm2 start+delta).
gemma4 excluded (no reasoning support; pre-existing broader gap).

Tool-call markup lives after </think>, so the verbatim post-boundary slice
keeps server tool-call recovery (messages.ts:417) working.

Verified live on lfm2.5-8b-a1b + qwen3.5-0.8b: include_reasoning=false → zero
think tags in raw_text (stream AND non-stream; lfm2 was leaking before), content
intact; =true → raw record + reasoning deltas preserved. Unit test covers
confirmed-</think>, truncated, no-thinking, and text-level-fallback cases.
clippy -D warnings + fmt clean; mlx-core lib tests pass (chat_common 47, lfm2 72).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ck blocks

Codex No-ship follow-up on 4b44c56 (two findings).

F1 [high] — qwen3 non-stream ignored include_reasoning entirely. Both
chat_sync_core (flat) and chat_sync_core_paged decoded the full generation,
parsed via tools::parse_generation_output (no include_reasoning), and built
ChatResult with thinking AND raw_text unsuppressed — so includeReasoning=false
still leaked <think>…</think> in both fields (qwen3 streaming already honored
it; this closes the stream/non-stream inconsistency). Route both builders
through the token-level parse_thinking_and_tools + raw_text_with_reasoning_
suppressed, matching finalize_chat_result and the other models. reasoning_tokens
is counted from the unsuppressed thinking (parse with include_reasoning=true)
so usage accounting is unchanged; thinking + raw_text are then suppressed per
the contract. Side effect (accepted, consistent with qwen3.5/lfm2): a truncated
thinking generation now routes entirely into `thinking` with text="" instead of
mislabeling reasoning as content.

F2 [medium] — strip_reasoning_span_text_level (the no-think_end_id fallback)
removed only the FIRST paired <think> block, while tools::parse_thinking strips
all. Multi-block reasoning could leave a later block in raw_text while `thinking`
was fully nulled. Loop the strip to remove ALL paired <think>/<longcat_think>
blocks (verbatim remainder), with a multi-block regression test.

Verified live: qwen3-0.6b non-stream includeReasoning=false → no think tags in
raw_text, thinking suppressed, reasoning no longer mislabeled as content;
=true → reasoning surfaced via thinking. lfm2.5-8b-a1b + qwen3.5-0.8b unregressed.
cargo: qwen3 130 tests + chat_common 48 (incl. new multi-block) pass; clippy
-D warnings + fmt clean; build:native rebuilt.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ul, no leak)

Codex No-ship follow-up on acd6401. The hand-rolled strip_reasoning_span_text_level
fallback (no-think_end_id path) picked the earliest opening tag across the
<think>/<longcat_think> families per iteration and bailed if THAT opener had no
matching close — so `prefix <think> <longcat_think>secret</longcat_think> suffix`
broke before the valid longcat block, fell through the missing-open branch (which
needs the close followed by newline/EOT), and returned the text verbatim →
leaked the longcat reasoning under include_reasoning=false, even though the parsed
`thinking` (via tools::parse_thinking, which checks families separately) suppressed it.

Delete the bespoke scanner; the fallback now delegates to `tools::parse_thinking(text).0`
— the SAME function parse_thinking_and_tools' own fallback uses (via
split_at_think_end(None) -> parse_generation_output). This makes the raw_text
reasoning boundary IDENTICAL to the parsed `thinking`/`text` boundary by
construction (no divergence possible) and preserves tool-call markup
(parse_thinking strips only reasoning blocks). Consequence: the fallback remainder
is trimmed to match the parser's clean_text (e.g. "\nABC" -> "ABC"); boundary
fidelity over byte-verbatimness on this rare defensive path.

Only the no-think_end_id fallback changed — the token-confirmed and truncated
branches (which every real model uses: qwen3/qwen3.5/lfm2 all have </think>) are
byte-identical to acd6401, so real-model behavior is unchanged (unit-test verified).
Added test_raw_text_fallback_mixed_unmatched_tag (Codex's mixed-tag repro); the
multi-block test still passes. chat_common 49 tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pan safe)

Codex No-ship follow-up on 58421f5 (two findings, both confined to the
no-think_end_id fallback — unreachable by qwen3/qwen3.5/lfm2, which all have a
</think> token and use the token-confirmed branch; this is forward-defensive code).

Delegating the fallback to tools::parse_thinking directly had two holes:
- mixed families: parse_thinking returns after the FIRST matching family, so
  `<think>a</think><longcat_think>secret</longcat_think>answer` left the longcat
  block in raw_text under include_reasoning=false.
- tool-call markup: parse_thinking ran on the full text, so a literal <think>…</think>
  (or bare </think>) inside a tool-call argument was treated as a reasoning delimiter,
  corrupting the <tool_call> span that server recovery (messages.ts:417) depends on.

Add tools::strip_reasoning_preserving_tools: split the text at <tool_call>…</tool_call>
spans (via the existing extract_tag_blocks byte ranges), strip reasoning only in the
gaps, and copy each tool span through verbatim. Gap stripping uses a new
strip_all_reasoning that iterates parse_thinking to a fixpoint so BOTH
<think>/<longcat_think> families are removed (parse_thinking strips one family per
pass; the text strictly shrinks so it terminates). Reuses the shared, tested
parse_thinking — no bespoke tag scanner. The chat_common fallback now calls it; the
overclaiming "both families" comment is corrected.

Tests (tools/mod.rs): mixed paired families; <think>…</think> and bare </think> inside
tool args (span byte-preserved); reasoning before a tool call; reasoning between two
tool calls; no-tags verbatim. Only the fallback path changed — token-confirmed and
truncated branches are byte-identical, so real-model behavior is unchanged (verified
earlier on qwen3/qwen3.5/lfm2). tools 71 + chat_common 49 tests pass; clippy
-D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ll is fully stripped

Closes the Codex No-ship on f320197: the gap-wise stripper split text at
<tool_call>…</tool_call> spans and stripped reasoning only in the gaps, so a
reasoning block that WRAPS a tool span (<think>…<tool_call>…</tool_call>…</think>)
leaked its pre-tool prefix — the open <think> sat in one gap and its </think> in a
later gap, and neither gap saw a complete block to strip.

Replace the gap-wise approach with sentinel masking: mask each complete
<tool_call>…</tool_call> span with an opaque U+E000-delimited placeholder that
carries no tag markup, run strip_all_reasoning over the WHOLE masked text (so a
reasoning block wrapping a tool span is matched and removed as a unit), then
restore only the sentinels that survived the strip. A sentinel inside a stripped
reasoning block disappears with it (tool span correctly dropped); a surviving
sentinel is restored byte-for-byte. PUA delimiters cannot collide with model text
and the trailing delimiter makes indices non-prefixing, so restoration is exact.

Still fallback-only (no-</think>-token path, unreachable by qwen3/qwen3.5/lfm2);
token-confirmed/truncated branches byte-identical. Adds two cross-boundary
regression tests (tool span wrapped by <think> / <longcat_think> reasoning).
tools 73 + chat_common 49 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nested tool calls on fallback

Closes the Codex No-ship on 2e5ac5d with two fallback-only fixes (both
unreachable by qwen3/qwen3.5/lfm2, which have </think> tokens → token-confirmed
branch; forward-defensive hardening):

1. Sentinel collision/injection (tools/mod.rs). The fixed U+E000-delimited
   sentinel could be forged by the model: a literal `\u{E000}TOOLCALL{n}\u{E000}`
   in prose would be restored into fabricated tool markup, and a sentinel string
   appearing inside a tool argument could be clobbered by a later index's global
   replace. Fix: derive the delimiter as a run of U+E000 one longer than the
   longest such run already in the input (tool_span_delimiter), making the
   delimiter — and every sentinel built from it — provably impossible to occur as
   a substring of the input (hence of any tool span). Every sentinel in the
   stripped output is then one we inserted: global restoration can neither
   fabricate tool markup from model text nor clobber an already-restored span.

2. Reasoning-nested tool calls on the text-level fallback (chat_common.rs). On the
   no-</think>-token fallback, parse_thinking_and_tools delegated to
   split_at_think_end(None) → parse_generation_output, which parses tool calls from
   the FULL text BEFORE removing reasoning — so a <tool_call> nested inside a
   <think> block surfaced as an executable tool call while the raw_text scrub
   correctly dropped it (an inconsistency this scrub introduced). Fix: on the
   fallback, isolate reasoning with strip_reasoning_preserving_tools BEFORE
   extracting tool calls, matching the token-confirmed path's isolation and the
   raw_text scrub. Confined to the chat finalize path; the shared
   parse_generation_output / build_reward_outputs (GRPO) path is untouched.

Adds 4 tests: literal sentinel in prose not restored, literal sentinel inside tool
args round-trips byte-for-byte, fallback excludes reasoning-nested tool call,
fallback still extracts a standalone tool call after reasoning. Real models
unaffected (token-confirmed/truncated branches byte-identical). tools 75 +
chat_common 51 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t synthesize a sentinel

Closes the Codex No-ship on f9ab706. The guaranteed-absent MULTI-CHAR delimiter
proved the sentinel was absent from the *input*, but reasoning removal is a
DELETING transform: stripping the `<think>` blocks in an input like
`E<think>x</think>E TOOLCALL0 E<think>y <tool_call>{"name":"secret"}</tool_call> z</think>E`
(E = U+E000) concatenates the leftover `E`, `ETOOLCALL0E`, `E` fragments into
`EETOOLCALL0EE` — exactly the synthesized sentinel — and the global str::replace
then RESURRECTS the reasoning-nested `secret` tool call into raw_text. The
absent-from-input invariant does not survive a transform that rearranges fragments.
(Confirmed empirically before fixing.)

Fix: mask each tool span with a SINGLE distinct Private-Use-Area code point chosen
ABSENT from the input (tool_span_sentinels), instead of a multi-char delimiter.
Two properties make restoration sound under deletion:
  * absent-from-input ⇒ no collision with model text and no placeholder inside any
    restored original (originals are substrings of the input) ⇒ global replace is
    collision- and clobber-free;
  * single code point ⇒ deletion can only remove or join text, never CREATE a code
    point, so a placeholder survives iff its tool span was outside every stripped
    reasoning block. The multi-char delimiter was forgeable precisely because
    concatenation can assemble it; a lone absent code point cannot be assembled.
If the PUA is somehow exhausted (input saturates 130k+ code points — impossible in
practice) we strip everything rather than risk a collision.

Adds a deletion-synthesis regression test (Codex's exact attack: asserts the
reasoning-nested `secret` call is NOT resurrected). Existing tool-preservation,
prose-literal, ordering, and fallback tests unchanged and passing. Still
fallback-only / unreachable by real models (token-confirmed branch byte-identical).
tools 76 + chat_common 51 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…addling tool spans

Closes the Codex No-ship on 5d46a0b. The single-codepoint fix killed delimiter
synthesis, but masking-then-stripping still had two holes:
  * [high] STRADDLING spans: a <tool_call> opening inside <think> whose </tool_call>
    lands after </think> makes extract_tag_blocks' first-open→first-close span SWALLOW
    the </think>. Masking then removed the only reasoning close from the text seen by
    the stripper, leaving <think> unterminated → the `<think>secret` prefix leaked into
    raw_text AND the reasoning-started tool call surfaced via the fallback's
    parse_tool_calls. (Confirmed empirically.)
  * [medium] the sentinel-exhaustion guard fell back to the unmasked strip_all_reasoning,
    re-entering the exact parser the helper exists to avoid.

Replace masking+placeholders with a purely RANGE-based scrub (Codex's recommendation):
  1. tool spans = opaque byte ranges;
  2. reasoning ranges = paired <think>/<longcat_think> blocks on the ORIGINAL text MINUS
     any block wholly inside a tool span (literal arg text); else the missing-open
     (</think>\n prefix) case, mirroring parse_thinking;
  3. removal = reasoning ranges ∪ every tool span that OVERLAPS a reasoning range (nested
     or straddling — entangled with reasoning, so dropped); tool spans disjoint from all
     reasoning are preserved verbatim;
  4. emit text minus the merged removal ranges.

Because boundaries are computed on the original text before anything is removed, a tool
span can neither hide a reasoning close nor be resurrected; with no marker substitution
there is no synthesis, collision, or exhaustion class at all. Deletes tool_span_sentinels.

Adds straddle regressions through strip_reasoning_preserving_tools, parse_thinking_and_tools,
and raw_text_with_reasoning_suppressed (the latter two per Codex's next-steps), plus the
retained deletion-synthesis regression. Still fallback-only / unreachable by real models
(token-confirmed/truncated branches byte-identical). tools 77 + chat_common 53 pass;
clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…crub

Closes the Codex No-ship on 6a5c89f (the range rewrite itself fixed the prior
straddle [high] + exhaustion [medium]; this closes a residual missing-open hole).

The missing-open branch was gated on `reasoning.is_empty()` and checked only the
FIRST `text.find(close)`. When that first close is literal text inside a tool
argument, it was skipped and the REAL top-level close later was never found, so the
function returned the input verbatim — leaking the leading reasoning AND surfacing a
reasoning-internal tool call on the no-think_end_id fallback. Example (confirmed):
`secret <tool_call>{"name":"leak","arguments":{"q":"</think> literal"}}</tool_call>
more secret</think>\nfinal`.

Fix (per Codex's recommendation): detect missing-open INDEPENDENTLY of the paired set
(not gated on emptiness) via two helpers — first_top_level (earliest top-level, i.e.
not-inside-a-tool-span, occurrence of an opener) and first_top_level_bare_close
(earliest top-level close followed by newline/EOF, skipping in-argument closes). The
leading prefix [0, close_end] is reasoning iff that close PRECEDES any top-level
opener (otherwise it belongs to a normal paired block and the text before its opener
is real content). This composes correctly with later paired blocks of either family.

Adds the two regressions Codex requested: a close inside a tool argument before the
real top-level close, and a missing-open prefix plus a later paired block of the other
family (content tool call preserved). All prior cases unchanged. Still fallback-only /
unreachable by real models. tools 79 + chat_common 53 pass; clippy -D warnings + fmt
clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Closes the Codex No-ship on 05bd253. The missing-open guard computed `first_open`
as the earliest top-level opener across BOTH families, so a `<think>…</think>` block
appearing before a bare `</longcat_think>\n` close wrongly suppressed the longcat
missing-open strip (a `<think>` opener cannot match a `</longcat_think>` close). Input
`secret <think>inner</think> more </longcat_think>\n<tool_call>…</tool_call> final`
leaked `secret … more </longcat_think>`; the symmetric longcat-before-bare-`</think>`
case had the same hole. (Confirmed.)

Fix: compare each family's bare close only against the first top-level opener of the
SAME family. `first_top_level_bare_close` now takes the family's close tag; the
detection loop iterates families, accepts a `(0, close_end)` prefix when no same-family
opener precedes the close, and keeps the earliest qualifying close. A nested paired
block of the other family inside the prefix is removed with it (it is content within
the injected reasoning).

Adds both cross-family regressions Codex requested (longcat close after a nested think
block, and the symmetric think close after a nested longcat block — content tool call
preserved in both). All prior cases unchanged. Still fallback-only / unreachable by
real models. tools 81 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…y block no longer vetoes the real close

Closes the Codex No-ship on 86ef253. The family-aware guard used the FIRST
top-level same-family opener as a global veto: a paired `<think>inner</think>`
nested in a missing-open prefix made `first_top_level(text,"<think>")` return the
inner opener, whose position precedes the real bare `</think>`, so the veto fired
and the prefix leaked (`secret <think>inner</think> more </think>\n<tool_call>…`
left `secret more </think>` in raw_text). Symmetric for longcat.

FIX: replace the opener-veto with bracket-depth matching (`missing_open_close`).
The template injects the opener into the PROMPT, so generated text begins one level
deep — model that as an implicit depth of 1 and walk the family's top-level
(not-in-tool) open/close tags in position order; the close that returns depth to 0
matches the injected opener and terminates the leading reasoning. A same-family
paired block nested in the prefix nets out (its open then close), so the unmatched
injected close is still found. A NORMAL paired block with no injected opener never
returns depth to 0 (open balances close, leaving depth 1) → correctly NOT detected
as missing-open, so leading content is preserved. Terminator still gated on
newline/EOF to mirror parse_thinking. Earliest qualifying close across families
wins; composes with the paired set; cursor-walk emit / trim unchanged.

Helpers: `first_top_level`+`first_top_level_bare_close` → `top_level_positions`
(all top-level offsets) + `missing_open_close` (bracket-depth). New tests: think /
longcat missing-open prefix nesting a same-family paired block (full prefix incl.
nested block stripped, content tool call + tail preserved); normal-paired-block
regression guard on the range path. Still fallback-only / unreachable by real models
(qwen3/qwen3.5/lfm2 all have </think> tokens). tools 84 + chat_common 53 pass;
clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ng-open terminator

Closes the Codex No-ship on d399594. `missing_open_close` returned `None` the
moment a close first drove depth to 0 when that close failed the newline/EOF gate
— abandoning the scan before a LATER newline-terminated close that the design's own
disambiguation intends as the real terminator. With a missing-open prefix that
contains a literal top-level `</think>` in reasoning content (not newline-
terminated) before the true terminator, detection bailed, the whole prefix was
preserved, and a reasoning-internal `<tool_call>` leaked into raw_text / the
no-think_end_id fallback's parsed tool calls — the exact failure this scrubber
prevents (`secret </think> literal <tool_call>{"name":"leak"}…</tool_call> more
</think>\nfinal` returned everything incl. the leak). Symmetric for longcat.

FIX: at the injected level (depth 1), a close is the terminator ONLY when followed
by newline/EOF; a close that fails the gate is a literal close in reasoning content
— keep the implicit open (depth stays 1) and continue scanning to the real,
newline-terminated close. Restructured the close branch from "decrement then test
depth==0" to "at depth 1, gate-test (return or ignore); else decrement (nested
close nets out)". This also makes depth provably ≥ 1 throughout: the injected level
is never decremented away, so no stray close can drive it negative. All prior cases
(nested same-family block, normal paired block, in-tool-arg close, the earliest-
wins cross-family pick, cursor-walk emit/trim) unchanged.

New tests: think + longcat missing-open prefix with a literal top-level close
(non-newline) and a reasoning-nested tool call before the real terminator — assert
the whole prefix incl. the leak tool call is stripped and only post-terminator
content survives. Still fallback-only / unreachable by real models (qwen3/qwen3.5/
lfm2 all have </think> tokens). tools 86 + chat_common 53 pass; clippy -D warnings
+ fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Closes both Codex No-ships on 4cd9d40 — two more fallback paths that the
missing_open_close fix didn't cover.

(1) No-tool path. With no `<tool_call>` span, strip_reasoning_preserving_tools
routes through strip_all_reasoning → parse_thinking, whose missing-open handling
used `text.find(close)` (first occurrence only) and bailed if it failed the
newline/EOF gate — the SAME literal-close masking bug, so `secret </think> literal
more </think>\nfinal` (no tool call) leaked the whole reasoning prefix. FIX:
parse_thinking's missing-open loop now scans EVERY occurrence of each close tag for
the first newline/EOF-terminated one. The three parse_thinking missing-open tests
are unchanged (their first close already determines the outcome).

(2) Missing-open straddle. A `<tool_call>` that opens inside the template-injected
reasoning prefix and whose body contains the real `</think>\n` terminator
(`</tool_call>` after it) put the terminator INSIDE a tool span. missing_open_close
scanned closes top-level-only, so it missed the terminator, returned None, and the
reasoning-started tool call leaked verbatim (`secret <tool_call><function=leak>
</think>\n…</tool_call> final`). The explicit-opener twin was already handled by the
paired path; this is its missing-open counterpart. FIX: scan CLOSES on the raw text
(tool spans included) so an in-tool close can be the terminator; keep OPENS
top-level-only so a `<think>` literal inside a tool argument cannot inflate depth and
hide the real close. The newline gate still skips a literal in-argument close, and
the existing overlap-drop drops the straddling span — so the call never surfaces.

New tests: no-tool literal-close-before-terminator; missing-open straddling tool
span dropped. All prior cases hold (in-tool-arg close, explicit-opener straddle,
nested same-family, normal paired block). Still fallback-only / unreachable by real
models (qwen3/qwen3.5/lfm2 all have </think> tokens). tools 88 + chat_common 53
pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…neric parse_thinking

Closes both Codex No-ships on d9e791f.

[high] In-tool newline-terminated close could falsely terminate missing-open.
The previous fix scanned ALL closes (tool spans included) and returned the first
newline/EOF-terminated one. But XML-style tool params carry RAW text, so a literal
`</think>\n` inside a `<parameter>` is plausible (JSON escapes newlines; raw params
don't). Such an in-tool close was chosen as the terminator, dropping only its span
and leaking the trailing reasoning: `secret <tool_call>…<parameter=q></think>\n
literal</parameter>…</tool_call> more secret </think>\nfinal` leaked `more secret
</think>\nfinal`. FIX: rank candidates — a TOP-LEVEL newline close is a definitive
terminator (returned immediately); an IN-TOOL newline close is only a TENTATIVE
straddle candidate, recorded while the scan continues, used solely if no top-level
terminator turns up. The genuine straddle (Codex's earlier finding) still works
(no top-level close exists → the tentative is used); the false case now defers to
the real top-level terminator, so nothing leaks.

[medium] Shared parse_thinking blast radius. The no-tool fix had broadened the
GENERIC parse_thinking missing-open to scan past inline closes — but parse_thinking
is shared by parse_generation_output (GRPO reward parsing), Qianfan OCR, and chat
finalize, so it would reclassify ordinary completions (an inline `</think>` then a
later `</think>\n`) as thinking and truncate. FIX: revert parse_thinking to
first-close-only (generic semantics preserved) and instead fix the no-tool
suppression leak by removing the `tool_ranges.is_empty()` fast path so the no-tool
case flows through the unified range logic, whose `missing_open_close` already scans
past literal closes. This splits the security scrubber from the generic parser
exactly as recommended; the now-dead `strip_all_reasoning` is removed.

New tests: raw-newline `</think>` in a tool param before the real top-level
terminator (asserts no leak, only "final"). All prior cases hold: no-tool literal-
close, explicit + missing-open straddle, in-tool-arg close, nested same-family,
normal paired, literal-close-before-terminator (think+longcat); 7 parse_thinking
tests (generic semantics intact). Still fallback-only / unreachable by real models.
tools 89 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…allback leaks

Closes both Codex No-ships on 90ed443.

[high] First-wins over multiple in-tool straddle candidates leaked. When two tool
calls each carry an in-tool `</think>\n` and NO top-level terminator exists,
`straddle.get_or_insert` kept the EARLIER (literal) close, so the reasoning range
reached only the first span — dropping tool #1 but leaking `more secret` plus the
later reasoning-started tool #2 (`function=real`). FIX: last-wins — keep the LATEST
in-tool candidate, so the reasoning range reaches the final straddle and the
overlap-drop removes EVERY straddling span and the inter-call reasoning. A top-level
terminator still preempts any tentative (returned immediately); single-candidate
straddle and the raw-newline-before-top-level cases are unchanged.

[medium] No-tool path no longer stripped SUCCESSIVE missing-open spans. Removing the
`tool_ranges.is_empty()` fast path made the no-tool case a single range pass, which
finds only the first top-level terminator: `secret </think>\nmore secret </think>\n
final` left `more secret </think>\nfinal`, whereas the deleted strip_all_reasoning
fixpoint stripped to `final`. FIX: the scrubber now iterates the pass
(`strip_reasoning_once`) to a fixpoint, so successive missing-open spans are all
removed — matching the old fixpoint, but on the scrubber's own `missing_open_close`
(which scans past literal closes, unlike the generic parse_thinking) rather than
delegating. Each pass shrinks or stabilizes the text, so it terminates; the with-tool
cases are single-pass fixpoints, so their behavior is unchanged.

New tests: two in-tool straddle candidates / no top-level terminator (asserts both
tool calls + all reasoning dropped, only "final"); successive no-tool missing-open
spans (asserts "final"). All prior cases hold. Still fallback-only / unreachable by
real models. tools 91 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Closes the Codex No-ship on 1eecd62. The unconditional fixpoint dropped a VALID
post-reasoning tool call. The missing-open scanner models byte 0 as template-injected
reasoning — true of the original generation, but NOT of a later pass's output that
begins with a PRESERVED tool call. For `secret </think>\n<tool_call><function=ok>
<parameter=q></think>\nliteral</parameter></function></tool_call> tail`, pass 1
correctly strips only the leading span and keeps the tool call; pass 2 then saw the
tool span at byte 0, treated its argument's literal `</think>\n` as a straddle
candidate, and the overlap-drop removed the whole valid call → only `tail` survived.

FIX: iterate to a fixpoint ONLY when the ORIGINAL text has no tool span (the no-tool
case, where byte 0 stays injected-reasoning across passes and successive missing-open
spans must be stripped — the [medium] fix). When a tool span is present, run exactly
ONE pass: the with-tool cases — including multiple in-tool straddle candidates, via
last-wins in `missing_open_close` — are already handled in a single pass, and never
re-running means a preserved tool call can't be reinterpreted as byte-0 reasoning.

New test: leading missing-open span + a valid tool call whose argument contains a
literal `</think>\n` — the tool call must survive the fixpoint. All prior cases hold:
successive no-tool spans (fixpoint), multi in-tool candidate (single-pass last-wins),
raw-newline-in-tool-param, straddle, in-tool-arg close, nested, normal paired. Still
fallback-only / unreachable by real models. tools 92 + chat_common 53 pass; clippy -D
warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t the original's

Closes the Codex No-ship on 7a1b248. The original-text guard
("with a tool span present, run one pass only") was too broad: when the
original's complete `<tool_call>` span is reasoning-INTERNAL (inside the
leading missing-open prefix), pass 1 correctly drops it and leaves a
tool-free remainder that STILL begins with a second missing-open span —
but the guard returned after one pass and leaked it. Repro:
`secret <tool_call>{"name":"leak"}</tool_call> </think>\nmore secret </think>\nfinal`
returned `more secret </think>\nfinal` instead of `final`.

Fix: iterate the pass to a fixpoint while the CURRENT OUTPUT is free of
complete tool spans, stopping the moment a PRESERVED tool call survives
(re-running on an output that begins with a real call would treat its arg
`</think>` as a byte-0 straddle and wrongly drop it). A reasoning-internal
tool call is dropped within a pass, so its tool-free remainder keeps
iterating; a preserved post-reasoning call halts iteration. A pass cannot
synthesize a tool span across iterations — if the output held an
open-before-close pair `extract_tag_blocks` would be non-empty and the loop
would already have stopped, and a pass only deletes (preserving tag order).

Fallback-only path: real models (qwen3/qwen3.5/lfm2) all have a `</think>`
token and use the token-confirmed/truncated branches, byte-identical across
all commits; this scrubber is the no-`</think>`-token-in-vocab text fallback.

Adds Codex's exact regression test
(test_strip_reasoning_missing_open_internal_tool_then_successive_span).
tools 93 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…thesized tool spans

Closes both Codex No-ships on 04963ca, both reachable on the no-`</think>`-
token fallback (the scrubbed text is fed to parse_tool_calls at
chat_common.rs:518, so a leaked/fabricated span becomes an EXECUTABLE call).

Finding 1 — surviving tool span stopped cleanup of a later missing-open span.
The output-tool-span guard halted whenever any complete `<tool_call>` survived
a pass, even when the remainder still LED with reasoning. Repro
`secret <tool_call>{leak1}</tool_call> </think>\nmore secret <tool_call>{leak2}</tool_call> </think>\nfinal`
leaked `more secret` and surfaced `leak2`. Fix: gate iteration on whether the
output still leads with a TOP-LEVEL (definitive) missing-open terminator
(has_top_level_missing_open_terminator), computed from the same
applied_missing_open the strip itself uses — so the gate and the strip never
disagree, including the cross-family corner where an in-tool straddle of one
family is earlier than a top-level close of the other (the in-tool one is
applied, so iteration halts and preserves the straddling call).

Finding 2 — reasoning deletion could SYNTHESIZE a tool call. Removing a
reasoning block flanked by tool-tag fragments (`<tool` <reasoning> `_call>`)
fuses them into a `<tool_call>` span that never existed in the input. Repro
`<tool<think>secret</think>_call>{"name":"leak"}</tool_call>` produced an
executable `leak` call. Fix: drop_synthesized_tool_spans removes any output
tool span absent verbatim from the pass input (a genuine preserved span is
copied verbatim and always re-appears, so only fabricated spans are dropped);
iterated to a fixpoint. The prior doc comment's "a pass cannot synthesize a
tool span" claim was false and is removed.

Adds Codex's two requested regressions (successive spans each with an internal
tool; split-opener synthesis) plus a cross-family preserved-call test, each
also asserting via parse_tool_calls that no leaked/fabricated call survives.
tools 96 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ce synthesis defense

Closes both Codex No-ships on 00daeb7 (both reachable: scrubbed text feeds
parse_tool_calls at chat_common.rs:518, so a leaked/fabricated span executes).

Finding 1 — cross-family terminator ranking was backwards. applied_missing_open
picked the earliest close across families, so an EARLIER in-tool straddle of one
family vetoed a LATER top-level close of the other. When a tool call precedes a
genuine later top-level close, the reasoning extends over the call (it is
reasoning-internal), but the earlier in-tool pick set is_top_level=false → the
fixpoint halted and leaked. Repro
`r1 </think>\n<tool_call><function=leak>…</longcat_think>\n…</tool_call> more secret </think>\nfinal`
leaked `more secret` + `leak`. Fix: applied_missing_open now PREFERS the earliest
top-level close across both families, using an in-tool straddle only when no
top-level close exists at all (latest straddle, matching missing_open_close's
within-family last-wins). The previously-committed cross-family test asserted the
WRONG outcome (preserve) and is corrected to drop; a no-later-close counterpart
pins the genuine-preserve case.

Finding 2 — substring provenance was not provenance. drop_synthesized_tool_spans
kept any output span that was a verbatim substring of the input — but a fabricated
(seam-fused) span can equal bytes that existed only INSIDE a deleted reasoning
block. Repro
`<think><tool_call>{leak}</tool_call></think><tool<think>secret</think>_call>{leak}</tool_call>`
survived. Fix: drop_non_preserved_tool_spans keeps only the PRESERVED (`kept`)
tool spans — those disjoint from all reasoning, copied verbatim and contiguously —
via a per-string budget (multiset), dropping fabricated spans AND duplicates
beyond the genuine count; iterated to a fixpoint.

Adds Codex's two repros + the cross-family preserve counterpart, each asserting
via parse_tool_calls that no leaked/fabricated call survives. 34 strip_reasoning
tests; tools 98 + chat_common 53 pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ing-budget)

Closes the Codex No-ship [high] on c0abb76 (reachable: scrubbed text feeds
parse_tool_calls at chat_common.rs:518, so a mis-attributed span executes).

Finding [high] — the per-string budget multiset mis-attributed provenance. It
keyed genuine-ness on the `<tool_call>…</tool_call>` byte string, so a FABRICATED
span byte-identical to a genuine call (and positionally earlier) consumed that
call's budget; the real later call was then dropped as excess. Repro
`<tool<think>secret</think>_call>{"name":"b"}</tool_call><tool_call>{"name":"a"}</tool_call><tool_call>{"name":"b"}</tool_call>`
yielded executable `[b, a]` (fused look-alike + reorder) instead of the genuine
`[a, b]`. Fix: RANGE provenance — the emit records each copied chunk as
(in_start, in_end, out_start); each PRESERVED (kept) tool span maps to its exact
OUTPUT byte range (it lies wholly within one chunk, since no removal is ever
strictly inside a preserved span); `keep_only_genuine_tool_spans` retains only
those ranges, dropping any other span one at a time and shifting the genuine
ranges after each drop so a fusion newly formed at a drop seam is itself caught.
Byte-identity is never used, so duplicates and look-alikes are disambiguated by
position. Adds the exact repro asserting executable `[a, b]`.

Finding [medium] — "top-level preference drops a post-boundary call" — is a
DELIBERATE disposition, not a fix. It is the structurally-identical input the
PRIOR review's [high] explicitly demanded be dropped (calling the keep a leak).
Under the successive-missing-open-span model (a second bare close IS a second
reasoning span — the same rule that strips the no-tool `secret </think>\nmore
secret </think>\n…` case), a call inside that span is reasoning-internal; dropping
it is the security-conservative, internally-consistent choice. Preserving it would
re-introduce that leak and contradict the no-tool stripping. Documented inline on
the test.

35 strip_reasoning tests; tools 99 + chat_common 53 pass; clippy -D warnings + fmt
clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Address the 8 actionable inline review comments on PR #64 (1 was already fixed):
- convert sanitize_lfm2_moe: rename .scales/.biases alongside .weight; honor
  --dtype for non-f32 inputs via a FLOAT-ONLY cast (never astype packed quant
  data — fixes a Uint32-astype corruption the dtype broadening introduced)
- persistence: detect dense-MLP quant from ANY projection .scales (apply +
  validate parity via shared dense_mlp_is_quantized/dense_mlp_proj_bases);
  dedup the affine switch-linear builder (qwen3_5_moe
  try_build_quantized_switch_linear -> pub(crate), drop the lfm2 copy)
- config: norm_topk_prob/use_expert_bias -> Option<bool> (optional in TS),
  readers .unwrap_or(true); index.d.cts regenerated
- tokenizer: env-gate the LFM2 template test (drop hardcoded local path)

Convert hardening surfaced by adversarial review:
- sanitize_lfm2_moe fails loud on pre-quantized per-expert/dense inputs via
  layered guards + a base-aware final invariant (only conv.conv.weight and
  *norm.weight are dense-only; lm_head is affine-quantizable via its sidecar)
- quantize_weights_inner skips already-quantized groups and non-float weights
  instead of double-quantizing/corrupting them

8 new convert tests; lfm2/convert/config suites green; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit def5a1a into main Jun 2, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/lfm2-moe branch June 2, 2026 04:47
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Post-rebase fixes required to land the MTP branch cleanly on the
advanced origin/main (#61-#64: lfm2 MoE, E37 prefill opt, drain-on-write
convert). All conflicts during the 84-commit replay were resolved within
their commits; these are the cross-cutting reconciliations:

- convert.rs: origin/main #63 changed `save_safetensors` to drain its
  argument (`&mut`, drain-on-write). The MTP sidecar + split-drafter
  writers borrow their tensor maps immutably and the sidecar reuses its
  map afterward (its `is_empty()` gates config metadata), so drain a
  small clone instead of the original.
- qwen3_5/model.rs: origin/main's E37/E38 last-token prefill slice
  (`forward_with_optional_last_slice`) auto-merged into the SHARED
  `forward_pre_norm_inner`, but that primitive must return the full
  per-position hidden for the MTP prompt-hidden path
  (`chunked_prefill_with_hidden_with_size` re-slices it by chunk
  length). Restored the tested plain-`forward` loop. E37's main win
  (lm_head matmul reduction) is still applied by
  `project_last_logits_from_pre_norm_hidden`; only the negligible eager
  last-layer-MLP slice (E38) is dropped. Kept origin/main's chunk_async
  toggle + our parameterized chunk_size in chunked_prefill.
- lfm2 integration tests (origin/main #64): added the MTP ChatConfig
  fields (enable_mtp/mtp_depth/mtp_adaptive_depth: None) that our branch
  introduced and the new lfm2 test literals lacked.

Verified: build OK; mlx-core 1654 pass / 3 pre-existing Metal-f32 env
failures (sources byte-identical to origin/main); paged-attn OK; clippy
-D warnings clean; fmt clean; typecheck OK; TS 1260 pass / 6 missing
gitignored-GSM8K-fixture failures (present in main checkout).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 9, 2026
…#93)

## What

CI's rolling `stable` toolchain bumped to **rustc/clippy 1.97.0
(2026-07-07)**, which added the **"redundant reference in `format!`
argument"** lint. That trips the existing `cargo clippy --all-targets --
-D warnings` gate on a pre-existing line in
`crates/mlx-core/src/tools/mod.rs`:

```rust
error: Some(format!("Tool call missing name: {}", &raw_content)),   // &raw_content is now flagged
```

This is what turned the **Rust Lint → Clippy** job red on `main` (first
failure on #89, then the #90 merge — run `29022183758`). The code itself
dates back to #64; nothing on #90 touched it — a toolchain bump surfaced
it.

## Fix

Inline the captured identifier:

```rust
error: Some(format!("Tool call missing name: {raw_content}")),
```

`raw_content` is still moved into the struct field on the next line, so
behavior is unchanged.

## Verification

Reproduced the CI toolchain locally (`rustup update stable` → clippy
`0.1.97 (2d8144b788 2026-07-07)`) and ran the exact gate:

```
cargo clippy -p mlx-core --all-targets -- -D warnings
    Finished `dev` profile in 2m 34s   # exit 0, no redundant-reference error
```

Only remaining output is the pre-existing `block v0.1.6` future-incompat
note (present on all green runs; not a `-D warnings` failure).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> One-line formatting change in an error message path; no logic or API
changes.
> 
> **Overview**
> Unblocks **Rust Lint → Clippy** on CI after **clippy 0.1.97** started
enforcing the redundant-reference-in-`format!` lint under `-D warnings`.
> 
> In `ToolCallResult::missing_name`, the error string now uses inline
capture (`{raw_content}`) instead of `{}", &raw_content`. The message
and move semantics are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
44cc4cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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.

1 participant