Skip to content

metal/model-hf: LFM3 MLX folder map, pins, and the Metal kernels (M0+M1) - #932

Merged
midagedev merged 16 commits into
mainfrom
mac-lfm3all
Oct 28, 2026
Merged

midagedev merged 16 commits into
mainfrom
mac-lfm3all

Conversation

@midagedev

Copy link
Copy Markdown
Owner

LFM3-1.7B on Metal, first two steps (M0 and M1 of the LFM3 plan). The leader's C0 (#924) and C1 (#930) are the CUDA and common side. Metal opens MLX folders only.

M0: the MLX folder and the HF tokenizer path

  • model-hf/src/arch/lfm3.rs: a new folder map for LiquidAI/LFM3-1.7B-MLX-4bit.
    • It writes the names and keys of llama.cpp's lfm3 converter.
    • Conv taps [2048,7,1] become [7,2048].
    • rope_freqs.weight is made with the converter's exact values (32 × 1.0, then 32 × 1e30).
  • folder.rs and part.rs gain made constant tensors (Make::Constant).
  • trunk.rs gets a shared tie rule. tie_word_embeddings is held against the absence of lm_head, and either mismatch is a named error. qwen35moe and minimaxm3 still refuse true.
  • hf/src/vocab.rs:
    • the lfm2 pre-tokenizer row (llama3 regex, ignore_merges held to the row);
    • the ByteLevel (true,false,true) post-processor;
    • LFM3's extra config keys, each read or refused by name.
  • tools/mlx-logits.py dumps an lfm3 folder through mlx-vlm's lfm3 (mlx-lm has none yet). The pin starts at BOS 124894: id 0 makes this model degenerate in mlx-vlm itself.

M1: Metal kernels, against an f64 oracle with mutants

  • shortconv.metal: C ⊙ conv(B ⊙ x) for any number of taps (7 for LFM3, 3 for LFM2.5), with a ring of u per slot. It has decode, rows and a ring commit.
  • norm_add_rows: the sandwich residual x += add · gain ⊙ rms_norm(out), with the norm's sum order.
  • Attention:
    • a sliding window (keys [p−w+1, p]) on decode, rows and prefill;
    • a per-head output gate (OutGate::ProjHead);
    • rope factors, which are a table recipe and not a kernel input.
    • Both new axes compile only where the instance has them. A gate-only instance lfm3_attn (head 128, group 4, opens: false) carries the kernel clauses until M2 wires the session.

Program identity. Existing programs are unchanged: a metal-compare against the base gives pipelines added=4 removed=0 changed=0 same=195, and the encode traces and generated ids at depth ~0 and 600 are identical.

Evidence

  • Second Mac (M1 Pro):
    • cargo test -p bloomery-hf -p bloomery-model-hf: all ok;
    • gate_metal_qwen35moe_kernels: 6 instances PASS;
    • --mutants-all: every mutant red on its clause (qwen35moe_a3b 187, qwen3moe_a3b 83, lfm3_attn 18, and the rest);
    • clippy 0.
  • just remote-static origin/main: every step rc 0.
  • Box, fixture tier: affected selected 19 gates; 8 ran, red 0. Seven were deferred to the real tier and four for an env.
    • Of the needs-env four, I ran gate-hf-minimax and gate-minimax31-folder with /models/MiniMax-M3.1-Flash: both green.
    • gate-hf-vocab-qwen38 and gate-prepare-corpus stay deferred: the box has no Qwen3.8 NVFP4 HF folder.

Also here:

  • metal_scan.rs:567 was red on main under the Mac's clippy since redundant_clone became deny (lints: seven lints the mac crates cleared become deny #922). The Linux cross lint does not build the metal crate. Now cargo clippy -p bloomery-metal --all-targets is 0 on the second Mac.
  • nemotron_h.rs tests get the Make::Constant arm; tools/model-tax.tsv gets an lfm row for the Metal instance table.

AI use: written and checked with Claude Code.

🤖 Generated with Claude Code

https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd

midagedev and others added 13 commits October 29, 2026 01:47
…el (true,false,true) and LFM3's extra config keys

minimax_encode's every_pre_row_has_a_hugging_face_reading stays red until crates/tokenizer gives lfm2 a reading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01X1hsQfNpqr2jqmpYe8SFXd
@midagedev
midagedev enabled auto-merge (rebase) October 28, 2026 16:55
@github-actions github-actions Bot added model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: MUST_FIX: the encode path now allocates per launch, and helper sets are copied inside the metal gate crate.

Must fix

1. The host encode path allocates a Vec per launch (R39)

norm.rs:137, attention.rs:329, shortconv.rs:222. Before this PR the argument words were stack arrays (args_bytes, pack). Now with_window does words.to_vec() on every flash, rows and prefill launch, even with no window. encode_norm builds two Vecs per norm_rows call. shortconv_step collects pos into a Vec. Term: attention_flash is the decode launch (arch/qwen3moe/ops.rs:316), so qwen3moe decode gains 1 allocation per layer per token; norm_rows gains 2 per call. R39: a step does not allocate. The fix is cheaper now, before M2 wires the session on these functions.
Fix: keep fixed arrays and send a prefix. For the norm:

        let words = [
            word(what, "cols", p.cols)?,
            p.layer,
            p.eps.to_bits(),
            word(what, "the x stride", p.x_stride)?,
            word(what, "the y stride", p.y_stride)?,
            add.map_or(0, f32::to_bits),
        ];
        let args = words.map(u32::to_ne_bytes);
        let sent = &args[..5 + usize::from(add.is_some())];
        // ...
        slot.set(Binding::bytes(sent.as_flattened())?)?;

For attention, make with_window return a fixed array and a count, and bind &words[..len].as_flattened(). For shortconv_step, fill a [u8; 4 * MAX_SLOTS] and bind its first 4 * slots bytes.

2. Copied helpers in the metal gate (one owner per fact)

  • Ev, Ev::zero, Ev::exact, mul, fma: oracle_shortconv.rs:51 copies oracle_delta.rs:56-105 line for line. They are the error-bound arithmetic of the f64 referee. If one copy is corrected, the other keeps the old bound and its gate stays green. Fix: move the five items to shared/oracle.rs (it owns U) as pub(crate), and use super::oracle::{Ev, fma, mul} in both.
  • ratio: clauses_window.rs:646 equals clauses_rows.rs:1085. Keep one in common.rs.
  • strided: clauses_shortconv.rs:813 is strided_rows (clauses_rows.rs:1371) with a pad argument. Keep the pad form in common.rs, pass f32::NAN from rows.

Non-blocking

⚠ Future-dated pin: model-tax.tsv:140 adds PIN(2026-10-29) for the lfm instance row. The other rows added in this PR say 2026-10-28. Use the date the pin is made.

⚠ The widened post_processor list at vocab.rs:220 (byte_level!(true, false, true)) is a loosened gate. The PIN(2026-10-28) line in the test names ignore_merges and extra_special_tokens only. Name the post-processor there, with the evidence that LFM3's file spells it so.

Checked

  • Duplicates: about 40 new items checked. Dryer pairs: the three in finding 2 are real. Kind::label and header share a shape only.
  • Complexity: crapper's large functions are all new; case tables, old bodies with a layer argument, or even growth. No split asked.
  • Silent failure: 9 sites followed (tied, check_head, ignore_merges, partial_rotary_factor, planned_constant, the squeeze check, window 0, head-gate length, ring rows). Each reaches a named error or the fault word.
  • Kernels: the window clauses hold; a prefill tile before the first live key has factor 0, so no NaN.
  • Tests: three planted mutants (check_head, ignore_merges, constant collision) turn red. The Metal clauses were not run here.
  • Gates: ignore_merges, the post-processor and extra_special_tokens are widened (⚠ above). No band moved.
  • Escape catalog: no match.

Notes

  • The PR body has no nvidia-smi line and no just gate-* output from a CUDA card. The PR touches no CUDA crate.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev

Copy link
Copy Markdown
Owner Author

Review fixes:

  • Must fix 1: norm, attention and short conv bind a prefix of a stack array, so no launch allocates (4941cd1).
  • Must fix 2: Ev/mul/fma live in shared/oracle.rs; ratio and strided live in the kernel gate's common.rs (f9db032).
  • The vocab pin now names the post-processor (2bd56fd).
  • The PIN date stays 2026-10-29: that row was made on 2026-10-29 (00:35 KST).

Evidence on the second Mac:

  • clippy 0; kernel gate PASS on 6 instances; mutants-all red on every clause on all 6.
  • metal-compare against main: added=4 removed=0 changed=0 same=195.
  • Encode traces (they record the bound bytes) and ids are identical at depth 0 and 600.
  • just remote-static origin/main rc 0.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: CLEAN: both earlier must-fix items are fixed in the new commits, and the new lines hold on every input I built.

Since the last review:

  • Must fix 1 (a Vec per launch, R39): fixed. LaunchArgs in attention.rs:328 is a fixed array plus a length. encode_norm in norm.rs:141 sends a prefix of a stack array. shortconv_step in shortconv.rs:222 fills a stack array and binds pos[..slots].
  • Must fix 2 (copied helpers): fixed. Ev, mul, fma live in oracle.rs; ratio and strided live in common.rs. Grep finds one definition of each.
  • ⚠ Future-dated pin: still open, model-tax.tsv:140 still says PIN(2026-10-29). The other rows say 2026-10-28. Use the date the pin is made.
  • ⚠ Post-processor pin: answered. The PIN(2026-10-28) comment in vocab.rs now names the (true, false, true) post-processor and why it acts on no text.

Checked

  • Duplicates: 4 new items checked (LaunchArgs, MAX_ARG_WORDS, SHARED_WORDS, the moved helpers). No duplicate remains. Ev is pub(crate) in oracle.rs, and both probe bins that include it already carry allow(dead_code).
  • Complexity: no function in the new commits grew by branches. bind_flash growth is the earlier even growth, and the new commits only change the argument type.
  • Silent failure: 3 sites followed. with_window has a const assert that N < 12, so a 12th word cannot overflow. In shortconv_step, slots > MAX_SLOTS is refused before pos[..slots], and the zip cannot truncate because slots = p.pos.len(). In the norm, add: None sends 5 words as before, and Some sends 6.
  • Performance: the decode launch no longer allocates. The shortconv step zeroes a 4 KiB stack array per call (MAX_SLOTS = 4096 / 4 words) and binds 4 · slots bytes. No heap term.
  • Tests: no test changed in these commits except call-site moves to common::strided and common::ratio. Mutant: a wrong pad at a call site would still turn the NaN-poison clauses red.
  • Gates: no band, tolerance or lint level moved in the new commits.
  • Escape catalog: no match.

Notes

  • The PR body has no nvidia-smi line and no CUDA just gate-* output. The PR touches no CUDA crate. The Metal gate runs on the author's Mac were not run here.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@midagedev
midagedev merged commit 19a4510 into main Oct 28, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant