Repository navigation
gemma4 Metal: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B) on M1 to M4, per-layer inputs and shared KV - #2273
gemma4 Metal: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B) on M1 to M4, per-layer inputs and shared KV#2273Mirrdhyn wants to merge 36 commits into
Conversation
|
Thanks @Mirrdhyn, this is a careful first half: the E4B admitted by its own geometry with every other layout still refused, the 24 cache-owning layers counted in snapshots and the pool, forced logits within near-ties of the same weights in fp32, resumed equal to fresh at 15 seams, and the 12B and 31B byte-equal against main with a big one-stream gain on the 12B. A few things before we run anything on our side:
The loader changes ( |
|
Thanks. Pushed 1. How the per-layer math was written. The steps are Gemma 4's per-layer input. For each step's order and bf16 rounding points we read mlx-lm 0.32.2's
The host's 2. M5. The E4B is now refused by name on a chip with tensor units: 3. Planted control and rotary. 4. The 12B and 31B on M5. No M5 here either. What I changed and checked:
If someone with an M5 can run |
6c69990 to
4fdbc21
Compare
|
Thanks @Mirrdhyn, for the clear account and for items 2 and 3. The M5 refusal is by name with a test, and the On item 1: since |
|
Thanks. Rewritten as you asked: head
Checks on this code: lean 210 → 210, |
|
Thanks, @Mirrdhyn. The mlx-lm citations are gone, What's left:
|
… and the credit (ashhart#2273)
|
Thanks, @ashhart. All three are done, in two new commits on top of
|
|
A correction to my comment above and to my 2026-11-06 one: DeepMind's code does apply the 1/√hidden scale. It is not in |
|
Thanks, @Mirrdhyn, for the journal and for writing down where the We've read the journal, and we accept the clean-room account. The writer had TensorFold excerpts with the bodies and the old op comments removed, plus DeepMind's A few small things:
We don't need a second room for the combine. |
|
Thanks, @ashhart. Done in three new commits on top of
No arithmetic changed. Checked on the Mac: lean 210 → 210,
|
|
Thanks @Mirrdhyn. All of the 8 Nov asks are met:
A few things before we run anything:
The CHANGELOG conflict is ours. A clause on the 12B's faster one-stream decode would help readers. |
|
Thanks @Mirrdhyn, and thanks for turning the 8 Nov items round so quickly. We've looked at taking the rest of this over ourselves, and one thing stops us: the converter. Where
Still open from our last note, which we're glad to do on your branch once the converter is settled:
After that, we'll check the 12B and 31B against main on an M5, and the E4B on an M1 to M4 chip.
|
|
Copying here what I sent on Telegram, so it stays with the PRs. @ashhart, you now have write access to hygurlabs/TensorFold-working-branches, so main can be merged into my branches directly, with no rights issue. That should spare you the separate landing PRs (#3722, #3340, #3960) from here on. Where things stand, as I read them
What we still owe you on #3052
One question on item 1: it waits on #2595, which is not ours and still has open items. Is there anything we can do to help it land, or should we measure on main in the meantime? #2273: where It was not worked from MLX's source. It is a numpy port of TensorFold's own The note at I will replace the MLX references in the comments at Once that is settled for you, your offer to do the row twin and the rebase on our branch would help a lot. One request: if you push to a branch we are still working on (#3052, #2273), a short note on the PR helps, so we pull before pushing. |
…ayers when the chunks read on (ashhart#1222)
…layers they run only (ashhart#1222)
…egisters, per-layer kernels 2x faster (ashhart#1222)
…axis, 64 threadgroups to 1088 on 515 rows (ashhart#1222)
…runs it in fp32 with --fp32 (ashhart#1222)
…l_main stays at 600 lines (ashhart#1222)
…ion w_scale, in the kernel, the dispatch and the notices (ashhart#1222)
…me the removed gelu kernel or its constants (ashhart#1222)
…s takes the tiles after its first window (ashhart#1222)
…of quantizeGroup checked against mx.quantize's outputs (ashhart#2273)
|
The current zig build test-gemma4-prompt-head-host -Dcpu=apple_m1 \
-Doptimize=ReleaseSafe -j2 --summary allI tested a scratch correction confined to the host fixtures: extend the recording Metal stub with rejecting methods for real Metal operations, make the row projection test helper use the actual pipeline ID type, and assert that a zero-row call returns before GPU work. The same target passed 193 tests with two skips. The converter unit suite also passed 11 tests on the PR’s exact source. The Metal fixture check runs without a real GPU, so device inference remains separate. Igor Lessio - AIFLOW LABS |
…er contents, so the prompt head's twin check compiles
|
@AIFlowML thanks for the exact command. |
|
Thanks @Mirrdhyn for the E4B Metal implementation and detailed host references. One host-oracle issue needs fixing before this can merge. The native E4B row path packs all gate rows before all up rows, but the FP64 gate/up comparison constructs alternating 16-row gate/up blocks. Its FP32 emulation repeats that order. On any checkpoint where gate and up differ, both window and tile outputs are therefore compared against mismatched reference columns. Please use concatenated gate-then-up matrices for both the direct and emulated E4B row-path references, then rerun the gate/up window and tile checks before the prompt-boundary and resume comparisons.
|
|
Fixed in Rerun on an M4 Max (no tensor units), on the checkpoint and ids of the earlier receipt:
A correction to the earlier receipt, found on the way: Merged main ( On the merged head:
One note: The Metal checks ran on a Mac shared with desktop apps, at 23 % to 99 % GPU utilization. All of them are equality checks. |
|
Thanks @Mirrdhyn for correcting the gate/up reference and clearly withdrawing the invalid long seam results. The concatenated references, short-input guards and runtime row-twin fallback are present. The E4B chunk path still rounds each decoded affine weight to BF16 before multiplication. The serial row path keeps the stored scale/bias computation, so those operations can differ. The row-width equality checks and FP64 error bounds do not cover that distinction. Please keep the checkpoint's stored affine values and serial arithmetic on that chunk path, with a deciding cancellation case and exact row-versus-served-prompt comparisons. The converted checkpoint itself is fine; the extra runtime rounding is what needs changing.
|
What this changes
The Metal half of #1222: Gemma 4 E4B served on Apple GPUs without tensor units (M1 to M4), on the family plan already in main.
Converter.
tools/zig/gemma4_e4b_convert.py --dense-pleturns NVIDIA's BF16 release into MLX affine 4-bit, group 64, under mlx-lm's names, the per-layer linears kept bf16 (the engine refuses them quantized by name).mlx_lm.convertalone is refused at load for that reason.Per-layer inputs.
ple.metalanddense.metal: the per-layer projection, the gathered table row, the 256-wide norm and the mix once per forward; per layer, the gate on the residual with the tanh GELU times the layer's slice as its epilogue, the projection and the post norm. The gate spreads K over five simdgroups and its rows over a second grid axis; the bf16 linears keep each row tile's accumulators in registers. The combine, the gate's epilogue and the layer tail follow DeepMind's release code (encode_per_layer_inputand the Block's per-layer-input step ingemma/gm/nn/gemma4/_modules.py, Apache-2.0, entry inTHIRD_PARTY_NOTICES.md); their bf16 rounding points were chosen by comparing outputs, in a clean room described below.Shared KV. Layers 24-41 read the caches of 22 and 23 and write nothing; snapshots and the pool count the 24 owning layers only.
Prompt. Chunks run on
affine_mm's tiles with the per-layer inputs. Where the layers past the cache-owning ones need not run (the E-series), the chunks and the first 128-row window stop there and the last row alone runs the rest; the skipped part projects only the per-layer inputs it uses. Models without shared layers (12B, 31B) keep one pass.Memory. Without tensor units, one copy of the projections and of the tied table.
Row path, whole family. One- and two-row windows take the row tiles' scalar twin, bit-equal to the tiles. It reaches the 12B and 31B too: same bits, and one-stream decode on the 12B goes from 38.5 to 54.0 tok/s on an M4 Max.
Tools.
tf-gemma4-e4b-ple(+ host check againstlayer_input.zig),-logits,-prompt-logits,-seams,-projections;gemma4_e4b_fp64.pyandgemma4_e4b_gate_fp64.py;gemma4_e4b_reference.py --quantreads this checkpoint's prefix and--fp32runs the reference in fp32 without bf16 rounding of the dequantized weights.Recipe
docs/recipes/gemma-4-e4b-native.md, changelog.Issue: Refs Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B): per-layer inputs and shared KV, Intel Arc first #1222 (the Metal half; the CUDA half landed as gemma4 CUDA: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B), per-layer inputs and shared KV #2230).
Stacked on: main
c3f64ca8a, nineteen commits (7e9d9df8to194400c4). The last one moves Gemma's embedding probes into their own Suite inmetal_gemma4_embed.zig, as 5fe04fa did for qwen27, sometal_main.zigstays under 600 lines.atc overlap --json(on the previous base1d891001b): CHANGELOG.md only, against CI: main's build cache fits every runner, and release-paths and macOS use it too #2252, since merged, and nemotron metal: one decode attention partial source for its 16 host names (#2251) #2263; no code conflict with an open pull request (the run is incomplete: some pulls' files were unavailable).M5 is refused for the E4B. On a chip with tensor units
Model.loadstops withGemmaE4bNotQualifiedWithTensorUnitsandservesays "Gemma 4 E4B is not qualified on chips with tensor units (M5); it runs on M1 to M4". The 12B and 31B are not refused and keep main's fused lane path there. I have only an M4 Max: nothing ran on an M5.Checks on this head
194400c4. Lean and the filtered contract ran on it; build,zig build test, the E4B's logits, seams, concurrent runs and the 12B/31B comparison ran on0f00e4ff, the same code (two comment lines differ). The prompt widths and--only embeddingran on4fdbc2152, whose code differs only in the per-layer kernels. The fidelity and speed receipts below ran one5e79015e(this branch on an earlier base); the E4B's logits on this head are byte-equal to that run (16 of 16 at width 16).git diff --checkclean.zig build testfrom a fresh cache, 11002 of 11087 tests pass, 1 fail:exl3_load"a scan that fails an allocation frees every group prefix it held" (NondeterministicMemoryUsage), which fails the same way on main without this branch;gemma4_e4b_convert_test.py11 pass.prefill_widthslike main's chunk loop since 5b92873: a 24-token prompt gives[24], a 1,174-token one[128, 384, 512, 149, 1](the last row runs alone), each summing to the prompt.tf-kernel-contract --only E4B):SUMMARY 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 1 controls: 1 red as planted, 0 missed; 0 limit problems(the control isgemma_dense4with its K loop one 256-deep step short);--only ple:SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 1 controls: 1 red as planted, 0 missed; 0 limit problems.gemma_ple_midis gone: no path dispatched it (the gate's epilogue does that step), so its kernel, pipeline and contract entry were removed.--only embedding:SUMMARY 24 kernels: 24 pass gates 1-4, as on main.tf-rotary-sweepwrote its receipt (302,008,320 cases); the unfiltered run with--rotary-accuracythen stops before its SUMMARY on this M4 Max at main's check "UNSUPPORTED gemma4 31B rounded dense: tensor units required; Gemma coverage unchecked".serveof the 31B on this 64 GB machine (refused at load on main and on this branch alike, "0.00 GiB left under the load limit"); images and audio (the converter drops both towers); drafter (refused for the E4B)._modules.py(revision9e1f74131ba9) into files whose old bodies and descriptive comments had been removed beforehand; it received only numbers back (the per-layer tool's differing values and max gap, logits "X of 16 equal"), plus one generic remark from the supervisor ("two formulas of the same op can round differently"), logged as such. Eight attempts reached 16 of 16 and the per-layer tool's floor of the old code (2 of 118,272 and 18 of 1,182,720). The journal lists the files given with their sha256 and every attempt; I can attach it. No commit in this branch carries the earlier code: the history was rewritten so each commit holds the new text, and every commit builds.Receipt
nvidia/NVIDIA-Nemotron-3.5-Bolt-E4B-BF16at49843eed8db1, converted withgemma4_e4b_convert.py --dense-ple(numpy 2.5.4):model.safetensorssha25648f965c8d7f4…, reproduced byte for byte. Reference: transformers 5.22.1, torch 2.15.0, mlx 0.32.4, mlx-lm 0.32.2.tf-gemma4-e4b-logits,gemma4_e4b_reference.py --quant,gemma4_e4b_compare.py), 617 positions:against transformers on the same 4/64 weights in fp32 (
--fp32): 613 top-1, KL mean 0.00032, max 0.019; the 4 misses are near ties:On the two exact ties Metal's argmax takes the lower index.
against the same weights in bf16 (the script's default, as gemma4 CUDA: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B), per-layer inputs and shared KV #2230): 611 top-1, KL mean 0.00060, max 0.028, 6 misses, all near ties;
against BF16: 579 top-1, KL mean 0.0734, the same as transformers on the 4/64 weights (578, 0.0737).
gemma4_e4b_fp64.py, 64 rows, 9 layers), error over Σ|x||w| in units of 2^-8: rms 0.02 to 0.05 by class (0.26 for the per-layer projection), worst 1.09 (down, tiles). The prompt tiles' rms is 1.13 to 1.22 times decode's, their worst ondown1.52 times: the tiles' chunked fp32 sums differ from decode's. Per-layer gate (gemma4_e4b_gate_fp64.py): 15 of 147,456 values differ, worst 2.9e-3.tf-gemma4-e4b-pleagainstlayer_input.zig, 2 of 118,272 differ (max 1.5e-3).bench_concurrent.py --alone --serial, T=0 and T=1, two passes): concurrent equals alone and serial, 0 unequal; prompt cache on against off: 9 of 9 turns equal, 3,584 tokens read from the cache on the resumed ones.bench_openai.py, median of 5): one stream 98.6 tok/s in chat, 201.7 on a raw prompt. Together (bench_concurrent.py, T=0): 1, 2 and 4 streams 99, 151 and 212 tok/s in chat, 195, 331 and 424 on code.bench_cache.py --require-cold, first request):ttft_s1.073, 1.228 and 2.658 at 2,571, 2,923 and 6,422 tokens (2,397, 2,380 and 2,416 tok/s), equal over two passes. The engine refused the E4B on Metal before, so there is no before.002c9e03; after the rebase the E4B's logits and the 12B's tokens and logits are byte-equal to that run, and one pass of the E4B's speeds matches it:google/gemma-4-12B-it707f0a3b,gemma4_12b_convert.py): last-row logits, greedy tokens and top-2 byte-equal at widths 512 and 1 on 3 prompts,token_shaequal on 5; one stream 38.5 → 54.0 tok/s; 4 streams code 122.5/122.7 → 123.4/122.7, chat 116.6/116.0 → 116.0/115.9; cold prompt within ±3 % without direction.mlx-community/gemma-4-31B-it-4bit696d436c): the same byte-equality at widths 512 and 1 (tf-gemma4-run); speed not measured,serverefuses it here on both arms.