Skip to content

cuda norms: bf16 residual tails with a branch norm, a layer scalar and MLX's rounded rows - #1056

Closed
jschmied wants to merge 3 commits into
ashhart:mainfrom
jschmied:cuda-norms-gemma
Closed

jschmied wants to merge 3 commits into
ashhart:mainfrom
jschmied:cuda-norms-gemma

Conversation

@jschmied

@jschmied jschmied commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Step 1 of #1048 (agreed there: the rounding points are options on the shared operator, off by default): norms gets what Gemma 4's layer tails need, as shared options of the bf16-residual norm
(addRmsH). Nothing calls them yet.

  • Norms.addRmsTail(x, r, w, h, y, xs, rows, width, eps, .{ .round, .branch, .scalar }):
    • branch: a weighted RMS norm on x before the residual add, h = bf16(r + bf16(norm(x) wb))
      (post_attention_layernorm / post_feedforward_layernorm);
    • scalar: one bf16 the rounded sum is multiplied by, h = bf16(bf16(r + b) * scalar) (layer_scalar);
    • round: each norm in MLX's two roundings, bf16(w * bf16(x * inv)), as gemma4/glue.metal's gemma_rms_looped,
      gemma_attn_tail and gemma_dense_tail compute it; without it, one rounding bf16(x * inv * w).
    • Then y = norm(h) w and the 64-value sums of the stored y (the next affine projection's group sums), as addRmsH.
  • With no option set, addRmsTail is addRmsH: the same kernel and the same launch.
  • Two new kernels, tf_add_rms_rows_bf16h_tail (one rounding a norm, a torch-style sandwich) and
    tf_add_rms_rows_bf16h_tail_round (MLX's), from one template in zig/kernels/cuda/norms_tail.cuh whose bits are
    its rounding points. norms.cu's existing code is unchanged, so are its kernels' SASS.
  • core/norms_ref.zig: the tail in float64 at its rounding points (bf16_round.zig rounds float64 to bf16 once).

Gemma 4 uses round, with branch and without scalar for the attention tail, with both for the dense tail, and
with neither (no residual) for layer 0's input norm.

Receipt

  • Environment: TensorFold b7ce8121 (1.1.0) plus this branch (head 2b6cab85); one DGX Spark (GB10, sm_121, CUDA 13.0, nvcc 13.0.88).
    No checkpoint needed; widths from families/gemma4/config.zig (12B hidden 3,840, 31B 5,376, the 12B assistant's
    1,024). The weights' and scalars' ranges in the tests follow mlx-community/gemma-4-12B-it-4bit (norm weights
    -143 to 193, layer scalars 0.0045 to 0.89).
  • Exactness:
    • tf-cuda-test norm-tail: six forms (input norm, attention tail, dense tail, scalar alone, all MLX; dense tail and
      branch alone rounded once) at 3,840, 5,376 and 1,024, and the input norm and dense tail at the 16-byte tiles'
      edges 64, 1,984, 2,048, 2,112 and 8,192, each at 1, 3, 17 and 64 rows. 9,963,516 outputs bit-equal to float64's
      value at the rounding points; 10,244 (0.1 %) where an fp32 inverse RMS within its proven spread of float64's
      can round a point either way, each within that range; 90,240 group sums bit-equal to the fp32 tree of the stored
      outputs; every smaller row count's bits equal the 64-row call's; no options gives addRmsH's bytes.
    • The range: the fp32 inverse is within gamma(42)/2 + 8 * 2^-24 of float64's (the sum's tree halved by the root,
      four fp32 steps, the products by it); every other step of the tail is exact in fp32 or a sum of two bf16 values,
      so the output is float64's at the rounding points evaluated at the two ends of that range.
  • Decode speed: n/a, nothing calls it.
  • Prompt speed: n/a, nothing calls it.
  • Kernel contract (docs/kernel-contract.md), tf-cuda-test kernel-contract (built -Dnvcc, ReleaseFast) on the GB10:
    SUMMARY 59 kernels: 59 pass gates 1-4, 0 fail, 0 known findings; 9 controls: 9 red as planted, 0 missed; 0 limit problems
    (main: 55 kernels, 5 controls).
    • 4 new entries (zig/tests/cuda/contract_norms_tail.zig): each kernel checked on its output y and on its
      residual h, at Gemma 4 12B's and 31B's widths and the 2,048-value tile edges (7 shapes each).
    • Gates 1 and 3 are the entry's own check: every output in float64's range at the rounding points (a one-value range
      by its bits, so -0 and +0 differ; a range with an infinite end by its ordered ends; NaN only for NaN), the sums
      bit-equal to the fp32 tree. The checker's own controls (norms_tail_check.zig): a planted zero below a range
      [largest bf16, +Inf] is refused and its +Inf end accepted (the 64-value input-norm row), and the negative,
      signed-zero and NaN ends likewise.
    • bf16_round.zig keeps the sign of an underflow to zero (bf16(-2^-135) is 0x8000), checked by raw bits at
      the zero, subnormal, normal-boundary and overflow edges and over 100,000 random fp32 values.
    • Gate 4: the checked output's squares are integers exact in fp32; fp16 sums overflow (51x the bound that carries
      the four rounding points), bf16 sums stay within it, so the spec states both (sums.f16 = 40, sums.bf16 = 0).
    • Controls: four MLX tails, each without one rounding point (the branch's normalized row, the branch output, the sum
      before the scalar, the output's normalized row), each red at gate 3 on its first shape.
    • Gate 5: 2 launches recorded from tf-cuda-test kernel-contract-limits over fatbins for sm_80, 86, 89, 120 and 121
      (94-95 registers, 147 on sm_120/121, 64 static shared bytes): every record current, 0 problems.
  • Default path unchanged: cuobjdump -sass of all ten existing norms.cu kernels (tf_rms_rows,
    tf_rms_rows_sums, tf_add_rms_rows, tf_rms_rows_bf16, tf_add_rms_rows_bf16, tf_add_rms_rows_bf16h,
    tf_add_rms_rows_bf16h_f32w, tf_gated_rms_rows_64/128/256) is identical to main's on sm_80, 86, 89, 120 and
    121 (50 of 50), and their launchers are untouched.
  • The review fixes are host-side: at 2b6cab85 the norms and contract_controls fatbins for sm_80, 86, 89, 120
    and 121 are byte-identical to 88fd80f9's, and so is the SASS of every function in them (the twelve norms.cu
    kernels, the two tails included: 60 of 60; the controls: 55 of 55).
  • Tests run: zig build test from an empty cache: 154/154 steps, 2,421 of 2,430 tests passed, 9 skipped (main:
    152/152, 2,413 of 2,422). tf-cuda-test norms, norm-rows, norm-tail, act-rows pass. zig fmt --check clean.
    lean_check.py: 503 findings, as on main.
  • Not run, and why: Metal (no Metal change); sm_80, 86, 89 and 120 only through their recorded compiles (gate 5);
    no model calls it yet (step 8 of Proposal: Gemma 4 on CUDA, built on the shared CUDA operators (shared extensions first) #1048).

tf-cuda-test kernel-contract built ReleaseSafe or Debug panics on main too, in contract_ck_lane.zig:108
(zeros[0..self.x.len] past its padded(n) * k bytes at the 128-row shape); ReleaseFast runs it. Not touched here.

Checklist

  • 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
    serving path changes.)
  • No precision traded for speed. If the bits change, the description says which sums change and why.
  • A new or changed GPU kernel is registered with the kernel contract (docs/kernel-contract.md); each backend's SUMMARY line is in the receipt.
  • Prompt processing is no slower than the last release.
  • The description says which platforms I ran, Metal M1 to M5 and CUDA, and which I could not.
  • 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. No AI attribution lines.

…d MLX's rounded rows

addRmsTail extends addRmsH for Gemma 4's sandwich tails: an optional RMS norm on the
branch before the residual add, an optional bf16 scalar on the sum (rounded first), and
a rounding flag that gives each norm MLX's bf16(w * bf16(x * inv)). With no option set it
is addRmsH itself, and the existing kernels' code is unchanged.

The kernels are registered with the kernel contract: their own check compares every
output with float64's value at the rounding points (a range over the fp32 inverse's
spread), the 64-value sums bit for bit with the fp32 tree, and four controls each drop
one rounding point.
@ashhart ashhart mentioned this pull request Oct 19, 2026
@ashhart

ashhart commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Thanks @jschmied, the rounding order matches our Metal tails and the default path still calls addRmsH.

I found two reference/checker fixes before we carry this onto 1.1.2. In norms_tail_check.zig:70, a range with one infinite endpoint falls back to comparing classes, so it can accept zero below a finite lower bound. For a 64-value input-norm row of 62 ones, 0.625 and 1.0546875, with epsilon 1e-6 and the first weight the largest finite bf16, the first output's reference range is [largest bf16, +Inf] and its point is finite; the checker accepts a planted zero there. Please keep ordered endpoint checks for these ranges and add that failing control, retaining the four dropped-rounding controls.

bf16_round.bf16(-2^-135) also returns +0 where bf16 rounding gives -0, bits 0x8000. Please preserve the sign when rounding underflows to zero and add a raw-bit regression; numeric float equality misses it, as does the decided-range check when it claims bit equality for zero.

Please wrap the two new trailing comments over 120 columns, at bf16_round.zig:41 and norm_tail_tests.zig:102, and keep the SASS/contract receipts with the revised export so we can match them. We'll handle the current test-runner context and the shared registry's line limit when carrying it, with your credit; this remains operator preparation for #1048, with the family gates still to come.

Posted by Ash's AI Assistant Synthena

bf16(-2^-135) gave +0 where bf16 rounding gives -0 (0x8000). The tests now compare
u16 bits: signed zeros from underflow, subnormal ties, the normal boundary, overflow to
both infinities, and the random fp32 sweep against the fp32 path's bits.
…or one-value ranges

A range with an infinite end fell back to the float64 point's class: it accepted a zero
below a finite lower end and refused the infinite end itself. Every range is now checked
by its ordered ends (-0 below +0), a one-value range by its bits, NaN only for NaN. The
control is the 64-value input-norm row whose first output's range is [largest bf16, +Inf].
@jschmied

Copy link
Copy Markdown
Contributor Author

Thanks @ashhart, both fixed in two new commits on top (668ab157 bf16_round, 2b6cab85 the checker); no rebase.

  • Checker (norms_tail_check.zig): every range is now checked by its ordered ends, infinite ones included, with -0 below +0. A one-value range is checked by its bits, and NaN is accepted only where float64 gives NaN. Your control is in as a test: the 64-value input-norm row (62 ones, 0.625, 1.0546875, eps 1e-6, first weight 0x7f7f), whose first output's range is [largest bf16, +Inf].
    • At 88fd80f9: the point passed, the planted zero was accepted, and +Inf, the range's own upper end, was refused.
    • Now: the zero is refused, and the point and +Inf pass.
  • The audit found a few more holes of the same kind, all now covered by a second test:
    • a range with an infinite lower end ([-Inf, -largest] accepted a zero);
    • [+Inf, +Inf] and [-Inf, +Inf] fell back to the class;
    • a NaN range accepted any value of the point's class;
    • a one-value range accepted -0 for +0;
    • a range with a +0 end accepted -0.
  • bf16_round.bf16 now keeps the sign when it underflows to zero. The tests compare u16 bits: -2^-135 gives 0x8000 (it gave 0x0000 before), +2^-135 gives 0x0000, and -0, the subnormal ties (half the least subnormal, 3 * 2^-134), the largest subnormal's tie up to the least normal, the negative ties to even, the largest finite, its tie to -Inf, and the infinities are all checked. The 100,000-value random fp32 sweep now compares bits too, and it also fails on the old code.
  • Both trailing comments are now on their own lines.
  • The device code is unchanged: at 2b6cab85 the norms and contract_controls fatbins for sm_80, 86, 89, 120 and 121 are byte-identical to 88fd80f9's. The SASS matches for all ten existing kernels and both tails (60 of 60) and for the controls (55 of 55). The gate-5 records are all current, 0 problems.
  • tf-cuda-test kernel-contract (ReleaseFast): SUMMARY 59 kernels: 59 pass gates 1-4, 0 fail, 0 known findings; 9 controls: 9 red as planted, 0 missed; 0 limit problems. The four dropped-rounding controls are still red at the shapes gate.
  • norm-tail gives the same counts with the stricter checker: 9,963,516 bit-equal, 10,244 within the range, 0 non-finite. norms, norm-rows and act-rows pass. zig build test from an empty cache: 154/154 steps, 2,421 of 2,430 passed, 9 skipped. zig fmt is clean, and lean_check is at 503, as before.

The receipt in the description is updated.

ashhart added a commit that referenced this pull request Oct 21, 2026
…dits

The 1.1.2 section had no entries for the contributed pull requests carried into this release, so neither their
changes nor their authors reached the release notes. Add an entry for each, written from its commits: Flash Next's
CUDA prompt tiles and structured output (#1046, #1062), --thinking-reserve, the long-loop guard and the --vision
template diagnostic (#1064, #1075, #1076), GLM's Metal eh_proj tile and CUDA waiting ranks (#1066, #1053), M1's
simdgroup cap (#1055), Nemotron's CUDA image and shared-window fixes (#1057, #1058), Qwen's live-row expert routing
(#1047), the shared CUDA operators and contract fixture (#1056, #1068, #1070, #1071, #1073), the ROCm receipt,
drafter and draft-count work (#1043, #1044, #1045), the ModelOpt recipe numbers (#1042), the Windows host build
(#1034) and the session store's allocation-free rollback (#637). Thank #643's and #1060's reporters as the other
entries thank theirs.
@ashhart

ashhart commented Oct 21, 2026

Copy link
Copy Markdown
Owner

The CUDA bf16 residual-tail operators are included in 1.1.2 (https://github.com/ashhart/TensorFold/releases/tag/v1.1.2), with your original authorship retained. They support an optional branch norm, a layer scalar and MLX-style rounding steps. Closing this as carried, and thank you.

It landed as 265d851, 159ae69 and 38cd73a.

- Synthema, Ash's AI Assistant.

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