Skip to content

feat(hip): Inkling 2 attention kernels under the kernel contract - #4633

Merged
ashhart merged 8 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-attention
Nov 24, 2026
Merged

ashhart merged 8 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-attention

Conversation

@AbrahamCete

@AbrahamCete AbrahamCete commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

TensorFold has no HIP kernels for Inkling 2's attention. This adds them: an inkling2 HIP kernel group with the prep
(tf_ink2_prep), the relative-bias table (tf_ink2_rel_table), chunked attention for sliding layers (tf_ink2_attn)
and global ones (tf_ink2_attn_fold, a split form a block a 1,024-key sub-chunk, and tf_ink2_attn_prompt), and the
ordered merge (tf_ink2_merge), with their launcher and their kernel-contract entry at Mini's shapes. It is the HIP
attention slice of #4274's plan, the HIP counterpart of M1, started on #4274 (issuecomment-7077604368). Kernels only:
no engine, loop, experts or glue.

The gate, as ashhart set it on #4265 (issuecomment-7077460180):

HIP needn't match #4125's CUDA bits. The agreed gate is the kernel contract on gfx1151 with planted controls,
same-engine exactness on HIP (drafted equals plain, resumed equals fresh, concurrent equals solo), and teacher-forced
fidelity against huggingface/transformers#51050.

This pull request covers the first part, the kernel contract on gfx1151 with planted controls. Same-engine exactness and
teacher-forced fidelity need an engine on #4387's host, which is not here.

Arithmetic. The kernels keep #4125's rounding points, as #4387's Metal attention does, and follow its structure
(prep, table, chunk attention, ordered merge):

  • prep: per-head q and k L2 clips, fminf(thr / (norm + 1e-6), 1); on global layers q and rel scaled by
    tau = 1 + alpha ln(max((pos + 1) / floor, 1)) after a first bf16 rounding; a gamma-free RMS norm on v; k and v into
    the segment's cache at slot pos % ring;
  • the table: bf16(sum_j rel[j] proj[j][d]), fp32 in tap order, for distances below 1,024;
  • scores in fp32 with scale 1/sqrt(128) plus the table's bias, exp2 with an online max, the window of 1,024 on sliding
    layers and every key on global ones;
  • every P rounded to bf16 before both its sum and P V;
  • chunks of 256 keys (sliding) and 16,384 (global), global chunks in 1,024-key sub-chunks, folded in a fixed order;
  • the merge folds the chunks in order, then the sink, last, as a raw logit, then the sigmoid of the raw gate, and
    rounds once to bf16. attend() says so: glue must not apply either sigmoid (Inkling 2 Mini on CUDA and Metal #4387's double-sigmoid defect).

Heads, key heads, n_floor and the clips are runtime arguments, as in #4125's launcher. Mini is 24 query and 8 key heads
with n_floor 8,192. The KV layout is #4125's and #4387's, [kv][ring][128] bf16 per segment, at per-segment offsets.

Design.

  • Scalar fp32 sums. A bf16 x bf16 product is exact in fp32, so each sum's error is that of its IEEE adds. The code
    builds for gfx1030, gfx1100, gfx1151 and gfx1201 with no chip-specific path and no trap body. WMMA is not used.
  • One wave holds a (row, head) pair. A block's pairs share one key head's 64-key K/V tiles in LDS (K rows padded one
    dword, so each lane reads its own bank). Each lane scores two keys with a 128-term fp32 dot and owns 4 of the 128
    output dims.
  • Every path runs the same per-pair steps on the same 64-key tiles, so the split and prompt launches are bit-equal to
    the fold by construction; the contract checks it on the device.
  • The prompt kernel shares each tile among 8 pairs. It uses one LDS stage (37,120 bytes, 36.25 KiB) and loads the next
    tile into registers meanwhile. CUDA's 96 KiB three-stage pipeline does not fit RDNA's 64 KiB a workgroup.
  • The group builds with the strict IEEE flags (-O2 -fno-fast-math -fdenormal-fp-math=ieee, -ffp-contract=off).

The reference. #4125's float64 reference moves from zig/tests/cuda to core.contract.inkling2_attn_ref, so both
backends hold their kernels to the same rounding points. A Call now names its query heads, key heads and fp32 chains
(Chain.cuda by default, Chain.hip for scalar IEEE adds), and tauAt takes the model's floor. CUDA's tests change
only their import. An independent check compared the old and new reference bit for bit: all 18 CUDA served shapes,
random, non-finite and stress fills, 2 seeds; 163,440 (row, head) pairs, 41.8M want and tolerance values, 2,016 gate-4
replays, and tau over 2^21 positions, with no difference. Pinned tests in the moved file hold those bits.

Beyond the plan, or where it was silent; say which you want changed:

  • attend() refuses, before any launch, a ring that is not whole 64-key tiles or is shorter than the window plus the
    call's rows less one, a call with no streams, and partial buffers smaller than rows x heads x stride.
    Rows.streams has no default, so a multi-stream caller cannot fall into the one-stream prompt kernel by omission.
  • A global position past the ring is not refused, because the contract's 4,096-slot ring over 1M keys wraps on purpose.
    The engine's glue keeps a global layer's positions inside its ring.
  • Global KV is kept as whole-stream rings, as Inkling 2's attention kernels under the kernel contract #4125 does. Should HIP's engine use hip_serve's 64-position pages for
    global layers instead? The tile load reads each segment's ring as one contiguous block, so pages would need a page
    table there.
  • Inkling 2's attention kernels under the kernel contract #4125's prep test (zig/tests/cuda/contract_inkling2_attn_prep.zig) narrows the tau range for a negative value that
    straddles a bf16 boundary (it scales the more negative end by 1 - 8u). The HIP copy widens each end by its own sign. I
    did not change CUDA's cases; it was already on the base.

Size: +2,177/-31 in 19 files, seven commits.

Checks on this head

  • Head commit: e90a42e, on main 14951bc, built from a git archive tree.
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: 165 and 165, 0 new.
    python3 tools/pr_check.py --base origin/main: 0 errors, 1 advisory warning (the changelog line needs this pull request's number).
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-inkling2-hip-host test-inkling2-cuda-host compile-cuda-tests -Dhip=true on this head: 21 of 21 tests
      passed, all steps succeeded.
    • The core contract's tests for the moved reference and every HIP record: 20 of 20 passed.
    • zig build check-hip-kernel-contract-host -Dhip=true: builds.
    • zig build test -Dhip=true on this head: 12,788 of 12,883 passed, 94 skipped, 1 failed. The failure is on the base
      too and is not in files this changes: stage_hip_test "every staged call on HIP memory equals the reference, whole
      and in parts" fails on main 5c1fea6 as well, run alone on a quiet GPU, and main has not changed
      zig/src/fabric/tp/ since.
    • zig fmt --check on the changed files and git diff --check: clean.
  • The new tests fail before their change:
    • the moved reference's tests did not compile before the parameterization (tauAt undeclared);
    • the gate-5 records first registered empty: 24 stale records on the four chips;
    • the launcher's host tests: the ring refusals, the stream count and the partial room each expected error..., found void before its check;
    • the exact-P cases: with P left unrounded in the tile (const float pa = exp2f(sa - mu), ...), smoke goes red on
      exactly those two registrations (13 kernels: 11 pass gates 1-4, 2 fail), while every other gate stays green.
  • CI: green on e90a42e: fmt, zig, zig-b, zig-windows, zig-macos-dev-tools, pytest,
    release-paths (ubuntu-24.04), benchmark-clients (ubuntu, windows) and
    comfyui-moss-installer pass; host-nightly-linux and host-nightly-macos skipped.
  • 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.
    • CUDA's device contract: no NVIDIA GPU here. The reference move is checked on the host (above).
    • Small's shape (TP=2 rank: 24 query and 4 key heads, n_floor 128,000) on a device. The kernels take it as runtime
      arguments. An independent run of this contract at 4 and at 24 key heads, on an earlier head with Mini's floor,
      passed every registration but the sliding one, which stopped at a probe shape the test refuses (3 rows at 2 keys).
    • Timing. Speed is not this slice's bar, and no engine calls these kernels yet.

Receipt

n/a: these kernels do not reach inference yet; no engine or server calls them. The kernel contract below is the
evidence. Same-engine exactness, teacher-forced fidelity against huggingface/transformers#51050 and the decode speed bar
come with the engine on #4387's host.

Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract, and the kernel each one replaces (tf-hip-kernel-contract image inkling2, at
    Mini's 24/8 heads, served shapes to 1M keys on a 4,096-slot global ring that wraps):

    • tf_ink2_prep sliding and global: 8 shapes each, each output inside its range at the device's rounding points,
      tau at n_floor 8,192 to 1M positions, including pos + 1 = 8,193 and 8,194.
    • tf_ink2_rel_table: 4 shapes within the float64 bound, worst 0.996 of it; gate 4's sums exact, bf16 would miss 1,792x.
    • tf_ink2_attn + tf_ink2_merge (sliding): 17 shapes within the bound, worst 0.779.
    • tf_ink2_attn_fold + tf_ink2_merge (global): 18 shapes within the bound, worst 0.726, including rows at
      positions 0 to 1,024 against float64.
    • The split and prompt launches replace the fold: 14 shapes each, bit-equal to it.
    • Three streams in one launch replace each stream run alone, at its row and cache offsets, bit-equal: prep (3 shapes),
      sliding, fold and split (12 shapes each). The second and third streams sit near half and a third of the context,
      far from the call's last position.
    • Two exact-P cases (sliding and fold): rows below position 64 with q 0, no sink, a gate whose sigmoid is 1, integer
      values, and biases drawn so each bf16(exp2f) is more than 2^-21 from a rounding tie. Every sum is then exact in
      fp32, and each output must equal bf16(fp32(sum P v / sum P)) bit for bit (7 shapes each). The float64 bound alone
      allows P's bf16 rounding either way, so this is what pins it.
    • Gate 4's sums at 1M keys: fp16 would miss by 736x (sliding) or overflow (global), bf16 by 256x. The exact-P cases
      state that 64 keys prove neither.
    • Gate 1 plants a NaN q, a +inf sink, a NaN sink, both gate infinities, a NaN gate and infinities in keys and values.
  • A planted control for each new kernel, and each one fails as planted (through the device's inputs or launch; the
    served kernels run unchanged), all red at shapes:

    • a bias read one distance late (sliding): 43.88 of the bound;
    • every sink at -inf (fold): 14.94 of the bound;
    • one q value a bf16 step up (prompt): its bytes differ from the fold's;
    • a window one key long (sliding): 76.92 of the bound;
    • the sink and gate given after their sigmoid, as Inkling 2 Mini on CUDA and Metal #4387's glue did (sliding): 10.33 of the bound;
    • alpha 0, so no tau (prep, global): an output outside its range;
    • rel_logits_proj read one column late (table): 103.06 of the bound;
    • stream 1's k and v written at stream 0's cache offset (prep): a slot no row writes is no longer 0.
  • Each backend's SUMMARY line and exit status (gfx1151, ROCm 10.1's hipcc, HIP 7.16):

    SUMMARY inkling2 HIP full: 13 kernels: 13 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 red as planted, 0 missed; 0 limit problems; gates 155893 ms, limits 4 ms (exit 0)

    zig build hip-kernel-contract-limits: every inkling2 record PASS on all four chips. The step exits 1 with 11
    problems, the same 11 as on main 5c1fea6 with this hipcc (14951bc changes no HIP record, kernel or
    zig/build/hip.zig), 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.zig), VGPRs on gfx1030 / gfx1100 / gfx1151 / gfx1201; no scratch on any chip:

    Launch Threads VGPRs LDS bytes
    tf_ink2_prep 32 20 / 20 / 20 / 19 0
    tf_ink2_rel_table 256 49 / 54 / 54 / 54 0
    tf_ink2_attn 128 101 / 101 / 101 / 101 35,072
    tf_ink2_attn_fold 128 109 / 109 / 109 / 108 35,072
    tf_ink2_attn_prompt 256 88 / 88 / 88 / 88 37,120
    tf_ink2_merge 128 18 / 18 / 18 / 15 0
  • Chips I could not run: gfx1030, gfx1100 and gfx1201 (limits only), and every CUDA SM.

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

AbrahamCete and others added 8 commits November 24, 2026 05:38
Move ashhart#4125's float64 attention reference from zig/tests/cuda into
core.contract.inkling2_attn_ref so the HIP contract can hold its kernels
to the same rounding points. A Call now names its query heads, key heads
and fp32 chains (Chain.cuda by default, Chain.hip for scalar IEEE sums),
and tauAt takes the model's n_floor (Mini's is 8,192).

CUDA's defaults are unchanged: the CUDA tests only change their import,
and a pinned test holds row() at CUDA's defaults to the bits the old
reference gave (checked bit for bit against it on sliding and global
rows before the move).

Checks: zig test of core.contract (17 pass); zig build
test-inkling2-cuda-host (10/10) and compile-cuda-tests on the tree.
A new inkling2 kernel group (strict IEEE build) with ashhart#4125's rounding
points on HIP: tf_ink2_prep (q/k L2 clips, tau on global layers, the
gamma-free v norm, k and v into each segment's ring), tf_ink2_rel_table,
chunked attention for sliding (tf_ink2_attn) and global layers
(tf_ink2_attn_fold, a split form a block a 1,024-key sub-chunk, and
tf_ink2_attn_prompt), and the ordered merge that takes the sink and the
gate raw. One wave holds a (row, head) pair over 64-key K/V tiles in
LDS with scalar fp32 sums; every path runs the same per-pair steps, so
split and prompt are bit-equal to the fold. The prompt kernel shares
each tile among 8 pairs in one 37 KiB LDS stage while the next tile
loads into registers. The kernels build for gfx1030, gfx1100, gfx1151
and gfx1201 (no scratch; records in hip_records_inkling2.zig).

The launcher (families/inkling2/hip_attention.zig) keeps heads, key
heads, floor and clips as runtime arguments and per-segment cache
offsets, as ashhart#4125's; whole-stream rings versus 64-position pages for
global KV stays open with the maintainer.

The contract entry (tf-hip-kernel-contract image inkling2) holds them
at Mini's 24/8 heads and n_floor 8,192 to core.contract's FP64
reference with HIP's chains, at served shapes to 1M keys on a ring that
wraps; three streams in one launch are bit-equal to each stream alone
(prep, sliding, fold, split). Eight controls go red at shapes, among
them a window one key long, the sink and gate given after their sigmoid
(ashhart#4387's glue) and a prep writing one stream's keys into another's.

Checks on gfx1151 with ROCm 10.1's hipcc: image inkling2 smoke and full,
11 kernels pass gates 1-4, 8 controls red, 0 limit problems;
hip-kernel-contract-limits passes all 24 inkling2 records (its 11
remaining problems are other groups' records); test-inkling2-hip-host,
check-hip-kernel-contract-host; lean 165 on base and head, 0 new.
The verifier's pins for core.contract.inkling2_attn_ref at CUDA's
defaults: keys past the bias extent, a full sliding window, the exact
(gate 4) branch, a NaN q and a +inf sink, gate 4's replay in fp32 and
bf16, and tau at Small's floor. The bits come from the base file
(5c1fea6:zig/tests/cuda/contract_inkling2_attn_ref.zig).

Checks: zig test of core.contract, 18 pass.
The verifier's edge cases for the HIP contract: global (fold) rows at
positions 0 to 1,024 held to float64 rather than only bit-compared, a
lone sliding row at 0, prep at pos + 1 = 8,193 and 8,194 just past
Mini's floor, and a NaN sink and a NaN gate planted beside gate 1's
infinities.
attend() now refuses a layer whose ring is not whole 64-key tiles
(error.Inkling2RingTiles: a tile's load never wraps), or is shorter
than its window plus the call's rows less one (error.Inkling2RingShort:
the rows' new keys would overwrite keys an earlier row still reads),
before any launch. The contract's rings (3,072 sliding, 4,096 global)
and Layer.sliding/global already meet both.

Checks: test-inkling2-hip-host 8/8 (two new tests, red before the
check), check-hip-kernel-contract-host.
The float64 bound allows P's bf16 rounding either way, so a kernel
that kept P unrounded stayed green. Two registrations (sliding, fold)
now make every output exact: rows below position 64 (one tile), q 0,
no sink, a gate whose sigmoid is 1, integer values in [-16, 16], bias
2 at distance 0 and the rest drawn so each bf16(exp2f) sits over 2^-21
from a tie. Every P is then at least 2^-5, both of its sums are exact
in fp32, and each output must equal bf16(fp32(sum P v / sum P)) bit for
bit. A host test shows an unrounded P moves 19,232 of 49,152 outputs.

docs/kernel-contract.md states the cases and the ring refusals, and
gives the prompt kernel's LDS as 37,120 bytes (36.25 KiB).

Checks on gfx1151: image inkling2 full, 13 kernels pass gates 1-4, 8
controls red, 0 limit problems. With the verifier's m1_p_unrounded
mutation, smoke goes red on exactly these two cases (11 of 13 pass).
test-inkling2-hip-host, check-hip-kernel-contract-host,
test-inkling2-cuda-host, compile-cuda-tests; lean 165, 0 new.
… stated

Rows.streams has no default any more: a caller states how many
segments `segs` holds, so a multi-stream call that forgets it no
longer compiles into the one-stream prompt kernel, which reads only
segs[0] and ignores the tiles. A call with no streams is refused
(error.Inkling2Streams). `slots` is now the partials the buffers hold,
and attend() refuses fewer than rows x heads x stride before any launch
(error.Inkling2PartialRoom); a split still needs 16 times that. The
contract's calls pass their real room, so their paths are unchanged.

A global position past the ring is not refused: the contract's
4,096-slot ring over 1M keys wraps on purpose. Layer.global and the
contract docs say the engine glue keeps a global layer's positions
inside its ring.

Checks: test-inkling2-hip-host 11/11 (two new tests, red before the
change); test-inkling2-cuda-host and compile-cuda-tests; on gfx1151,
image inkling2 full: 13 kernels pass gates 1-4, 8 controls red, 0 limit
problems. Lean 165 on base and head, 0 new.
@ashhart
ashhart force-pushed the perf/hip-inkling2-attention branch from f3f9d4d to 713d33b Compare November 24, 2026 05:38
@ashhart
ashhart merged commit ef4dd75 into ashhart:main Nov 24, 2026
1 check failed
@ashhart

ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Thank you @AbrahamCete. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

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