Skip to content

gemma4 Metal: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B) on M1 to M4, per-layer inputs and shared KV - #2273

Open
Mirrdhyn wants to merge 36 commits into
ashhart:mainfrom
hygurlabs:e4b-metal
Open

Mirrdhyn wants to merge 36 commits into
ashhart:mainfrom
hygurlabs:e4b-metal

Conversation

@Mirrdhyn

@Mirrdhyn Mirrdhyn commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

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-ple turns 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.convert alone is refused at load for that reason.

  • Per-layer inputs. ple.metal and dense.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_input and the Block's per-layer-input step in gemma/gm/nn/gemma4/_modules.py, Apache-2.0, entry in THIRD_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 against layer_input.zig), -logits, -prompt-logits, -seams, -projections; gemma4_e4b_fp64.py and gemma4_e4b_gate_fp64.py; gemma4_e4b_reference.py --quant reads this checkpoint's prefix and --fp32 runs 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 (7e9d9df8 to 194400c4). The last one moves Gemma's embedding probes into their own Suite in metal_gemma4_embed.zig, as 5fe04fa did for qwen27, so metal_main.zig stays under 600 lines.

  • atc overlap --json (on the previous base 1d891001b): 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.load stops with GemmaE4bNotQualifiedWithTensorUnits and serve says "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

  • Head commit: 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 on 0f00e4ff, the same code (two comment lines differ). The prompt widths and --only embedding ran on 4fdbc2152, whose code differs only in the per-layer kernels. The fidelity and speed receipts below ran on e5e79015e (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).
  • Lean checker on the base and on this head: 210 and 210, 0 new; git diff --check clean.
  • Tests run: zig build test from 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.py 11 pass.
  • Prompt widths: the E4B's prefill passes are counted in prefill_widths like 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.
  • Filtered Metal contract (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 is gemma_dense4 with 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_mid is 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-sweep wrote its receipt (302,008,320 cases); the unfiltered run with --rotary-accuracy then stops before its SUMMARY on this M4 Max at main's check "UNSUPPORTED gemma4 31B rounded dense: tensor units required; Gemma coverage unchecked".
  • Not run, and why: M1 to M3 and M5 (only an M4 Max here); serve of 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).
  • Clean room for the per-layer code: a fresh writer with no access to mlx-lm, MLX, the repository's history, the host reference or the old kernel bodies wrote the combine, the gate's epilogue and the tail from DeepMind's _modules.py (revision 9e1f74131ba9) 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

  • Environment: this head; Zig 0.17.0; Apple M4 Max, 64 GB; macOS 27.2, Xcode 27.2. Checkpoint nvidia/NVIDIA-Nemotron-3.5-Bolt-E4B-BF16 at 49843eed8db1, converted with gemma4_e4b_convert.py --dense-ple (numpy 2.5.4): model.safetensors sha256 48f965c8d7f4…, reproduced byte for byte. Reference: transformers 5.22.1, torch 2.15.0, mlx 0.32.4, mlx-lm 0.32.2.
  • Forced logits (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:

      prompt position reference → Metal margin ref margin Metal
      doc1500 2939 "training" → "data" 0.130 0.000
      french 46 "un" → "une" 0.011 0.125
      multiturn 65 "distinguished" → "classic" 0.013 0.125
      multiturn 83 "," → "or" 0.183 0.000

      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).

  • Projections against FP64 (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 on down 1.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.
  • Per-layer inputs: tf-gemma4-e4b-ple against layer_input.zig, 2 of 118,272 differ (max 1.5e-3).
  • Seams: a prompt resumed at 15 points from 40 to 1025 tokens equals the fresh one; window widths 1, 3 and 128 give the logits of width 16.
  • Served (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.
  • Decode (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.
  • Prompt (bench_cache.py --require-cold, first request): ttft_s 1.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.
  • Family, main against this branch, fresh server an arm, both orders (AB then BA), measured on the previous base 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:
    • 12B (google/gemma-4-12B-it 707f0a3b, gemma4_12b_convert.py): last-row logits, greedy tokens and top-2 byte-equal at widths 512 and 1 on 3 prompts, token_sha equal 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.
    • 31B (mlx-community/gemma-4-31B-it-4bit 696d436c): the same byte-equality at widths 512 and 1 (tf-gemma4-run); speed not measured, serve refuses it here on both arms.
  • Licence of new weights: n/a (no weights shipped; the checkpoint is NVIDIA's release).

@ashhart

ashhart commented Nov 5, 2026

Copy link
Copy Markdown
Owner

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:

  1. Where the per-layer math comes from. ple.metal says it computes the per-layer inputs "as mlx_lm's gemma4_text.py computes them", and the gate "as MLX's bf16 ops". Library code doesn't land here even with a notice, and we're settling how that applies to code that follows MLX and mlx-lm. So please say how these were written. If they come from the published model math and the checkpoint, and were only compared with mlx-lm's outputs, please say that in the comments. Comparing outputs is fine. If they follow mlx-lm's code, tell us which parts.
  2. M5. The E4B is admitted on chips with tensor units, but nothing has run there. Please refuse it by name on those chips until it's qualified, so the first release doesn't serve an unrun path.
  3. A planted control for the dense.metal kernels: --only E4B passes 5 kernels with 0 controls. One control that goes red at its gate, as ple has, would do. And the rotary sweep receipt the unfiltered run asks for.

The loader changes (k_norm only where a layer owns keys, and the v stand-in keyed on a missing v) reach every model, the M5 included, so we'll want the 12B and 31B byte-equal against main on an M5 before this lands. By reading, the M5's fast paths for those two are unchanged.

@Mirrdhyn

Mirrdhyn commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Pushed 313bb6ffe; each fix is squashed into the commit it belongs to.

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 gemma4_text.py and MLX's nn.gelu_approx; the oracle in main cites the lines (tools/zig/gemma4_e4b_layer_input_oracle.py: :479, :491–:503, :381–:389). So ple.metal follows that code op by op, though no line is copied:

  • gemma_ple_combine follows _project_per_layer_inputs: projection × hidden^-0.5, RMS norm, + table row × √256, × 2^-0.5;
  • gemma_ple_mid follows nn.gelu_approx's ops and their bf16 roundings, as main's gemma_geglu already does;
  • the rest of the layer (projection, norm, residual, scalar) follows lines :384–:389.

The host's layer_input.zig (in main) and these kernels were then checked bit for bit against MLX's outputs. The comments now say this: ple.metal's header reads "op order and bf16 roundings as mlx-lm 0.32.2's gemma4_text.py (lines in the oracle)", and the kernel comments describe the math (code × scale + bias, the tanh GELU) instead of saying "as mlx_lm computes them". If following the op order and rounding points is the part you're settling, tell me what to change.

2. M5. The E4B is now refused by name on a chip with tensor units: admitChip returns GemmaE4bNotQualifiedWithTensorUnits and serve says "Gemma 4 E4B is not qualified on chips with tensor units (M5); it runs on M1 to M4". A unit test covers the E4B with and without tensor units, and the 12B and 31B with both (admitted). The recipe and changelog say M5 is refused. I have no M5, so the refusal itself has not run on one.

3. Planted control and rotary. control: gemma4 E4B dense bf16 gemma_dense4 drops the last 256-deep step of K compiles dense.metal with its K loop one step short and goes red at the shapes gate (32.25 where float64 gives 40.37, at 1×256×2560). --only E4B: SUMMARY 5 kernels: 5 pass gates 1-4, 0 fail, 0 known findings; 1 controls: 1 red as planted, 0 missed; 0 limit problems.
tf-rotary-sweep wrote its receipt (302,008,320 cases). The unfiltered tf-kernel-contract --rotary-accuracy then stops on this M4 Max before any SUMMARY: "UNSUPPORTED gemma4 31B rounded dense: tensor units required; Gemma coverage unchecked". That is main's check in metal_main.zig for every Gemma entry on a chip without tensor units, so the unfiltered run needs an M5.

4. The 12B and 31B on M5. No M5 here either. What I changed and checked:

  • For models without per-layer inputs the loader is main's again: k_norm always loaded, the v_proj stand-in on cfg.global(i). The q/k/v member list now comes from the plan; for a model without shared caches it is main's list, since config refuses a checkpoint whose attention_k_eq_v differs from keys_are_values.
  • On a chip with tensor units the 12B and 31B keep the fused lane path (m.fuse unchanged for them). The row-path changes only reach weights from packRows, which only chips without tensor units load.
  • Prompt chunks before the last now skip the head, whose logits the next chunk overwrote; layers and cache are unchanged for these models.
  • On the M4 Max, tf-gemma4-run built on main 2467a6c1c and on this head gives byte-equal outputs for the 12B and the 31B at widths 512 and 1 (3 prompts × 64 tokens).

If someone with an M5 can run tf-gemma4-run on main and on this head for the 12B and 31B, that would settle it.

@ashhart

ashhart commented Nov 6, 2026

Copy link
Copy Markdown
Owner

Thanks @Mirrdhyn, for the clear account and for items 2 and 3. The M5 refusal is by name with a test, and the dense.metal control goes red at shapes.

On item 1: since ple.metal follows mlx-lm's gemma4_text.py op by op, it can't land as it is. Library code doesn't land here even with a notice, and this push changed only the comments. Please rewrite gemma_ple_combine, gemma_ple_mid and the layer tail (forward.zig:217) from Gemma 4's published model description, or from the publisher's own release code with a THIRD_PARTY_NOTICES entry. Then drop the mlx-lm citations (ple.metal:1, :32). Comparing against MLX's outputs, bit for bit if you like, is fine. Choosing the rounding points to match those outputs is fine too, as long as the code isn't read from mlx-lm.

@Mirrdhyn

Mirrdhyn commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Rewritten as you asked: head 194400c4, rebased on main c3f64ca8a.

  • Source. gemma_ple_combine, the gate's GELU epilogue in dense.metal (the same step as gemma_ple_mid) and the layer tail in forward.zig now follow DeepMind's release code, encode_per_layer_input and the Block's per-layer-input step in gemma/gm/nn/gemma4/_modules.py (google-deepmind/gemma 9e1f74131ba9, Apache-2.0), with an entry in THIRD_PARTY_NOTICES.md. The mlx-lm citations are gone.
  • How. A clean room: a fresh writer got only DeepMind's file and our three files with the old bodies and their descriptive comments already removed, no repository history, no mlx-lm or MLX, no host reference. It got numbers back, never code. It chose the rounding points from those numbers, as you allowed. One step differs from DeepMind's function: the projection is scaled by 1/√hidden before the RMSNorm. The norm cancels a constant factor, so it changes only eps and the bf16 rounding; it is kept to match the outputs. After eight attempts the E4B's logits are 16 of 16 byte-equal to the earlier run, and the per-layer tool sits at the old code's floor. The journal (files given with sha256, every attempt) is ready to attach.
  • gemma_ple_mid was dead: no path dispatched it, the gate's epilogue does that step. Its kernel, pipeline and contract entry are removed, so the filtered contract now reads 4 E4B kernels and 2 ple kernels, each with its planted control red. The contract's host references for these kernels were rewritten the same way.
  • History. No commit in the branch carries the earlier code: each commit holds the new text and builds. git log -p against main finds no oracle, gelu_approx or the old bodies. The five remaining "mlx-lm" mentions are about the checkpoint's tensor names, in the converter, its test and the recipe.

Checks on this code: lean 210 → 210, zig build test with only main's exl3_load failure, seams 15 of 15, concurrent equal to alone, 12B and 31B byte-equal to main at widths 512 and 1.

@ashhart

ashhart commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Thanks, @Mirrdhyn. The mlx-lm citations are gone, gemma_ple_mid is out, and THIRD_PARTY_NOTICES.md:312 and :316 name DeepMind's _modules.py, its revision and Apache-2.0. Following a model's release code with a notice is fine here.

What's left:

  1. The clean-room journal, which you said is ready to attach. Please include the files you were given, with their sha256, and every attempt. The new code keeps the earlier code's steps and rounding points, including the 1/√hidden scale before the norm (ple.metal:43, forward.zig:224) and the rounded 0.5·g (dense.metal:118). You've explained why, and the journal is what shows it.
  2. A comment that disagrees with the code: dense.metal:110 says bf16 rounding "after each op", but g * g * g is rounded once (:112). Please make the comment match the code.
  3. The CHANGELOG line should end "(gemma4 Metal: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B) on M1 to M4, per-layer inputs and shared KV #2273, part of Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B): per-layer inputs and shared KV, Intel Arc first #1222). Thanks to @Mirrdhyn." The conflict with main is ours to settle when it lands.

Mirrdhyn added a commit to hygurlabs/TensorFold-working-branches that referenced this pull request Nov 8, 2026
@Mirrdhyn

Mirrdhyn commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @ashhart. All three are done, in two new commits on top of 194400c4 (no force-push, head 17fe2da1).

  1. Journal: https://gist.github.com/Mirrdhyn/7041323c77aaa5b3907c77fcbd2abd1e. It holds the journal as written during the room, every attempt (8 in phase 1, 1 in phase 2), the 25 variants tried, DeepMind's _modules.py at 9e1f74131ba9, and every file the writer was given, with sha256 for all of them (0-README.md). The writer later wrote into four of the given files (ple.metal, dense.metal, forward.zig, the phase-2 harness), so these are rebuilt by replaying the preparation from 4fdbc2152. Each rebuilt file's sha256 equals the one the journal recorded before the writer started (given/HOW.md).

    One thing the journal doesn't say, and you should know. The 1/√hidden scale was there from attempt 1 because the combine's signature the writer was given kept the old interface's psc parameter (given/src/ple.metal:34). The writer read it as 1/√hidden. So that step came from the interface, not from the numbers or from DeepMind's code. The numbers then kept it: without it (attempt 4, variant B) the inputs differ in 15,138 values, against 11,208 with it, and rounding it to bf16 (attempt 5, G) brings them to 2. The rounded 0.5·g comes from attempt 5's g2, where every op of the tanh GELU is rounded, and v4 keeps it. The journal also records a possible leak after attempt 7, for you to weigh. If you'd rather have the combine rewritten without that hint, I can run a second room for it alone, with a neutral signature, and post its numbers whatever they are.

  2. Comment: dense.metal:110 now says each op rounds to bf16 and x³ rounds once, as the code does.

  3. CHANGELOG: the line ends "(gemma4 Metal: Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B) on M1 to M4, per-layer inputs and shared KV #2273, part of Gemma 4 E4B (NVIDIA Nemotron 3.5 Bolt E4B): per-layer inputs and shared KV, Intel Arc first #1222). Thanks to @Mirrdhyn."

@Mirrdhyn

Mirrdhyn commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

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 encode_per_layer_input itself (_modules.py:169-198, the only part we had looked at) but in the projection's definition, _modules.py:106-108: _layers.Einsum(..., w_scale=(float(self.embed_dim) ** -0.5)). At the same revision, gemma/gm/nn/gemma4/_layers.py multiplies the weights by w_scale before the einsum. Our kernel scales the product instead; the two are equal in exact arithmetic and round differently in bf16. So the psc parameter left in the given signature pointed to a step that DeepMind's release code has. I still wanted you to know where the writer took it from.

@ashhart

ashhart commented Nov 8, 2026

Copy link
Copy Markdown
Owner

Thanks, @Mirrdhyn, for the journal and for writing down where the psc hint came from and correcting it at 08:14. The comment at dense.metal:110 now matches the code, and the CHANGELOG line reads as asked.

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 _modules.py at 9e1f74131ba9. They had no mlx-lm, no layer-input oracle and no layer_input.zig. Every given file's sha256 is listed, and the supervisor's remark after attempt 7 is disclosed where it happened. That remark was generic, and the psc reading it may have touched is now explained.

A few small things:

  1. Please attach the journal's 0-README.md (the sha256 list) and given/HOW.md to this PR as well, so the record stays with the thread.
  2. Since the 1/√hidden scale is the projection's w_scale in DeepMind's code, please say so where it's applied (ple.metal:42, forward.zig:224) and add gemma/gm/nn/gemma4/_layers.py to the entry at THIRD_PARTY_NOTICES.md:312.
  3. GEMMA_E4B_WINDOWS is read with a direct getenv (families/gemma4/backend.zig:207) and changes the prompt path. Please register it in zig/src/core/profile.zig, as GEMMA_DRAFT_BF16 is (:135), or drop it.
  4. Two leftovers from removing gemma_ple_mid: docs/kernel-contract.md:185 still lists "combine and gelu kernels", and ple.metal:5 lists GELU_C0/C1.

We don't need a second room for the combine.

@Mirrdhyn

Mirrdhyn commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @ashhart. Done in three new commits on top of 17fe2da1 (no force-push, head 073f5afb):

  1. Record: 0-README.md and given/HOW.md are below, verbatim from the gist.
  2. The scale: ple.metal:42 and forward.zig:224 now say the 1/√hidden is DeepMind's projection w_scale, which _layers.py's Einsum applies, and the entry at THIRD_PARTY_NOTICES.md:312 names gemma/gm/nn/gemma4/_layers.py.
  3. GEMMA_E4B_WINDOWS is dropped, along with its sentence in the recipe: the E-series prompt always takes the tiles after its first window.
  4. Leftovers: docs/kernel-contract.md:185 now lists "per-layer table and combine kernels", and ple.metal:5 no longer lists GELU_C0/C1. I also removed the two GELU_C0/C1 defines that Ple.source in kernels.zig still put in front of ple.metal, which no longer reads them.

No arithmetic changed. Checked on the Mac: lean 210 → 210, zig build test with only main's exl3_load failure, --only "gemma4 E4B" and --only ple pass with their planted controls red, the E4B logits 16 of 16 byte-equal to the earlier run, seams 15 of 15, concurrent equal to alone.

0-README.md

Clean-room record for TensorFold PR #2273 (E4B on Metal, per-layer inputs)

Gist file names are the room's paths with / written as __ (given__src__ple.metal is given/src/ple.metal).

  • JOURNAL.md: the journal as written during the room, unedited: provenance, files given with sha256, every attempt
    and its numbers, supervisor notes and disclosures.
  • given/: the four given files the writer later wrote into, rebuilt by replaying the preparation from 4fdbc2152;
    each sha256 equals the journal's (given/HOW.md).
  • src/, phase2/: the room as the writer left it (final files, the interfaces and notices it was given).
  • src/variants-done/<attempt>/: every variant tried, by attempt.
  • source/_modules.py: google-deepmind/gemma 9e1f74131ba9, gemma/gm/nn/gemma4/_modules.py, Apache-2.0, unchanged.

Disclosure added after the room: the combine's signature in the given ple.metal (line 34) kept the old interface's
psc parameter, which the writer read as 1/sqrt(hidden) from attempt 1. See the PR comment.

sha256 of every file:

c761fc629560be65e5b8265432fa0aed73e35de436d71b42d4a5f08f980b8b44  given/HOW.md
8e7467f47a3bb1040f977692f76701dda76eec19e5292c8ce9cc6b2980055777  given/phase2/metal_gemma4_ple.zig
06eb30d3d8aa3c6c74509a954adfb6b9e87d20d209376bf8d3afc49749a985b7  given/src/dense.metal
5ef0c3f277d238d77da3214a2ed0d51c29dc0ce1dd66399255385fb82f182bc5  given/src/forward.zig
1e9d0f19ceddd415aebad83aa216a057a58d3081d0ba20f927eaf7ff8687a27b  given/src/ple.metal
017525a76b4cfa56ca62ae1daed3875fef255b0bef1e59ab09008ea97f696130  JOURNAL.md
2663c6af63f8ac1a16e7499d45a3a9e39110a103c63b197e32dbe852b6d04ab1  phase2/API.md
bddfe1f24b3e594dc09c91d7074459e8566a3619412b7acbc6b28c54c43e7bcd  phase2/metal_gemma4_ple.zig
55dee2ef3397b3e12631bd000d34d62ac1cdcf1b511c5fb945a73e8975f0bda1  source/_modules.py
d89486c2df8defc55121b055fb13c3c7c252e25f5202c7c269be92cbf62a27e6  src/dense.metal
225ac158fcaaa54e1fdd04fd569bfc62f0e7520e77b76e89b4f8bbef3e3eba06  src/forward.zig
566ede21b94ed77badfe415dcff3f7589d1630de12e4c79fa7ce20beeb47e60b  src/INTERFACES.md
9dfca76c087be626b67c875bd5bf1852f4317bebfd30eaf80ca38281030bd22d  src/NOTICE_ENTRY.md
24d8e163d4aefaf999f9fe44cc9dce20ee50c4699b82e50fb6fc1e49c469f39d  src/NOTICES_EXAMPLE.md
c7d90fa587b74203185d67b757a4f75486c1b652eb67a26966aa7bef651ea978  src/ple.metal
3a6f062dadc5ab468edc6c305229458028b06187dd0fbfbb3dfa5303ed8fdf2c  src/variants-done/4/A.ple.metal
adebbabdfb2a7b59ac121ca0d1600fe4ac8b60da4614b096e7861f653af19d9b  src/variants-done/4/B.ple.metal
05c7ad77a02e4ec5ef2bcfd9b2477f8727203be518e319f52ee675c3b19d9ced  src/variants-done/4/C.ple.metal
5beac2175e8fd0bcbc8f4918759aede2fbad202529596451be065e76c5b617b3  src/variants-done/4/D.ple.metal
463425ac38896bcb191c3d80e567aa4ea1ee9a46dc8648c99d34cebfa005616b  src/variants-done/4/E.ple.metal
c0c3b697bf4b8087a7208d4cad37ab2fc01a8abd9c9a77723f98292a7a75ca52  src/variants-done/4/F.ple.metal
6838c907c2d6a187d00065200debd33d97dbfeaebe9efd6f79674a573c59537f  src/variants-done/5/g1.dense.metal
8b032c35be0ef39ebade74691fbf3ddf1702b37231153885f7fb272c26ce5537  src/variants-done/5/g2.dense.metal
3fe6669343aa852045c9509bba9006b12aeb126e74ea392368726eec27d96b73  src/variants-done/5/g3.dense.metal
0287b9149f17d45e60337113296861a0a7c3158c1e1126553d93829002d4a594  src/variants-done/5/G.ple.metal
ad694f12fec448178c5c67737a13aea7852360604aae57924fd7268b2f5936ee  src/variants-done/5/H.ple.metal
4c7b468cd0ab9fed8e63c8703edbeb482338066a556b702aa94efed617aeefba  src/variants-done/5/K.ple.metal
debb2f29d2427c21dedd2437f5fb95f4f2a9e8d1f28c4ed0c02100a5a348b64c  src/variants-done/6b/v4.dense.metal
b2e96babd88c00a72707cdc9566a48d0e25e6edb9128d033c44aef761f3d6af4  src/variants-done/6/v1.dense.metal
c428dda7fe93e4c34776d3db3377ea4ea7ba00d5ebc65be805e94f91110a8203  src/variants-done/6/v2.dense.metal
8ee5e6b6a299a13aa95e466735757d78923a796b4364cdf3bb68d46a9795cd1e  src/variants-done/6/v3.dense.metal
debb2f29d2427c21dedd2437f5fb95f4f2a9e8d1f28c4ed0c02100a5a348b64c  src/variants-done/6/v4.dense.metal
a7cfbbff9d3939e6ddfdef86a3659fbd1e89f51fb2156327ffc80cb77baebd7c  src/variants-done/6/v5.dense.metal
fabc74bb08fa3cc6d184fd4258d267f343db48a68dafe0f3c6bb7072376bb56b  src/variants-done/6/v6.dense.metal
caee2005ff1b65b384da13c072c5414c8376ff8af36942345237e0f0b78b9f08  src/variants-done/7/swap.forward.zig
d244622e3b4c8bb4a368dcf4d629c29f732a8a950614f8aff904c105b4a5f407  src/variants-done/7/swap.ple.metal
7d6ebfe4158c58cd1fcf551e4f004ba057a2aa1d3daf72ff01554ef9e2ce5648  src/variants-done/8/r1.ple.metal
588388f2e89e84f91d1feb3639d3cd8a2e75c395855e22e6f4ae78f8729f938c  src/variants-done/8/r2.ple.metal
b11f1f5065c51f342d491bc46a469951b886bcbd30841a892bf8a704c0ca0084  src/variants-done/8/t1.dense.metal
36f65c40f95bec591e0bbf94514c70c20ba8e00f30e79b9748efccfb8ded78d9  src/variants-done/8/t2.dense.metal
given/HOW.md

Files given to the writer, rebuilt by replay

These four files are the ones handed to the writer before it wrote in them. The originals were overwritten in the room;
these are rebuilt by replaying the supervisor's preparation, in order, from the supervisor session's transcript.

  • src/ple.metal, src/dense.metal, src/forward.zig: git archive 4fdbc2152 of
    zig/kernels/metal/gemma4/ple.metal, zig/kernels/metal/gemma4/dense.metal and zig/src/families/gemma4/forward.zig, then the supervisor's one Python
    script that cut the holes and replaced the comments (2026-11-06 17:02 UTC), run verbatim.
  • phase2/metal_gemma4_ple.zig: zig/tests/contract/metal_gemma4_ple.zig at 4fdbc21, then the supervisor's Mid
    deletion on branch e4b-metal-pr8 (17:05 UTC, the harness part of that script, the only edit to the file before
    phase 2), then the phase-2 script that cut its holes (18:07 UTC), both run verbatim.

The sha256 of each file equals the one recorded in JOURNAL.md under "Files provided":

06eb30d3d8aa3c6c74509a954adfb6b9e87d20d209376bf8d3afc49749a985b7  src/dense.metal
5ef0c3f277d238d77da3214a2ed0d51c29dc0ce1dd66399255385fb82f182bc5  src/forward.zig
1e9d0f19ceddd415aebad83aa216a057a58d3081d0ba20f927eaf7ff8687a27b  src/ple.metal
8e7467f47a3bb1040f977692f76701dda76eec19e5292c8ce9cc6b2980055777  phase2/metal_gemma4_ple.zig

@ashhart

ashhart commented Nov 9, 2026

Copy link
Copy Markdown
Owner

Thanks @Mirrdhyn. All of the 8 Nov asks are met:

  • the record is on the thread;
  • ple.metal:42 and forward.zig:224 name the w_scale, and THIRD_PARTY_NOTICES.md:312 names _layers.py;
  • GEMMA_E4B_WINDOWS is gone;
  • the two leftovers are fixed.

A few things before we run anything:

  1. The row twin. weights.zig:448 sends every one- and two-row window to the scalar twin. On M1 to M4, that reaches the 12B's and 31B's decode too. qwen27 takes the same twin only after simd_bits.twinExact passes for that shape on the running chip (families/qwen27/quant_gpu.zig:327), because the twin's bits can differ from the tiles on some chips. Could gemma4 check it the same way, once per shape, and keep the tiles where it fails? Your M4 Max byte-equality proves it for that chip only.

  2. A rebase. Three code files conflict with main:

    • kernels.zig: main moved the prompt attention source into promptSource (:142-149), which still uses cfg.window and state.ring. The E4B needs geo.sliding_window and state.ringOf(geo) there, or its sliding layers get a 1024 window.
    • model.zig: keep admitChip and main's fused_lane.available(m.device), with your layer_input == 0.
    • metal_main.zig: limits now live in metal_limits_all.zig, so the per-layer set's limits go there.

    Please also add the E4B and the Ple sources to zig/runtime_sources/models.zig:11, which compiles only the 31B and 12B.

  3. The converter. quantize in tools/zig/gemma4_e4b_convert.py:37-53 follows MLX's affine quantize step by step (the comments at :46 and :50). How was it written: from the format, or from MLX's source? Matching mx.quantize byte for byte is fine. What we can't take is code worked from another project's source.

The CHANGELOG conflict is ours. A clause on the 12B's faster one-stream decode would help readers.

@ashhart

ashhart commented Nov 12, 2026

Copy link
Copy Markdown
Owner

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 quantize comes from. tools/zig/gemma4_e4b_convert.py:37-54 works out each group's scale and bias step by step: the edge with the larger magnitude, q0 from it, the scale rebuilt from q0, the codes from the unrounded scale and bias. The comments name MLX as the model for those steps (:46 "as MLX's rint", :50 "as MLX does"), and :161 notes how MLX's Metal and CPU quantize differ. Matching mx.quantize byte for byte is fine. Code worked from MLX's source is not, so we can't land this or finish it for you until we know which it is. Either of these settles it:

  1. Tell us it was written from the format and only checked against mx.quantize's outputs, and say so in the function's comment in place of the MLX references.
  2. Or replace it with a quantizer written from the format without reading MLX's code. The checkpoint's bytes may change, so the logits, seams and speed receipts would need a rerun on the new checkpoint.

Still open from our last note, which we're glad to do on your branch once the converter is settled:

  • The row twin: zig/src/families/gemma4/weights.zig:448 sends every one- and two-row window to the scalar twin. It should check simd_bits.twinExact once per shape on the running chip, as families/qwen27/quant_gpu.zig:327 does, and keep the tiles where the check fails.
  • A rebase: kernels.zig (promptSource needs geo.sliding_window and state.ringOf(geo)), model.zig (admitChip beside main's fused_lane.available(m.device)) and metal_main.zig (the per-layer limits move to metal_limits_all.zig). Plus the E4B and Ple sources in zig/runtime_sources/models.zig:11.

After that, we'll check the 12B and 31B against main on an M5, and the E4B on an M1 to M4 chip.

  • Synthena (Ash's Agent)

@Mirrdhyn

Copy link
Copy Markdown
Contributor Author

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

  • Item 4: resolve the integration with xpu: serve logprobs and top_logprobs on Qwen3.8-27B #3051 in draft_sources_xpu_test.zig, carry its Note hook into walk, and keep the affected modules within 600 lines. In the rebase, the verifyPrice path stays for the shared case, and both xpu_dflash2_depth_test.zig and the lone test are kept.
  • Item 6: rerun the slower engine-only cells from 13 Nov (tool call, thinking budget, JSON schema sampled at about 8K tokens), main and head alternating, at least 3 runs a side.
  • Item 8: end the CHANGELOG line with (#3052, refs #2897); the short-prompt figure follows item 1.
  • Item 1: the 34-token and 7,588-token cells at or above the best fixed tree, timed and on the first request of a fresh server, with equal hashes. The 7,588-token cell is still under, so this is open work on our side, to be measured on top of XPU 27B decode attention: tree rows of a key slice run back to back (bit-identical, +23 % at 32K, +33 % at 131K) #2595.

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 quantize comes from

It was not worked from MLX's source. It is a numpy port of TensorFold's own quantizeGroup (zig/src/families/gemma4/dflash_weights.zig, on main since mid-October). The two places where it differs from that function were found by comparing variants against mx.quantize's outputs: rint in place of round-half-away (0 scale and bias mismatches against 2 in 10,240), and codes taken from the unrounded scale and bias. So this is your option 1.

The note at :161 is an observation too, not something read in MLX's code: on a Mac, mx.quantize gives different scales on Metal and on CPU for a few groups (7 of 10,240 in a quick run, with 1,077 code words differing as a result), so --check-mlx pins the CPU device.

I will replace the MLX references in the comments at :46, :50 and :161 with that provenance. The work log of 23 Oct has the probe script and its figures if you want them.

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.

Mirrdhyn and others added 20 commits November 21, 2026 14:23
…ion w_scale, in the kernel, the dispatch and the notices (ashhart#1222)
…of quantizeGroup checked against mx.quantize's outputs (ashhart#2273)
@AIFlowML

Copy link
Copy Markdown
Contributor

The current 9d1fa0a68 head trial-merges cleanly into 3a02038db, but the Gemma prompt-head host target fails to compile. The candidate adds a call that reaches Buffer.slice in the recording Metal fixture, which has no such method. The other two diagnostics in row_projection.zig also occur on main and come from the test helper treating the fixture's integer pipeline ID as a pointer.

zig build test-gemma4-prompt-head-host -Dcpu=apple_m1 \
  -Doptimize=ReleaseSafe -j2 --summary all

I 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
@Mirrdhyn

Copy link
Copy Markdown
Contributor Author

@AIFlowML thanks for the exact command. da943a3a7 is the fix, confined to the host fixture: the recording Metal stub gains a Device.queue that refuses and a Buffer.slice that panics, so twinExact, which the prompt head now reaches through bitTwin, type-checks. Since Device.buffer already refuses every allocation, neither is reached at run time. zig build test-gemma4-prompt-head-host -Doptimize=ReleaseSafe passes 185 of 191 (6 skipped) on aarch64 Linux, with and without -Dcpu=apple_m1. No device code changes. The two row_projection.zig diagnostics you saw also happen on main and are left alone here.

@ashhart

ashhart commented Nov 23, 2026

Copy link
Copy Markdown
Owner

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.

  • Synthena

@Mirrdhyn

Copy link
Copy Markdown
Contributor Author

Fixed in c8cedf336. gemma4_e4b_fp64.py now builds gate|up as the row path packs it, all gate rows followed by all up rows, for both the FP64 reference and the FP32 emulation. interleaves() is true only with tensor units, and the machine below has none.

Rerun on an M4 Max (no tensor units), on the checkpoint and ids of the earlier receipt:

  • Projections against FP64 (9 layers: 0, 3, 5, 11, 17, 23, 24, 35, 41; the PR text said 7, which was wrong), error over Σ|x||w| in units of 2^-8, rms and worst:

    • gate_up: decode 0.021 / 0.60, tiles 0.024 / 0.60, now in the range of the other classes;
    • qkv: 0.027 / 0.49 and 0.030 / 0.49;
    • o: 0.021 / 0.56 and 0.024 / 0.62;
    • down: 0.039 / 0.72 and 0.047 / 1.09.

    With EMULATE=1, bf16 weights with fp32 chunks match the native gate_up tiles bit for bit on 99.98 % of outputs.

  • Window widths 1, 3 and 128 against 16 (tf-gemma4-e4b-logits): 16 of 16 files byte-equal at each width.

A correction to the earlier receipt, found on the way: duck_free_ids.json holds 607 ids, and tf-gemma4-e4b-seams slices 1,300 from it in a build without bounds checks. So 12 of the 15 seams cases, the 1,300-token prompt at all 12 resume points, read memory past the file. Their saved outputs show NaN logits, and only the 3 short cases were valid. d1199267c makes seams and projections refuse an ids file shorter than what they slice. With a 6,422-token ids file, seams gives 15 cases and 0 unequal, before and after the merge.

Merged main (8ace0d121): main's chunk-a-call prompt pass (47edbd9) now carries the E-series path too. That is windows of up to 128 rows, then tiles, with the last row alone, one window or chunk per step call. The cut points are unchanged, and a host test checks the cuts against the previous loop. Windows run on the decode scratch, so each one also advances the scratch generation, and another stream's taps read after it show as stale.

On the merged head:

  • Host, on Linux and on the Mac: test-gemma4-prompt-head-host 198/200 (2 skipped) on the Mac; zig build test on Linux 12,925 pass, 95 skipped.
  • Unchanged bits: width-16 logits byte-equal to the pre-merge, and the FP64 output identical to the pre-merge.
  • Served (bench_concurrent.py --alone --serial, T=0 and T=1, two passes): concurrent equals alone and serial, 0 unequal.
    • That includes a 4,585-token prompt whose windows run while another stream decodes.
    • A request cancelled mid-prompt and then rerun equals a fresh one, with the cache on (4,582 tokens read) and off.
  • Prompt cache on against off: equal tokens.

One note: /v1/completions requests get no prompt-cache reuse on Gemma 4 on Metal, on main d9e81bda1 with the 12B as on this branch. Chat requests do reuse.

The Metal checks ran on a Mac shared with desktop apps, at 23 % to 99 % GPU utilization. All of them are equality checks.

@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

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.

  • Synthena

This branch has not been deployed

No deployments
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.

3 participants