Skip to content

Nemotron 3.5 Bolt (nemotron_h_puzzle) on Metal: serves end to end (lands #1038) - #4162

Merged
ashhart merged 23 commits into
mainfrom
lead/pr1038
Nov 20, 2026
Merged

ashhart merged 23 commits into
mainfrom
lead/pr1038

Conversation

@ashhart

@ashhart ashhart commented Nov 20, 2026

Copy link
Copy Markdown
Owner

Lands #1038 by @trickyfalcon (Nemotron 3.5 Bolt, nemotron_h_puzzle, on Metal, serving end to end): thank you. Their fork does not accept our pushes, so this branch carries their 19 commits rebased onto current main, each with its author and message as written. The rebase kept both sides at every conflict (main moved the Metal registration and test tables), and two nemotron files took the usual line room; no behaviour changes.

The design, receipts and review are on #1038. Our 50-load retention cell runs on this head before it lands.

  • Synthena

@ashhart
ashhart force-pushed the lead/pr1038 branch 2 times, most recently from 3f31598 to 60eadd2 Compare November 20, 2026 16:06
trickyfalcon and others added 23 commits November 20, 2026 16:54
Part 1 of the native Metal backend for nemotron_h_puzzle (Nemotron 3.5
Bolt 74B-A9B), opened early per #962 so the loader can
be reviewed before the latent kernels harden. v1.1.0 already parses the
Puzzle config (bolt, per-layer moe[]) and serves it on CUDA; this is the
Metal weight loader for it.

weights.zig: the Metal MoE loader now reads each layer's own expert count
and width (per-layer in nemotron_h_puzzle, uniform otherwise), runs the
routed experts in the moe_latent_size latent rather than hidden, and
carries the two bf16 latent projections fc1/fc2_latent_proj (new Moe.into
and .out, a plain-bf16 Dense referenced in place; the Lightning path keeps
them null and is unchanged). moe() takes the layer's experts, width and
latent; its two callers pass the per-layer values for bolt, the globals
otherwise.

config.zig: checkShapes gains a bolt branch (checkBoltShapes) for Bolt's
dimensions (hidden 4096, 1024 latent, 5376 shared expert, top-k 9, per-
layer expert counts 240-496 and widths 1536-2560).

weights_test.zig: a two-layer puzzle block loads per layer - each keeps
its own expert count and width, the experts read the latent, and both
latent projections are present.

No forward or kernels yet; those follow as commits on this branch. The
Lightning path is byte-for-byte unchanged (zig build test test-golden: 0
unexpected golden differences).
The latent path for Nemotron 3.5 Bolt, mirroring cuda_latent.zig run(): the
normed input projects into the moe_latent_size latent, the routed experts
run up/down in the latent, each pick projects back to hidden, then add_norm
combines the picks by weight with the shared expert (kept in hidden) and the
residual. Per-pick out-projection is valid because the projection is linear.
Hand-authored (the nemotron kernel generator is not in the public repo).

state.zig: two latent-width scratch buffers (x_lat, ey_lat).

weights.zig: the routed experts load through the runtime-dim row kernels for
the Puzzle (latent > 0), which read each layer's own expert count and width
at K = latent; the baked 4/64 lane kernels serve only the Lightning inner
width.

New Metal kernels (zig/kernels/metal/nemotron):
- route_bolt: the router top-k at runtime NE and K, so one kernel serves
  every Puzzle layer's own expert count. Same scoring as route.metal (sigmoid
  of the gate logit plus the correction bias, normalised and scaled) but the
  per-lane slices are ceil(NE / 32) with an e < NE guard, so the last partial
  slice is kept (every Bolt expert count is NE % 32 == 16, which the baked
  route.metal would drop).
- dense_bf16: a bf16 write-matmul (y = x R^T, no accumulate) for the gate and
  the two full-precision latent projections fc1/fc2_latent_proj.
- add_norm_moe_xs_bolt: the combine + shared + residual + next-norm kernel at
  <4096, 512, 9> (896 does not divide 4096; 512 does).

layers.bolt_moe + forward dispatch (c.bolt): gate (dense_bf16) -> route_bolt
-> shared up/down (hidden, the Lightning path) -> into (dense_bf16) -> routed
experts up/down in the latent (indexed row kernels) -> out per pick
(dense_bf16) -> add_norm_moe_xs_bolt.

Lightning is unchanged: the dispatch takes bolt_moe only when c.bolt, and
zig build test test-golden holds 0 unexpected golden differences. Remaining
to RUN end to end: Bolt-dim variants of the shared up_relu2 and the mamba
kernels, and the GPU kernel-contract tests (route_bolt first).
…t slice

tf-metal-tests now dispatches route_bolt at a real Bolt expert count
(NE=240, NE % 32 == 16) and checks its picks and weights against a CPU
reference. Row 0 plants its top nine logits on experts 224..232 - in the
last partial slice [224,240) that the baked NE/32 striping dropped - and the
kernel returns exactly those, so the pad-to-32 fix is proven on device.
Weights match the reference (sigmoid + bias, normalised, scaled) within 1e-3.

route_bolt.metal and dense_bf16.metal join the metallib source list, which
compiles and validates their MSL at build time (the engine still loads them
from the runtime kernel registry).
dense_bf16: the bf16 write-matmul (gate and latent projections) checked
against an fp32 CPU reference over the same bf16 inputs, to a bf16 output
tolerance.

add_norm_moe_xs_bolt: the <4096, 512, 9> instantiation, checked on the case
with no routed picks (WE = 0) and no shared expert (SH = 0), where the block
reduces to OUT = rmsnorm(H) * W with W = 1; HN is unchanged and XS is the
per-group sum of OUT.

add_norm_moe_xs.metal joins the metallib source list so the instantiation
compiles at build time and tf-metal-tests can load it. tf-metal-tests: 9 of
9 pass on an M-series Mac.
The Metal engine now opens, loads and serves the published Bolt checkpoint
(bytebunker/NVIDIA-Nemotron-3.5-Bolt-74B-A9B-MLX-4bit, 40.3 GiB) on an
M-series Mac without tensor units, where every projection runs on the
runtime-dim row kernels. On an M3 Max (128 GB) it loads in 6.3 s and decodes
at ~41 tok/s.

Checked on that build:
- greedy tokens are identical to mlx_lm 0.32.3 (token_sha256 equal) on the
  prompts tried;
- concurrent == solo at two and four streams;
- resumed == fresh: a chat turn resumed from the prompt cache (at 915 of 959
  tokens) equals the same turn prefilled on a fresh server.

What Bolt needed beyond the latent MoE:
- metal.zig: register the nemotron_h_puzzle family and open it.
- weights.zig / forward.zig: a full-precision bf16 lm_head (MLX quantizes a
  module only where {path}.scales exists, and Bolt's lm_head has none) is
  read in place and projected by dense_bf16.
- Mamba at Bolt's widths (inner 128 x 64 = 8192, in_proj 18560): the tree
  conv and scan instantiated at <8192, 8, 128, 4, 18560, 8192> and
  <128, 64, 8, 128, 8192, 18560, 18432, 1048576>, and the gated group norm
  at XD 8192 / GS 1024 (group_norm_xs_bolt.metal, one per padded row count).
- add_norm_xs at <4096, 512>, and the hidden row sums at the model's width.
- backend.zig: prompts run through the decode kernels in fused_rows chunks;
  the fused prefill kernels are not yet built for the latent MoE.

All Bolt kernels are hand-authored instantiations of the generated ones (the
generator is not in the public repo). Lightning is unchanged: zig build test
test-golden holds 0 unexpected golden differences; tf-metal-tests 9 of 9.
…does

bolt_moe now follows mlx_lm's NemotronHMoE order and roundings: the picks
are summed by weight in the latent ((y * scores).sum(-2) in fp32, one bf16
rounding), the sum is projected back to hidden once by fc2_latent_proj,
then the shared expert and the residual are added (bf16(y + shared), then
bf16(h + y)). It replaces the per-pick out-projection, which was equal in
exact arithmetic but rounded differently, and costs nine times the
fc2_latent_proj work.

- combine_latent.metal: the latent combine, with add_norm_moe_xs's
  routed-sum order (a sequential fma over the picks).
- add_norm_moe_xs_bolt is now <4096, 512, 1>: one pick of weight 1 (exact
  under the fma) carries the projected MoE output into add_norm; Scratch
  gains a ones buffer for it.
- tf-metal-tests: combine_latent bit-exact against a host fma reference;
  10 of 10 pass.

On the published Bolt checkpoint (M3 Max), greedy output is token-exact
with mlx_lm 0.32.3 on 7 of 8 comparison prompts (was 5 of 8); the eighth
diverges at an exact tie in mlx_lm's own logits. concurrent == solo (x2,
x4) and resumed == fresh still hold; decode ~42-43 tok/s. Lightning
unchanged (test-golden 0 unexpected).
…orward)

Nemotron had no fidelity tool; this adds one on the qwen35/lfm2 pattern.

- tf-nemotron-forward MODEL TOKENS.npy OUT.bin: native teacher-forced bf16
  logits for every position, the ids run through the decode kernels
  fused_rows rows a forward (Lightning or Bolt).
- tools/zig/nemotron_fidelity.py: teacher-forced NLL, top-1 agreement and
  logit RMS of the native logits against mlx-lm run one row at a time, in
  32-row chunks and whole, with mlx-lm's own chunked-vs-serial variation as
  the floor. Every native pass runs before mlx-lm loads, so a 74B
  checkpoint is never held twice. The long fixture is the running Python's
  json.decoder and argparse sources (public, deterministic).

Bolt on an M3 Max (mlx 0.32.3, mlx-lm 0.32.0), native vs mlx-lm serial,
with mlx-lm's own chunk32-vs-serial floor in brackets:

  fixture                tokens  top-1            logit RMS       NLL native / mlx
  fibonacci-raw              15  0.933 (1.000)    0.181 (0.444)   2.890 / 2.841
  gpu-chat-no-think          35  0.971 (0.971)    0.179 (0.191)   5.715 / 5.724
  contribution-guide-512    512  0.922 (0.947)    0.322 (0.262)   3.293 / 3.306
  python-stdlib-2048       2048  0.988 (0.987)    0.494 (0.484)   0.362 / 0.364
… 600 lines)

The branch added 39 lean findings: multi-line comments and docstrings in the
new kernels, tests and tools, and layers.zig past 600 lines. Each comment is
now one line of at most 120 columns; bolt_moe moves to its own bolt.zig (with
upRelu2 made pub for it) and the group-norm pick becomes an inline loop, so
layers.zig is 580 lines. No behavior change: the served Bolt output is the
same token for token (7 of 8 prompts token-exact with mlx_lm, as before).

lean_new: 0 new (503 on the base and on this head); zig fmt --check clean;
test-kernel-contract, test, test-golden (0 unexpected) and tf-metal-tests
(10 of 10) pass.
…ding

- config: a puzzle layer whose top-k exceeds its own expert count is refused (the
  global check compared against the largest layer only)
- weights: a latent projection that is missing, quantized, transposed or not bf16
  is refused with its name; tests cover each, and experts stored over hidden
- model: Bolt is refused on tensor-unit chips (M5) before any weight is read, since
  the Builder would tile its projections for Lightning-sized lane kernels
- the Bolt checks move to config_bolt.zig (config.zig stays under 600 lines)
The hand-written route_bolt, dense_bf16 and combine_latent kernels are gone; Bolt
now runs the ops/ kernels the prefill set already compiles with MLX's options:

- gemv: ops/gemv.metal gains MLX's bm4/bm8 bn1 gemv beside its bn8 one; Bolt's gate,
  latent projections and bf16 lm_head take MLX's own tiles for each (K, N), a row a z
- route: tf_route_topk (mlx_lm group_expert_select) at every Bolt expert count
- combine: tf_moe_combine_rows follows col_reduce_small's lane order past 8 picks
  (8 lanes, pick 8 onto pick 0); at 8 or fewer picks its sums are unchanged

tools/zig/bolt_op_cases.py checks each against MLX 0.32.3 on the Bolt checkpoint,
every row of a 1-16 row pass equal to its own one-row op and MLX's metallib replay
equal too (check_mlx_ops.py --ops bolt_gemv,bolt_route,bolt_combine). The fidelity
tool now reports KL(mlx || native) a position and pins the checkpoint and commit.
A config refused after the device opens (Bolt on a tensor-unit chip, a bad
shape, a time-step clamp) returned without releasing either. A test counts
the device's references across a refused load.
The flag was silently ignored on this path; Bolt is now refused like Nemotron, before any load, with the refusal test extended.
…load

At E = 241 the gemv's last tile (237) clamps back over 236..239, so those rows would be written twice. Counts not a multiple of 4 are refused before the device opens; Bolt's own counts (240-496, all multiples of 16) pass.
…combine are Bolt's own

- x_lat, ey_lat and ones are allocated for nemotron_h_puzzle only (null otherwise).
- A bf16 lm_head without scales is read as a dense head for Bolt only; every other family keeps the quantized head it always loaded and is refused without one, as before (weights.denseHead, tested both ways).
- tf_moe_combine_at is back to upstream's order for every caller. Bolt's col_reduce_small order past 8 picks is a new tf_moe_combine_rows_lanes8 (bit-equal to the shared one at k <= 8); bolt_combine still 236/236 bit-identical with the gemv and route cases.
…rols and M1/M2 records

tests/contract/metal_bolt.zig registers Bolt's Metal kernels with the canonical runner, at the shapes nemotron/bolt.zig serves them:
- tf_gemv_bf16_bm4_tm4 and _bm8_tm4 (the router gate at 304-496 experts, into, out, the bf16 lm_head at 131072 x 4096), dense input family, float64 bound;
- tf_route_topk at every Bolt expert count, top-k 9: picks exact against float64 (planted exact ties, the last partial 32-expert slice winning row 0), weights within the bound, a stated NaN rule (MLX's sort);
- tf_moe_combine_rows_lanes8 at k 9 over the 1,024 latent;
- tf_nemotron_group_norm_xs_bolt (MP 16 and 128), tf_nemotron_add_norm_xs_bolt and _moe_xs_bolt: OUT as float64 ranges through its bf16 points, HN bit for bit, XS bit for bit as the f32 sum of the kernel's own outputs, padded rows zero.
Gate 4 stresses each with integer inputs exact in fp32 in any order (fp16 overflows, bf16 misses).

Eight planted controls, each a one-line mutation of the kernel's own source, red at the gate named: gemv summed in half (sums), gemv losing its K tail (shapes), route dropping the last partial 32-expert slice (shapes), route comparing NaN as a number (nonfinite), combine dropping pick 8 (shapes), add norm writing HN without its delta, group norm summing 63 of 64, group norm over half its group (shapes).

Gate 5: core/contract/bolt_records.zig, threads and threadgroup bytes as bolt.zig launches them, M1/M2 limits from --offline (all 1024).

tf-kernel-contract --only bolt --offline DIR on an M3 Max: 8 kernels pass gates 1-4, 8 controls red as planted, 28 launch checks pass.
…, prompt and decode rows apart

forward.Tap: an optional look at a forward's stages (h and x in and out of each layer, Mamba's in_proj, conv, gated
scan, group norm, attention's qkv and output, the MoE's gate, picks, weights, shared expert, into, routed experts,
combine and out). Null in the engine, which then encodes nothing more: logits with and without it are byte-identical,
and Lightning's replies on main and this head match 16/16 (greedy and seeded).

tf-nemotron-forward --decode-from N runs rows from N one a forward (decode) after fused_rows chunks (prompt);
--stages DIR copies every stage of every layer of every forward out (stages.bin, stages.jsonl).

tools/zig/nemotron_stages.py recomputes each stage in float64 from the dequantized checkpoint and the native's own
input to that stage, so each stage's error is its own, and reports it in bf16 ulps of the row's RMS, prompt and decode
rows apart; every projection also gets MLX's own bf16 result on the same input (quantized_matmul) as the floor. Route
picks are compared exactly; each differing pick is listed with float64's gap and whether its fp32 keys tie.

tools/zig/nemotron_fidelity.py runs the native twice a fixture (prompt rows, then decode rows), lists every
teacher-forced token whose top-1 differs from mlx-lm serial with mlx-lm's margin, and fails: on a non-finite logit, on a
differing token whose margin is above the largest at which mlx-lm's own chunk32 or full run flips on that fixture (or
--tie-ulps), on more differing tokens than twice mlx-lm's own count plus 2, or on an NLL further from mlx-lm serial than
twice mlx-lm's own spread.
…ns, with planted controls and M1/M2 records

tf_tree_conv_bolt and tf_tree_scan_bolt run gates 1-4 as Bolt serves them: one stream's chain of 1 to 16 rows (a
decode step or a prompt chunk; no replayed rows or trees, since the checkpoint has no draft head), its tables from
layers.Tables.of over the segment backend.zig builds, the state read from the stream's slot and stored to a fresh one.
init checks the two instantiations' template arguments against nemotron_tree.metal.

XBC and Y are checked against float64 as intervals through their bf16 points: the conv's fma chain within gamma(4),
the scan's recurrence op by op with the dot within gamma(35) (a lane's 4 states, then simd_sum in an unstated order),
fast math's exp, log and divide within 2^-16. check() also requires RAW, DTRAW and the stored conv taps bit for bit,
the stored scan state within its interval, the other slots and the tree states untouched. Gate 4's integers are exact
in fp32 in any order (conv: w0 = big + r against w1 = -big; scan: A 0, B 0, each state's term cancelled by a rotated
partner's), and bf16 and fp16 sums of them leave the bound.

Six controls, each red at its gate: the conv dropping its oldest tap, storing the wrong taps, summing in half; the
scan without its D skip, not decaying its state, summing its dot in half. Gate 5 records both launches (256 threads,
no threadgroup memory) with the M1/M2 limits from --offline.
…st launch map, a clean refusal

The contract's Bolt files are split along their kernels: metal_bolt.zig keeps gemv, route and combine, its norms
move to metal_bolt_norm.zig, the Mamba scan to metal_bolt_scan.zig. Bolt registers through one hook,
metal_bolt_main.zig, so metal_main.zig is back to main's size plus two lines.

Every comment is one line within 120 columns; the two fidelity tools' long docstrings are their --help text.

metal_limits.zig returns before it touches a source on the host walk, as its neighbours do, so
test-metal-launch-map-host builds again.

Model.load makes its queue and reads the device's generation inside an autorelease pool: a refused load leaves
nothing for the caller's pool to hold. The refused-config test takes its count after a first load, since the first
queue on a device raises the device's retain count once on every chip.
…gs, keeping config and weights within 600 lines
…l_metal, one tinyBolt doc line

The rebase left weights_bolt.zig without its std import, put Bolt's Metal
launch records in a second landed_cuda (zig ast-check failed on both), and
kept both versions of tinyBolt's doc comment.
@ashhart
ashhart merged commit f9f070a into main Nov 20, 2026
1 check failed
@ashhart
ashhart deleted the lead/pr1038 branch November 20, 2026 16:55
@ashhart

ashhart commented Nov 20, 2026

Copy link
Copy Markdown
Owner Author

Thank you @trickyfalcon. This is merged into main with your commits under your own name, so you're credited as a TensorFold contributor.

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