Skip to content

core: one MLX affine module reader for the Metal families (#2460 item 7) - #2583

Merged
ashhart merged 6 commits into
ashhart:mainfrom
jschmied:core-mlx-reader
Nov 11, 2026
Merged

ashhart merged 6 commits into
ashhart:mainfrom
jschmied:core-mlx-reader

Conversation

@jschmied

@jschmied jschmied commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

The first step of item 7 of #2460 ("one loader per weight format"). Before: five Metal loaders each built
{module}.weight, .scales and .biases by hand and checked the three shapes in their own way: qwen3_5
(projection, fixed 4-bit g64), lfm2_moe (affine, fixed bits, g64, count 0 = rank 2), lfm3 (Loader.affine,
width from the config), and minimax_m3 and step5 (two identical copies of checkedAffine, bits and group read from
the stored shapes; the MiniMax DFlash2 and DSpark drafters call MiniMax's). After: one reader in
core/quant/mlx_affine.zig: read(checkpoint, module, want) gets the three tensors and check refuses anything
but u32 words [.., n, k * bits / 32] and bf16 tables [.., n, k / group] with every byte accounted for. want gives
the stack (1 = one projection, rank 2), n, k, and the bits and group when the family fixes them (otherwise they
come from the shapes, as MiniMax and Step-5 did). row_projection.affine turns a checked triple into the row kernels'
Weights at the tensors' own buffer offsets. The reader returns views of the checkpoint's tensors, so the bytes the
kernels read are the same bytes as before.

Per family, what stays its own: lfm2_moe keeps its 4-byte offset check; lfm3 keeps its tensor() (bounds,
alignment, and the seen set it uses to refuse stray tensors) and takes only the dims from core; qwen3_5 keeps its
Linear type; MiniMax's norm check now calls the core require (same rule, same error name). Step-5's two loader tests
move to core/quant/mlx_affine_test.zig unchanged (error name UnexpectedAffineTensor).

Not in this PR (next): gemma4/weights.zig, spark25/{metal_,}weights.zig, qwen27/checkpoint.zig, nemotron,
glm/weights.zig, Flash-Next (load_weights, rows_load, pack*), and the XPU loaders (lfm3/xpu_model.zig) read
other forms (deferred tensors, packed caches, host copies) and need their own step. The three affine metadata modules
(flashnext/affine.zig on safetensors entries + Spec, glm/affine.zig on refs/runs, qwen27/affine.zig on
config specs) have three different APIs, so merging them is not a byte-equal move; listed as the next PR.
lfm3/weights.zig (header schema) is unchanged: test-lfm3-host builds it as a module rooted in families/lfm3, which
cannot import core by path.

Checks on this head

  • Head commit: cfa7c87
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 116 on the base (5874551), 116 on this head, 0 new.
  • Tests run, with the command and pass, fail and skip counts: zig build test test-golden test-cuda-host (aarch64
    host, -Dnvcc): 612/612 steps, 7581 passed, 0 failed, 63 skipped. zig build -Dfixed-cpu test-kernel-contract test-server-security test-pull-security fuzz-cortheon check-release-paths: green. zig build check-native-cuda-host compile-cuda-tests -Dtarget=x86_64-linux-gnu: green. python3 tools/pr_check.py: 0 errors (1 warning: the
    Unreleased line needs --pr). zig fmt --check build.zig zig and git diff --check: clean.
    New tests (core/quant/mlx_affine_test.zig, run by test-quant-geometry-host): Step-5's two cases (expert axes,
    rank, bytes, packed widths); a fixed width refuses another width's shapes, a table one group too long and fp16
    tables; dims for stacks and uneven K; a file-backed safetensors with one module in each family's form (fixed and
    inferred widths, 2 to 8 bits, groups 32 to 128, stacks) read back with the written shapes, dtypes and byte hashes.
    Each fails against a fault planted in a scratch copy: tables one group too long in dims (5 tests fail), scales
    checked as fp16 (4), inferred bits off by one (3).
  • CI: green on cfa7c87 (zig, zig-windows, zig-macos-dev-tools, fmt, release-paths, benchmark-clients).
  • Not run, and why: Metal served greedy for the four families without a loadable MLX checkpoint on the Mac (below).
    CUDA serving: none of the changed code is in the CUDA build; zig build native -Dsm=121 of main and of
    this head in the same worktree path gives the same tensorfold-native (md5 eeb95dd7 both), so no served CUDA run.

Receipt

  • Main against branch, same loader, on Linux with a recording stand-in for the Metal device (host memory buffers): each
    family's real load() on the local checkpoint, every affine module and tensor dumped (buffer, offsets, n, k, bits,
    group, expert count and repeat, Wyhash of the bytes the kernels read).

    checkpoint family affine modules dump md5 main dump md5 head
    LiquidAI/LFM3-1.7B-MLX-4bit lfm3 154 c9d2c192 c9d2c192
    LiquidAI/LFM3-VL-2B-MLX-4bit (8-bit embedding, g32) lfm3 154 359f2b6a 359f2b6a
    LFM2.5-24B-A2B MLX 4-bit lfm2_moe 221 (incl. 64-expert stacks) 30ccd3fd 30ccd3fd
  • Qwen3.5-2B, MiniMax-M3.1-Flash and Step-5: no checkpoint on this machine. Main's per-module code (copied from
    5874551) against the new path on synthetic triples: widths 2 to 8 bits, groups 16 to 128, stacks 1 to 8, n 8 to 40,
    K 64 to 512, each as stored and with 39 random planted changes (one dim, a dtype, an offset, a table byte count, a
    dropped rank):

    reader on main cases both accept, same view both refuse differ only head accepts only main accepts
    checkedAffine (MiniMax, Step-5) 85120 12978 72142 0 0 0
    lfm2_moe affine 85120 1339 81646 0 0 2135
    qwen3_5 projection 21280 240 20952 0 0 88
    lfm3 Loader.affine (stored width / another width) 21280 / 21280 3778 / 154 17502 / 21126 0 0 0

    "Only main accepts" is one case alone: a table whose byte count is not its shape's extent, which main's Qwen and
    LFM2 readers did not check. The safetensors parser already refuses such a tensor (end - begin must equal the
    shape's bytes), so no checkpoint that loads on main is refused on this head.

  • Metal, M3 Pro: zig build test 760/760 steps on both, 11654/11746 main and 11696/11788 branch (92 skipped each; +42 =
    the new reader tests); test-step5-host + compile-step5-host 14/14. Qwen3.5-2B MLX 4-bit served greedy, main ==
    branch byte-equal on 4 prompts (text and token hash), solo and 4 concurrent. LFM2.5-24B, LFM3, MiniMax and Step-5
    have no loadable MLX checkpoint on that Mac (size or quantization): Linux load dumps and unit tests cover them.

  • Boxes it reaches: the Metal load of qwen3_5, lfm2_moe, lfm3, minimax_m3 (+ DFlash2, DSpark) and step5.

  • New switch? None.

  • Environment: TensorFold cfa7c87 on main 5874551; Zig 0.17.0; aarch64 Linux (GB10) for the host checks.

  • Exactness: the loaders return the same views (offsets, shapes, widths); no kernel or numeric change.

  • Decode speed before and after: n/a, load-time only. Prompt speed: n/a.

  • Licence of any new weights or drafter: n/a.

Checklist

  • The title and description match the head commit, including the receipt and the stack.

  • New tests fail before the change, pass after it, and skip cleanly without their dependency.

  • Comments and docstrings are one line. No measurements or history in the source.

  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.

  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.

  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.

  • No precision traded for speed. If the bits change, the description says which sums change and why.

  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled

@ashhart

ashhart commented Nov 8, 2026

Copy link
Copy Markdown
Owner

@jschmied thanks, a clean first step for item 7. Against main, all five families accept exactly what they did and get the same views, so loads are byte-equal. A few things before it lands:

  1. CHANGELOG: please add a line, e.g. "Metal: Qwen 3.5, LFM2-MoE, LFM3, MiniMax-M3 (with its DFlash2 and DSpark drafters) and Step-5 read MLX affine modules through one core reader, core/quant/mlx_affine.zig; loads are unchanged, and a refused module now reports UnexpectedAffineTensor and names the module (core: one MLX affine module reader for the Metal families (#2460 item 7) #2583, part of RFC: families compose core blocks: a conformance kit first, then sampler, config, drafter and format loaders #2460). Thanks to @jschmied."
  2. spark25: spark25/metal_weights.zig:86 affine looks like Qwen 3.5's form (views, fixed bits, g64, rank 2) with its own require. Could it move here too, or what keeps it apart?
  3. Duplicates: step5/tensor_shape.zig require now matches mlx_affine.require apart from the error name; could step5 call the core one? And core/quant/mlx_geometry.zig already checks affine geometry. Please say why the two stay separate, or what merging would change.
  4. lfm2_moe: the misalignment refusal at weights.zig:47 no longer logs which module failed. A one-line std.log.err would keep that.
  5. Tests, if cheap: a refusal case per family through its own loader (lfm2_moe misalignment, lfm3's UnsupportedQuantization, Qwen 3.5's fixed width).

jschmied added a commit to jschmied/TensorFold that referenced this pull request Nov 9, 2026
@jschmied

jschmied commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart. Pushed ed588c6 and 11084be:

  1. CHANGELOG: your line, verbatim, under Unreleased.
  2. spark25: moved. metal_weights.zig affine is now mlx_affine.read(c, base, .{ .n, .k, .bits, .group = cfg.group }) + row_projection.affine, so a refused Spark module reports UnexpectedAffineTensor and names itself. Its require (still used for norms and the bf16 matrices) calls mlx_affine.require and keeps UnexpectedSparkTensor.
  3. step5: tensor_shape.require now calls mlx_affine.require and maps to UnexpectedStep5Tensor, so the check exists once and Step-5's error name (used for its non-affine tensors too) stays.
    mlx_geometry vs mlx_affine: they check different contracts. mlx_geometry is the quant layer's format-generic geometry (core/quant/mlx.zig, experts.zig): it takes the config's bits/group, derives K from the tables, accepts i32 or u32 words and f16/bf16/f32 tables, and lets an uploaded buffer be longer than the tensor. mlx_affine is the Metal loaders' view reader: N and K come from the family, bits/group fixed or read from the shapes, only u32 words and bf16 tables, every byte exact. Merging one into the other either loosens the Metal loaders (f16 tables, i32 words they can't run) or tightens the quant path (refusing f32 tables and longer device buffers it relies on). The overlap is the shape cross-check; mlx_affine.check could call geometry.scalarShape for it and keep its own dtype/extent checks, but that also limits the derived width to 2..8 bits and changes the error raised for a mismatched triple. Happy to do that as a follow-up if you'd like one shape derivation.
  4. lfm2_moe: the misalignment refusal logs <module>: LFM2 affine tensors not 4-byte aligned again.
  5. Tests: not cheap through the loaders themselves. The lfm2_moe and Qwen 3.5 refusals log at error level (item 4), and Zig's test runner fails any test that logs an error. lfm3's Metal loader isn't in a test root that has both Metal and its rope_freq module. The forms themselves are covered in core/quant/mlx_affine_test.zig: fixed-width refusal (Qwen 3.5's), uneven K (LFM3's dims -> UnsupportedQuantization), stacks and fp16 tables.

Merge state: the only conflict with main is CHANGELOG.md (your line beside entries that landed since), so GitHub CI hasn't run on 11084bebe; the code commits merge cleanly. Happy to move the line wherever you like at landing.

@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@jschmied, thanks for the quick turnaround. The Spark move and the shared Step-5 check both read the same as before: the same views and accepted shapes, with Spark's and Step-5's own error names kept for their other tensors. Your reasons for keeping mlx_geometry separate make sense, and so does testing the refusals on the reader, given the error-log rule. Two small things before it lands:

  1. Spark. The second commit moved Spark onto the reader after the receipts were taken. Could you post main against branch for Spark on this head? A load dump like the LFM ones is enough, or a greedy token hash if you have an MLX-quantised Spark checkpoint on the Mac.
  2. The suite on this head. The Metal zig build test and test-step5-host counts, since tensor_shape.zig now uses the core check.

Optional: a Spark form (fixed width, group 64, rank 2) in the file-backed test in mlx_affine_test.zig, so all six families are pinned there. We'll add Spark to the CHANGELOG line when it lands.

@jschmied

jschmied commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@ashhart thanks. Both points on the head a8d638586:

  • Spark, main against branch. XHToken/Spark-X2.6-4B at 66e3ae7be, converted with tools/zig/spark25_convert.py --bits 4 (affine 4-bit, groups of 64, 2.15 GiB). Served by main (merge base 5874551fa) and by the branch on an M3 Pro (36 GB, no tensor units), --parallel 4 --context 4096 --prompt-cache-gib 0. Greedy, four chat prompts, 128 tokens, alone and then 4 concurrent: the token hashes are byte-equal between main and branch, and each server's 4-concurrent replies equal its solo ones. The load dumps (everything the server logs except request lines) differ only in the port and the load time (6.3 s / 5.1 s). So the reader serves Spark's affine modules as main did, through mlx_affine.read + rows.affine.
  • The suite on this head (-Dcpu=apple_m1, fresh cache dir so every test runs): zig build test 760/760 steps, 11,696/11,788 tests passed (92 skipped); zig build test-step5-host 9/9 steps, 15/15 tests. lean 116 vs 116 (0 new); pr_check --base 5874551fa --pr 2583: 0 errors, 0 warnings.
  • The optional Spark form (a8d638586, test only): mlx_affine_test.zig gains Spark's form, a fixed 8-bit width in groups of 64 at rank 2 (model.layers.6.self_attn.o_proj, [8, 256]), read through affine.read with bits and group fixed; its stored bytes, shapes and dtypes come back unchanged.

@ashhart

ashhart commented Nov 10, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied. Both points are covered on a8d638586. Spark's greedy replies hash the same on main and on the
branch, alone and four at once, and the load dumps differ only in port and load time. zig build test passes
760/760 and test-step5-host 9/9. With the Spark form in mlx_affine_test.zig, all six families are now pinned in
the file-backed test. Thanks for adding it.

Nothing else from us. The only conflict with main is CHANGELOG.md, which we'll settle at landing, and we'll add
Spark to your line then. Main is closed for a release right now. Once it reopens, we'll run our Metal cells and land
it.

@ashhart

ashhart commented Nov 10, 2026

Copy link
Copy Markdown
Owner

@jschmied our Metal cells on a8d638586 are in, main against this branch on an M5 Ultra. Qwen3.8-27B and LFM2 both read level on prompt passes, decode and chat, and 0 of 20 prompt rows differ across runs. It's on the landing queue now. We'll settle the CHANGELOG.md conflict at landing, with Spark-X added to your line as promised. Nothing needed from you.

  • Synthena (Ash's Agent)

jschmied and others added 5 commits November 11, 2026 18:04
core/quant/mlx_affine.zig reads a module's .weight, .scales and .biases and checks
them as one projection (u32 words, bf16 tables, every byte accounted for), with the
bits and group fixed by the family or read from the shapes. row_projection.affine
makes the row kernels' Weights from a checked triple at the tensors' own offsets.
qwen3_5, lfm2_moe, lfm3 (Metal), minimax_m3 (with its DFlash2 and DSpark drafters)
and step5 drop their own copies; the loaders return the same views as before.
Step-5's loader tests move to core/quant/mlx_affine_test.zig.

Refs ashhart#2460 (item 7)
…step5 and spark25 share its check

spark25/metal_weights.zig's affine (fixed bits, groups of 64, rank 2) is now mlx_affine.read plus
row_projection.affine, so a refused module reports UnexpectedAffineTensor and names itself. Its and
step5's exact-extent require call mlx_affine.require and keep their own error names. lfm2_moe logs
the module whose tensors are misaligned again.

Refs ashhart#2460 (item 7)
@ashhart
ashhart merged commit 4f57658 into ashhart:main Nov 11, 2026
3 of 10 checks passed
ashhart pushed a commit that referenced this pull request Nov 11, 2026
@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thank you @jschmied. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

@ashhart

ashhart commented Nov 13, 2026

Copy link
Copy Markdown
Owner

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.

2 participants