Skip to content

cuda embed_rows: MLX affine tables at 2 to 8 bits and a bf16 scale - #1070

Closed
jschmied wants to merge 2 commits into
ashhart:mainfrom
jschmied:cuda-embed-gemma
Closed

jschmied wants to merge 2 commits into
ashhart:mainfrom
jschmied:cuda-embed-gemma

Conversation

@jschmied

Copy link
Copy Markdown
Contributor

What this changes

Includes core/bf16_round.zig with #1056's sign fix (an underflow to zero keeps its sign, checked by raw bits), so the four steps share one identical file.

Step 3 of #1048 (beside #1056 and #1068; the rounding points are options on the shared operator, off by default, as agreed there): embed_rows gets what Gemma 4's embedding needs, as one shared option of the MLX affine rows. Nothing calls it yet.

  • EmbedRows.affine(ids, w, scales, biases, out, rows, d, .{ .bits, .group, .scale }):
    • bits: MLX's affine codes at 2, 3, 4, 5, 6 or 8 bits, in MLX's little-endian words (a code may cross a word);
      group: 32, 64 or 128 values a scale and bias;
    • each value is MLX's dequantize, bf16(q * s + b) (the product is exact in fp32, so fma or not is the same);
    • scale: a bf16 value each row is multiplied by in fp32 and rounded to bf16 again, bf16(bf16(q * s + b) * scale),
      as gemma4/glue.metal's gemma_embed computes the embedding times MLX's weak-typed bf16(sqrt(hidden)). A scale
      that is not a bf16 value (or not finite) is refused.
  • With 4 bits, no scale and groups of 32 or 64, affine is affine4Groups: the same kernel and the same launch.
  • One new kernel, tf_embed_rows_affine, from zig/kernels/cuda/embed_affine.cuh (it reads codes with
    affine_codes.cuh's code_at, as affine8.cu does), whose keep bit is the rounding point (a constant in the
    served kernel). embed_rows.cu's existing code is unchanged.
  • core/embed_ref.zig: MLX's code unpacking and the row value at its rounding points (the fp32 sum, its bf16, the
    fp32 product, its bf16); bf16_round.zig as in cuda norms: bf16 residual tails with a branch norm, a layer scalar and MLX's rounded rows #1056 and cuda act_rows: GeGLU and SwiGLU in MLX's bf16 steps #1068.

Gemma 4 uses .{ .bits = 4, .scale = 62 } on the 12B 4-bit checkpoint (bf16(sqrt(3840))), 73.5 on the 31B
(bf16(sqrt(5376))), and .bits = 8 on the oQ8e checkpoints.

Receipt

  • Environment: TensorFold d1018b31 (1.1.1) plus this commit; 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 scales' and
    biases' ranges in the tests follow mlx-community/gemma-4-12B-it-4bit's embed_tokens (scales -0.18 to 0.32,
    biases -4.1 to 2.7).
  • Exactness:
    • tf-cuda-test embed-rows: every width (2, 3, 4, 5, 6, 8 bits) at 3,840 and 5,376 with their scales, at 3,840
      without one, at the blocks' edges 64, 1,984, 2,048 and 2,112, and with groups of 32 (scaled) and 128, plus 4-bit
      groups of 32 at 2,560; each at 1, 3, 17 and 64 rows. 8,347,648 outputs bit-equal to float64's value at the
      rounding points; every smaller row count's bits equal the 64-row call's; scale 1 gives tf_embed_rows_affine4's
      bytes; the refusals (7 bits, 1 bit, a group of 48, an unrounded or infinite scale, an unaligned output) hold.
    • Why bits and not a range: the code times a bf16 scale is exact in fp32 (at most 16 significant bits), so the sum
      is rounded once to fp32; a bf16 value times a bf16 scale is exact in fp32 too, so every output is float64's value
      at those points, bit for bit.
    • tf-cuda-test norm-rows (the existing 4-bit rows and copies) passes.
  • 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 92 kernels: 92 pass gates 1-4, 0 fail, 0 known findings; 9 controls: 9 red as planted, 0 missed; 1533 limit problems
    (main: SUMMARY 85 kernels: 85 pass gates 1-4, 0 fail, 0 known findings; 7 controls: 7 red as planted, 0 missed; 1533 limit problems).
    • The limit problems are main's: 1.1.1's records that are zero or stale (tf_q35_*, tree_round and others).
      This change adds none; it leaves that count as it is.
    • 7 new entries (zig/tests/cuda/contract_embed.zig): tf_embed_rows_affine4 (4 bits, as served today) and
      tf_embed_rows_affine at each width with its scale, each at Gemma 4 12B's and 31B's widths and the 2,048-value
      block edges (7 shapes each).
    • Gates 1 and 3 are the entry's own check: every output bit-equal to float64's value at the rounding points (NaN
      where float64's is NaN; infinities as float64's), with one group in 16 far past the checkpoint's ranges. Gate 4 is
      N/A (no sums).
    • Controls: tf_ctl_embed_affine run without the dequantized value's bf16 rounding, and with the scale folded into
      the group's scale and bias (q (s scale) + b scale, rounded once): each red at gate 3 on its first shape.
    • Gate 5: tf_embed_rows_affine (256 threads) recorded from tf-cuda-test kernel-contract-limits over fatbins for
      sm_80, 86, 89, 120 and 121 (38-40 registers, no shared memory): its record current.
  • Default path unchanged: cuobjdump -sass of tf_embed_rows_affine4, tf_embed_rows_bf16 and
    tf_embed_rows_bf16_copies is identical to main's on sm_80, 86, 89, 120 and 121 (15 of 15), and their
    launchers are untouched.
  • Tests run: zig build test from an empty cache: 213/213 steps, 2,965 of 2,979 tests passed, 14 skipped (main: 211/211, 2,959 of 2,973). tf-cuda-test embed-rows and
    norm-rows pass. zig fmt --check clean. lean_check.py: 444 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).

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.

EmbedRows.affine reads MLX's affine tables at 2, 3, 4, 5, 6 or 8 bits (groups of 32, 64
or 128) and, given a bf16 scale, multiplies each dequantized bf16 value by it and rounds
again: bf16(bf16(q * s + b) * scale), Gemma 4's embedding times bf16(sqrt(hidden)). With
4 bits, no scale and groups of 32 or 64 it is affine4Groups itself, and the existing
kernels' code is unchanged.

The 4-bit rows and the new kernel at each width are registered with the kernel contract:
every output bit-equal to float64's value at the rounding points, and two controls, one
without the bf16 rounding before the scale and one folding the scale into the group's
scale and bias.
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.
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 embed_rows extension is included in 1.1.2 (https://github.com/ashhart/TensorFold/releases/tag/v1.1.2), with your original authorship retained. It reads MLX affine tables at 2, 3, 4, 5, 6 or 8 bits with an optional bf16 scale. Closing this as carried, and thank you.

It landed as 36caa42 and 42cb101.

- Synthema, Ash's AI Assistant.

@ashhart ashhart closed this Oct 21, 2026
@jschmied
jschmied deleted the cuda-embed-gemma branch October 23, 2026 21:02
@ashhart ashhart added the landed Landed on main by the maintainers; the commits keep the contributor's authorship label Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

landed Landed on main by the maintainers; the commits keep the contributor's authorship

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants