Skip to content

feat(hip): Inkling 2 Mini's loop kernels (cross-pass message and message gate) under the kernel contract, bit-equal to loop_model - #5012

Draft
AbrahamCete wants to merge 11 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-loop
Draft

AbrahamCete wants to merge 11 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-loop

Conversation

@AbrahamCete

@AbrahamCete AbrahamCete commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

TensorFold has no HIP kernels for Inkling 2 Mini's loop: the cross-pass message and the message gate. This adds them as
a new inkling2_loop HIP kernel group with its launcher and a kernel-contract entry at Mini's shapes:
tf_ink2_loop_messages, and the gate's two halves tf_ink2_loop_gate_down and tf_ink2_loop_gate_up. It is HIP4 of
the HIP column on #4274, after ashhart's go (issuecomment-7132785932). Kernels only: no engine, glue or attention
residual.

As in #4994, every registration compares each output's bits with families/inkling2/loop_model.zig
(crossPassMessage and messageGate). No float64 bound is used.

Where they sit. In passes 2 and 3 of the core layers (visits 18 to 41), a layer's messages come from the previous
pass's banks: B_12 and P_18, bf16, copied at the end of passes 1 and 2. The q, k and v gates mix each role's raw
attention-residual output with its message. After the MLP's attention residual, the mlp gate does the same. A token
has 96 messages and 96 gates. CUDA's engine computes a visit's 4 messages before its gates, and Metal computes all 48
at the pass reset; tf_ink2_loop_messages takes 1 to 12 core layers a call, so either works. One gate launch takes 1
to 3 gates, so a visit's q, k and v gates can share one. A gate may write over its own h, as CUDA's engine does.

Arithmetic, as loop_model.zig has it:

  • rho: the sum of squares is one fp32 chain from +0 in input order. The mean is that sum divided by 2,304 in fp32, and
    the inverse is 1 / sqrt(mean + eps): a correctly rounded square root, then a correctly rounded division, not rsqrt.
    eps is loop_model's float64 1e-6 narrowed to f32. Each normalized value is one fp32 product.
  • Message: each query's dot with each normalized bank row is one fp32 chain from +0 in input order, unfused. The logit
    is that dot times binary32(1/48), which the launcher computes as residualScale does. The softmax takes the max
    from -inf, Zig's f32 @exp of each difference and the sum from +0. Each output sums its two shares w * b from +0, so
    a column where both shares are -0 gives +0. Output is f32 [message][rows][2,304], CUDA's layout, so each role's rows
    are one contiguous plane.
  • Gate: h and m are f32. Their rho values are rounded once to bf16 (the joined norm, h's half first). Each of the 64
    zeta is one fp32 chain of 4,608 bf16 products from +0 in input order, rounded once to bf16. Each forget and gain is a
    chain of 64 from +0 in rank order through Zig's f32 std.math.tanh. The output is (1 - F) * h + G * m as four fp32
    steps: keep, left, right, sum. Output is f32.
  • A product of two bf16 values is exact in fp32 unless it overflows or underflows, so fusing the gate's dots would
    change only those products. The message dots and the f32 squares round every product, so contraction is off.

The header move. HIP4 needs the same f32 tanh and exp that #4994 ported from Zig 0.17. The first commit moves
zexp, zexpm1, ztanh, zldexp and the bf16 helpers from experts.hpp into inkling2/zmath.hpp, which
experts.hpp includes. On all four chips every inkling2 and inkling2_experts kernel's code is identical to
262b048's (hip-code-object-gate). image inkling2_experts smoke and full pass on that commit and on this head
(SUMMARY lines below).

Proofs of the f32 math, over all 2^32 inputs. tf_ink2_loop_math is a probe that runs the kernels' tanh, exp and
1 / sqrt. A small host harness ran this head's code object over every f32 bit pattern and piped the outputs to a Zig
0.17 checker, built once with libc and once without:

  • ztanh, zexp and 1 / sqrtf each give Zig's bits on all 4,294,967,296 inputs, NaN payloads included, with and
    without libc. This covers all f32 inputs, wider than the f32 <= 0 that the softmax's exp needs.
  • A one-off kernel built with this group's exact flags gave the correctly rounded result on all 2^32 inputs for
    sqrtf, 1 / x and x / 2304, and for x / y with a pseudo-random divisor y derived from each x.
  • Negative checks with the same checker on the device's own functions: tanhf differs from Zig on 109,637,798 inputs,
    expf on 41,203,423 and rsqrtf from 1 / @sqrt on 597,936,208 (beyond NaN payloads).
  • In the served kernels' code, the square root is v_sqrt_f32 followed by the correctly rounded correction
    sequence, and the division is v_div_scale/v_div_fmas/v_div_fixup. No v_rsq_f32 appears outside the rsqrt
    control and the probe's device op.

Design.

  • A message block has 256 threads and holds one row of one message. Each thread writes its 9 columns' squares, then
    their query products, into LDS (18.7 KB), and lanes 0 and 1 add each bank's terms in order. At 18.7 KB, six
    blocks fit a WGP, so all 48 messages of a row run at once.
  • A gate-down block has 256 threads, one row and 8 of the 64 ranks. Waves 1 to 6 compute each 192-column tile's
    4,608-long products into one of three LDS slots, two tiles ahead of the chains. Lanes 0 to 7 add them in order,
    reading on into the next slot. Each producer keeps three tiles of weights in flight in registers across LDS-only
    barriers. The joined norm sits as bf16 over the squares (29.6 KB of LDS, four blocks a WGP).
  • A gate-up block is 64 columns by 4 rows, one (column, row) a thread.
  • Why the products go through LDS: these chains are the whole latency. In be58440's version, where each chain lane
    converted and multiplied its own operands, the 1-row, one-gate gate down took 28.0 us. With other threads writing
    the exact f32 products and __builtin_amdgcn_sched_barrier keeping each load 24 adds ahead, it takes 21.9 us here.
    That is one queued run of each object, with no base-against-base run. Who computes a product changes nothing in its
    bits or in the order of any sum.
  • Register arrays are indexed with constants only, so no kernel uses scratch.
  • The group builds with the strict flags (-O2 -fno-fast-math -fdenormal-fp-math=ieee, -ffp-contract=off) for
    gfx1030, gfx1100, gfx1151 and gfx1201, with no chip-specific path.
  • The launcher imports only hip. Before any launch it refuses no rows or more than 2,048, no or more than 12 core
    layers, no or more than three gates, and tensors not 16-byte aligned.

Speed, measured on gfx1151. A small harness loads this group's code object, as the build makes it, and launches it
as the launcher does. Each gate launch reads a different controller from the launch before it: three-gate launches
rotate over all 48 (56 MB), one-gate launches over 16 (18.9 MB). Whether any of these reads hit a cache was not
measured. Launches were queued back to back. Times are rocprofv3 kernel-trace medians of 30 launches, from the code
object whose gfx1151 sha256 prefix is 7e7e0409. A second run of the same object matched within 0.5 us at the decode
shapes and 3.5% at the prompt shapes; there is no base-against-base run and no mirrored order.

Kernel Rows Messages or gates a launch Median, us p90, us
tf_ink2_loop_messages 1 4 14.6 14.8
tf_ink2_loop_messages 1 48 15.7 15.8
tf_ink2_loop_messages 4 48 34.2 36.1
tf_ink2_loop_messages 8 48 66.7 67.0
tf_ink2_loop_messages 512 4 319.3 323.2
tf_ink2_loop_messages 2,048 4 1,232.0 1,241.0
tf_ink2_loop_gate_down 1 1 21.9 23.6
tf_ink2_loop_gate_up 1 1 4.2 9.6
tf_ink2_loop_gate_down 1 3 23.7 23.9
tf_ink2_loop_gate_up 1 3 12.1 12.5
tf_ink2_loop_gate_down 4 3 49.6 50.5
tf_ink2_loop_gate_up 4 3 13.4 16.8
tf_ink2_loop_gate_down 8 3 73.9 78.6
tf_ink2_loop_gate_up 8 3 18.4 22.2
tf_ink2_loop_gate_down 4 1 22.7 27.4
tf_ink2_loop_gate_up 4 1 4.4 6.5
tf_ink2_loop_gate_down 8 1 25.7 30.3
tf_ink2_loop_gate_up 8 1 5.7 5.9
tf_ink2_loop_gate_down 512 1 1,286.8 1,333.2
tf_ink2_loop_gate_up 512 1 170.1 174.5
tf_ink2_loop_gate_down 2,048 1 5,084.4 5,201.9
tf_ink2_loop_gate_up 2,048 1 962.4 979.7

Per decode token, from the table, with the q, k and v gates in one launch and the 48 messages at each of the two
resets:

  • 1 row: 24 visits x (35.8 us for the q, k and v gates + 26.1 us for the mlp gate) + 2 x 15.7 us for the messages =
    1.52 ms. With 4 messages a visit instead, as CUDA's engine does, it is 1.84 ms. With each of the 96 gates its own
    launch, the gates alone take 2.51 ms.
  • 4 rows: 2.23 ms a step, 0.56 ms a token. 8 rows: 3.10 ms a step, 0.39 ms a token.
  • A 2,048-row prompt chunk, each gate its own launch: 96 x 6.05 ms + 24 x 1.23 ms = 610 ms, 0.30 ms a token.
  • These are kernel times. Launch overhead is not included (98 launches a token; not measured in this PR's runs).

A token's gates read 96 x 1,179,648 bytes of controller weights, about 113 MB; the queries add 0.9 MB. At 240 GB/s (a
1 GiB read kernel, median of 20, from #4994's runs) that is 0.47 ms, so the 1-row total is 3.2x the bandwidth bound.
The serial order sets its own floor: a gate's critical path is 6,976 dependent adds (2,304 for rho, then 4,608 for
zeta, then 64), and a message's is 4,608, so one token's 48 gate launches and 2 message launches hold 344,064
dependent adds (48 x 6,976 + 2 x 4,608). I kept no measurement of a dependent add's latency here, so I give no time for
that floor. The llama.cpp Vulkan baseline on this machine (21.9 tok/s, posted on #4274) leaves 45.7 ms for a whole
token; 1.52 ms is 3.3% of it.

The before/after in 9c61b6e's message is one queued run of each object, with no base-against-base run and no
mirrored order, and its "after" column comes from a build that differs from this head only in comments. In it, the
gate up at 1 row and one gate is 0.5 us slower (3.7 -> 4.2 us), while that row's gate pair, down plus up, is faster.

Where CUDA, Metal and loop_model differ. This follows loop_model everywhere:

Questions for you; say which you want changed:

  1. Reduction order: see feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994's second question. Here it decides more: a gate's critical path is 6,976 dependent
    adds, so these kernels are latency-bound, at 3.2x the bandwidth bound. A reference-defined parallel order might
    bring them near the bandwidth bound (not built or measured).
  2. Engine placement, for HIP5: should the messages be computed at the pass resets, as Metal does (0.03 ms a token
    here), or 4 a visit, as CUDA does (0.35 ms)? And may HIP5 pass a visit's q, k and v gates in one launch, as the
    launcher allows?
  3. Prompt rows: the gate's down half runs one row a block, 5.1 ms for 2,048 rows. A tiled variant that shares each
    weight tile across rows could cut that (not built or timed). Do you want it here, or with HIP5's prompt path?
  4. The probe tf_ink2_loop_math and the six control kernels ship in the inkling2_loop image, as
    tf_ink2_act_factors does in feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994 (its fourth question). The served kernels contain no switch; each control is
    its own compile-time instantiation.
  5. The messages' fma control fuses the second share of the output sum, not a dot. The dots' products are now computed
    by other threads into LDS, so a fused dot no longer exists as such. Is that control enough for this kernel?

Checks on this head

  • Head commit: 9c61b6e, on feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994's 262b048 (on main 3795e60).
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 165 and 165, 0 new. The base is
    main 3795e60. python3 tools/pr_check.py --base 3795e6054: 0 errors, 1 advisory warning ("pass --pr NUMBER to
    check its Unreleased line"; the changelog line is yours).
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-inkling2-loop-hip-host -Dhip=true: 12 of 12 passed. On a mock runtime they cover the launcher's
      grids and refusals and the query scale and eps. On the host they cover the gate-4 simulations, which equal
      loop_model bit for bit in fp32 order, the -0 case and the stress rows' margins. test-inkling2-experts-hip-host:
      11 of 11 passed.
    • zig build test on a clean tree of this head: 13,494 of 13,588 passed, 93 skipped, 1 failed. The failure is
      stage_hip_test "every staged call on HIP memory equals the reference, whole and in parts", the failure feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994
      reports on main 3795e60 too.
    • zig build test -Dhip=true on the same tree: 1,493 of the 1,515 tests it ran passed, 21 skipped, and the same
      stage_hip_test failed.
    • zig fmt --check build.zig zig and git diff --check: clean.
    • A code-object comparison of 262b048 and this head:
      • gfx1151: 625 kernels and functions identical and the 9 new ones added, no spill and no scratch in any of them.
      • The only changes are affine_dot2_block<DotBF16, N> instantiations in tiles/dot2.hip, which this branch does
        not touch: 4 on gfx1151 (N = 2, 3, 6 and 8) and gfx1201, 1 on gfx1100, none on gfx1030. feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994 found two
        builds of main alone differing in four instantiations of the same function (N = 2, 3, 5 and 6).
      • All 12 inkling2_experts kernels are identical on the four chips.
  • The new tests fail before their change. Each served kernel was first built with the choices CUDA makes, and the
    contract went red:
    • the probe with the device's tanhf and expf: 11651 of 986721 outputs differ; first tanh at 0x3e82c577: 0x3e7ffffe where Zig gives 0x3e7fffff;
    • the messages with rsqrt: at gate 1, message 0 row 0 column 0 is 0xc18bcc74 where loop_model gives 0xc18bcc75,
      and at shapes, 0xbf6a24ae where loop_model gives 0xbf6a24af;
    • the gate with the device's tanhf: red at gates 1, 3 and 4, for example gate 0 row 0 column 2 is 0x3d79d48a where loop_model gives 0x3d79d488, and 37.1x over its exact-sum bound at k 4608.
  • CI: not run yet on this head; opened as a draft.
  • Not run, and why:
    • gfx1030, gfx1100 and gfx1201 on a device: I have only gfx1151. All three build, and their records match the code
      objects.
    • Same-engine exactness, teacher-forced fidelity and the decode speed bar: no engine calls these kernels yet.
    • A served trace showing these kernels in a request: same reason.
    • The timing has no base-against-base run and no mirrored order (B1 C1 C2 B2), and no machine state (clock,
      temperature, /dev/kfd holders) was recorded beside it.
    • Truly cold one-gate cells: one-gate launches rotate over 16 controllers, not 48.
    • Three gates a launch at prompt rows, 16 and 64 rows, and warm weights: not timed.
    • The latency of a dependent fp32 add and of an empty launch: measured while writing the kernels, but the output was
      not kept, so no figure for either is given here.
    • Two builds of the same tree showing affine_dot2_block N = 8 changing: the build nondeterminism above is shown
      for N = 2, 3, 5 and 6 only.

Receipt

n/a: these kernels do not reach inference yet; no engine or server calls them. The kernel contract below is the
evidence, and the timing above is a kernel-level measurement, not a served receipt.

Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract (tf-hip-kernel-contract image inkling2_loop); none replaces another kernel.
    Each output's bits are compared with loop_model's (or Zig's, for the probe), NaN as a class:

    • tf_ink2_loop_math: tanh, exp and 1 / sqrt at 328,907 inputs, 986,721 outputs. The inputs are every branch edge of
      the ported tanhf, expf and expm1f one ulp either side and both signs (expm1's at half its argument too), zeros,
      infinities, NaNs, subnormals, the largest finite, exp's subnormal outputs from -87.25 to -104.5 every 1/64, all
      65,536 bf16 patterns and 262,144 random f32.
    • tf_ink2_loop_messages: 1 row at one and all 12 core layers; 4 and 8 rows at 12 layers; prompt calls of 16 rows
      at one layer, 64 at 12, and 2,048 at one; 7 shapes. Both banks hold -0 at two columns a row, so the +0 start is
      checked at every shape. One-layer cells use the last core layer's query rows; 12-layer cells use all 24.
    • tf_ink2_loop_gate_down with tf_ink2_loop_gate_up: 1 row with one and three gates; 4 and 8 rows with three;
      prompt calls of 16 rows with one, 64 with three, and 2,048 with one; the up block's row edges at 3, 4 and 5; 10
      shapes. The second and third gates of each call write over their own h.
    • Gate 1 plants NaN and infinities: a NaN bank value, infinite bank and query values (messages); a NaN h, an
      infinite m, an infinite forget weight and a NaN gain weight (gates). Both NaN and finite outputs must occur.
    • Gate 4's rows: banks of +-1 and queries nonzero at three columns (messages); h and m of +-1 with three +-256, and
      three small integer weights a row (gates). Every fp32 sum is exact in any order. fp16 sums would miss by 42,505x
      (messages) and 605,453,945x (gates), and bf16 by 252,578x and 3,671,421x.
  • A planted control for each new kernel, each its own kernel, red at shapes:

    • the probe with the device's own tanhf, expf and rsqrtf: 58315 of 986721 outputs differ;
    • messages with rsqrt for 1 / sqrt: 0xc0407054 where loop_model gives 0xc0407053;
    • messages with the second share fused into an fma: 0xbf9f3bf3 where loop_model gives 0xbf9f3bf4;
    • messages summing m0 + m1 without the +0 start: column 11 is 0x80000000 where loop_model gives 0x00000000;
    • gates with the device's own tanhf: 0x3fd8cd82 where loop_model gives 0x3fd8cd84;
    • gates with (1 - F) * h + G * m fused into one fma: 0x3f202abf where loop_model gives 0x3f202abe.
  • Each backend's SUMMARY line (gfx1151, ROCm 10.1's hipcc, HIP 7.16); the logs keep no exit status:

    SUMMARY inkling2_loop HIP full: 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 6 controls: 6 red as planted, 0 missed; 0 limit problems; gates 801 ms, limits 4 ms

    SUMMARY inkling2_loop HIP smoke: 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 6 controls: 6 red as planted, 0 missed; 0 limit problems; gates 459 ms, limits 5 ms

    image inkling2_experts, which this branch changes only by the header move:

    SUMMARY inkling2_experts HIP full: 12 kernels: 12 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed; 0 limit problems; gates 11790 ms, limits 4 ms

    SUMMARY inkling2_experts HIP smoke: 12 kernels: 12 pass gates 1-4, 0 fail, 0 known findings; 5 controls: 5 red as planted, 0 missed; 0 limit problems; gates 10511 ms, limits 4 ms

    zig build hip-kernel-contract-limits: all 36 inkling2_loop and 24 inkling2_experts records PASS on the four
    chips. The step exits 1 with 11 problems, the same 11 as feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model #4994 reports on main 3795e60 with this hipcc, all in
    other groups: tf_moe_combine_gate (gfx1030, gfx1100, gfx1151), tf_vl_resize (all four chips), and the 6- and
    8-bit relu2 stream tiles 2x8 and 4x4 on gfx1100.

    Records (hip_records_inkling2_loop.zig), VGPRs on gfx1030 / gfx1100 / gfx1151 / gfx1201; no scratch on any chip:

    Launch Threads VGPRs LDS bytes
    tf_ink2_loop_messages 256 66 / 65 / 65 / 65 18,712
    tf_ink2_loop_gate_down 256 73 / 73 / 73 / 73 29,576
    tf_ink2_loop_gate_up 256 112 / 112 / 112 / 111 1,024
    tf_ink2_loop_math 256 15 / 15 / 15 / 15 0
    tf_ink2_loop_ctl_rsqrt 256 66 / 65 / 65 / 65 18,712
    tf_ink2_loop_ctl_fma 256 65 / 65 / 65 / 65 18,712
    tf_ink2_loop_ctl_signed_zero 256 66 / 65 / 65 / 65 18,712
    tf_ink2_loop_ctl_tanhf 256 107 / 106 / 106 / 105 1,024
    tf_ink2_loop_ctl_gate_fma 256 112 / 112 / 112 / 111 1,024
  • Chips I could not run: gfx1030, gfx1100 and gfx1201 (limits only), and every CUDA SM and Metal chip.

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency. (The three device
    registrations failed before their kernels were right, as shown above. The launcher's host tests were written with
    the launcher and not run without it.)
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.
  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off. (n/a: no engine)
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (n/a: no engine)
  • No precision traded for speed. If the bits change, the description says which sums change and why. (n/a: new kernels)
  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled. (n/a: no engine)

…32 tanh and exp

Inkling 2 Mini's serial reference (families/inkling2/loop_model.zig)
evaluates the routed experts' activation with Zig's f32 std.math.tanh
and @exp, which compiler-rt's expf implements. The device's own tanhf
and expf give other bits, so experts.hpp ports Zig 0.17's f32 tanh,
expm1, exp and ldexp operation for operation, with the constants'
exact bits.

A new kernel group, inkling2_experts (strict: -O2 -fno-fast-math,
IEEE denormals), starts with tf_ink2_act_factors. The contract
(image inkling2_experts) holds both factors, softcap4(g) * sigmoid(g)
and softcap25(u), to Zig's bits at all 65,536 bf16 inputs; its
control runs the device's tanhf and expf and goes red at shapes.
A host test shows loop_model's expertActivation is one fp32 product
of the two factors rounded once to bf16, so the factors' bits fix
every activation output.

Records for gfx1030, gfx1100, gfx1151 and gfx1201; the launcher
imports only hip, and a mock runtime checks its grid.
…l to loop_model

tf_ink2_nvfp4_down and tf_ink2_mxfp8_down decode w2 in registers as
loop_model's reference rows do: NVFP4 as
bf16(E2M1 * E4M3 * (bf16(amax) / bf16(denominator))), MXFP8 as
bf16(E4M3 * 2^(scale - 127)) through ldexp, so scale 255 is 2^128 and
does not overflow the way CUDA's fp32 2^(scale - 127) does. Each output is one
fp32 chain over the route's 1,152 activations in input order
(contraction off), rounded once to bf16. A block holds 64 outputs of
one route, its activation row staged in LDS; an id past the experts
gives a NaN row instead of reading past the weights.

The contract compares every output's bits with loop_model's
nvfp4ReferenceRow, mxfp8ReferenceRow and expertProjection, at decode
and prompt rows, edges of 1, 63, 64 and 65 outputs and 32 and 64
inputs. Two one-hot cells cover every MXFP8 (code, scale) pair and
every NVFP4 pair at eight amax values; the MXFP8 cells route to Mini's
last experts through a weight base that many experts early. Gate 4's
stress rows sum exactly in fp32 in any order, overflow fp16 and miss
by over 100x in bf16, which a host test checks. The control reads
each row's scales one group late and goes red at shapes.

The launcher refuses a reduction past 2,304 or not of whole scale
groups, misaligned codes, an NVFP4 call without amax or denominator,
and more than 65,535 routes.
…ed SwiGLU bit-equal to loop_model

tf_ink2_nvfp4_gu and tf_ink2_mxfp8_gu run w13's gate row 2j and up
row 2j + 1 against a token's 2,304 inputs, each one fp32 chain in
input order over weights decoded in registers, rounded to bf16, then
bf16(softcap4(g) * sigmoid(g) * softcap25(u)) left to right in fp32
through the ported Zig tanh and exp. A block holds 64 outputs of one
route; its token's row is staged in LDS.

The contract compares every output's bits with loop_model's
expertProjection and expertActivation at decode and prompt rows and
the same edges as down; the MXFP8 cell routes to experts 120-127.
Gate 4's stress rows give g = u = 1 exactly in fp32, where fp16 sums
are not finite and bf16 sums miss by over 100x after the activation.
Two controls go red at shapes: w13 given as gate rows then up rows
(not interleaved), and one input a bf16 step up.
…to loop_model

tf_ink2_combine sums a token's routes from fp32 zero in ascending
(expert id, slot) order, each term the fp32 route weight times the
bf16 down output, then rounds once to bf16, as loop_model's
combineExperts does; ids outside the 128 experts are skipped. A block
holds 64 outputs of one token.

The contract compares every output's bits with combineExperts at 1,
16 and 2,048 tokens. Gate 4's terms (2^20, 3, 5, 7, 9, 11, -2^20 and 1
by ascending id) are exact in fp32, overflow fp16 and lose their
residual in bf16; a host test shows route order would give other
bits. The control rounds the fp32 route weights to bf16 and goes red
at shapes.

docs/kernel-contract.md describes the inkling2_experts image: the
kernels, their rounding points, the factor proof, the decode cells,
gate 4's rows, the NaN rule, the five controls and the refusals.
…once in LDS, bits unchanged

The gate/up and down kernels ran one thread an output, each thread
reading its own weight rows and decoding every weight in registers,
with few waves resident at decode rows. Now a block of 256 threads
holds 64 outputs of one expert and serves up to eight of that
expert's routes in a launch (the block of its first route does; the
others return). Each 64-input tile of the block's rows is loaded with
16-byte loads, one tile ahead, and decoded once into bf16 in LDS by
all 256 threads: NVFP4 through a per-expert table of every E4M3 scale
and E2M1 magnitude (the sign flips the bf16 bits, since
(-a) * b * phi is -(a * b * phi) exactly), MXFP8 through a table of
E4M3 values and the same ldexp. Each output's chain then runs from
LDS, acc = acc + w * x in input order, gate and up interleaved; the
sum order, the rounding points and every output bit stay as before.
The decode loops index their registers with constants only, so no
kernel uses scratch.

The contract adds four cells whose 4 and 8 tokens give every route its
own expert (the most weight traffic a launch can need); with the
existing cells, 12 kernels pass gates 1-4 bit for bit and the 5
controls stay red. gate/up and down launch 256 threads a block; the
records and the launcher's tests follow.
… flight, bits unchanged

On the previous head, NVFP4 gate/up and down took as long as MXFP8
for the same tile count while reading half the bytes: every tile paid
a whole memory latency. The next tile's prefetch was waited for at
once, for three reasons. The scale bytes were packed into one register
as they arrived, under a branch. The x values used 16-bit loads into
half registers. And __syncthreads() fences global memory, so it waited
for every outstanding load.

Now every tile load is unconditional, from an address that is always
valid (a run past the tile reads its row's start, a row past the
block's its last row), with each scale byte and x value in its own
register. The barriers fence LDS only, so later tiles' loads stay in
flight across them. A tile's registers decode into LDS and then load
the tile two ahead, so two tiles are in flight with no register copy.
NVFP4's 16-byte and 8-byte row paths are two instantiations sharing
one LDS block.

The decode, each output's chain order and every output bit are
unchanged: the contract's 12 kernels pass bit for bit and its 5
controls stay red. No kernel spills or uses scratch, and the VGPRs
keep 16 waves a SIMD.
The loop kernels need the same f32 tanh and exp that the routed
experts use, ported from Zig 0.17 operation for operation, and the
same bf16 rounding. Those functions move from experts.hpp into
inkling2/zmath.hpp, which experts.hpp includes; the build lists the
new header so an edit to it rebuilds the groups.

On all four chips every inkling2 and inkling2_experts kernel's code
is identical to the previous head (hip-code-object-gate). The only
changes are in tiles/dot2.hip's affine_dot2_block, which this does
not touch and which changes between builds of the same tree.
`image inkling2_experts` smoke and full: 12 kernels pass gates 1-4
and the 5 controls are red as planted.
…to Zig's bits

The loop kernels (the cross-pass message and the message gate) must
match loop_model.zig bit for bit, and loop_model runs Zig 0.17's f32
std.math.tanh, @exp and `1 / @sqrt`. This adds the inkling2_loop
kernel group, built with the strict flags, and its first launch:
tf_ink2_loop_math, a probe that runs the kernels' tanh and exp (the
ports in zmath.hpp) and their inverse square root (a correctly
rounded sqrt, then a division) over given inputs.

The contract checks the probe against Zig at every branch edge of the
ported functions, all 65,536 bf16 patterns and 262,144 random f32: on
gfx1151 every output has Zig's bits. A control runs the device's own
tanhf, expf and rsqrtf instead and goes red at `shapes` (58,315 of
986,721 outputs differ). Outside the contract, the probe matches Zig
on all 2^32 f32 inputs for each of the three functions.

The group plumbing (build group, kernels.zig, contract entry, record
families, a host step `test-inkling2-loop-hip-host`) follows the
inkling2_experts group's.
tf_ink2_loop_messages computes loop_model.crossPassMessage for every
row, core layer and role (q, k, v, mlp): rho of the bf16 banks B_12
and P_18, each query's dot with both, the two-way softmax, and the
weighted sum. Its output is f32 [message][rows][2,304], CUDA's
layout, so each role's rows are one plane a gate can read. A block of
256 threads holds four rows of one message in LDS; one lane per
(row, bank) runs the sum of squares and then the dot, each as a single
fp32 chain from +0 in input order.

Where CUDA and Metal round otherwise, this follows loop_model: 1 / sqrt
as a correctly rounded sqrt and a division (not rsqrt), unfused query
dots in input order, Zig's f32 exp, and the output's sum from +0, so a
column where both shares are -0 gives +0 (CUDA and Metal give -0).

The contract compares every output's bits with loop_model's at 1, 4
and 8 rows for one and all 12 core layers, the row group's edges, and
prompt calls of 16, 64 and 2,048 rows. Gate 4's banks of +-1 and
three-term queries keep every fp32 sum exact in any order; fp16 sums
would miss by 42,505x and bf16 by 252,578x. Three controls go red at
`shapes`: rsqrt for 1 / sqrt, fused query dots, and the sum without
its +0 start.
tf_ink2_loop_gate_down and tf_ink2_loop_gate_up compute
loop_model.messageGate for one to three gates a launch, so the q, k
and v gates of a visit can share one. Down: a 256-thread block a row
and 8 ranks finds rho of h and m, rounds the joined norm to bf16, and
runs 8 zeta chains of 4,608 from +0 in input order, each rounded to
bf16. Up: a thread a column runs the forget and gain chains of 64 in
rank order through Zig's f32 tanh (ported in zmath.hpp), then
(1 - F) * h + G * m as four fp32 steps. A gate may write over its own
h, as the engine's gates do.

A dependent fp32 add costs about 2.1 ns on gfx1151 from registers and
2.6 ns from LDS, but 5-7 ns when the same lane also converts and
multiplies its operands. So every thread computes the chains' f32
products into LDS (each product loop_model's, exact or rounded once),
and the chain lanes only load and add, two blocks ahead. The weights
of the next three 256-column tiles stay in flight in registers across
LDS-only barriers.

The contract compares every output's bits with loop_model's at 1, 4
and 8 rows for one and three gates (the second and third in place),
an up block's row edges, and prompt calls of 16, 64 and 2,048 rows.
Gate 4's h and m of +-1 with three +-256 keep every fp32 sum exact in
any order; fp16 sums would miss by 6e8x and bf16 by 3.7e6x. Two
controls go red at `shapes`: the device's own tanhf, and the last two
steps fused into one fma.
…ts unchanged

Each message and gate is bounded by its serial fp32 chains (loop_model
fixes their order): 4,608 dependent adds for a message, 6,976 for a
gate. On gfx1151 a dependent add costs about 2.1 ns from registers,
but these ran at 3.5 ns or more: the chain lanes converted and
multiplied their own operands, and the compiler waited on each LDS
load four adds after issuing it.

- Messages: one row a block (18.7 KB of LDS, so all 48 messages of a
  row are resident), every thread writes its columns' squares and
  then query products into LDS, and lanes 0 and 1 only add them.
- Chains read 32 floats ahead, with __builtin_amdgcn_sched_barrier
  between blocks of 8 so each load stays 24 adds ahead (2.9 ns a step).
- Gate down: waves 1-6 compute each tile's products two tiles ahead
  into three slots, so the 8 chain lanes run on into the next tile
  without a pause; the joined norm is kept as bf16 over the squares
  (29.6 KB of LDS, four blocks a WGP).
- Gate up: a block of 64 columns by 4 rows, one row a thread row.
- The messages' fma control now fuses the second share of the sum.

rocprofv3 medians on gfx1151, cold weights rotating over 48
controllers, launches queued (c4a9d22/be58440fb -> this):
  messages, 1 row:   4 messages 21.4 -> 14.8 us, 48 messages 49.4 -> 15.6
  messages, 8 rows:  4 messages 24.0 -> 15.0 us, 48 messages 73.6 -> 66.6
  messages, 2,048 rows, 4 messages: 1,503 -> 1,228 us
  gate down, 1 row: 1 gate 28.0 -> 22.8 us, 3 gates 29.8 -> 23.6
  gate down, 8 rows, 1 gate: 55.8 -> 25.8 us; 2,048 rows: 8,225 -> 5,091
  gate up, 1 gate: 1 row 3.7 -> 4.2 us, 8 rows 17.9 -> 5.6 us

`image inkling2_loop` smoke and full: 3 kernels pass gates 1-4 with
the same bits, 6 controls red. No spills or scratch on any chip.

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.

1 participant