Skip to content

feat(hip): Inkling 2 Mini's routed experts under the kernel contract, bit-equal to loop_model - #4994

Draft
AbrahamCete wants to merge 6 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-experts
Draft

AbrahamCete wants to merge 6 commits into
ashhart:mainfrom
AbrahamCete:perf/hip-inkling2-experts

Conversation

@AbrahamCete

@AbrahamCete AbrahamCete commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

TensorFold has no HIP kernels for Inkling 2's routed experts. This adds them as a new inkling2_experts HIP kernel
group: gate/up over w13 with the softcapped SwiGLU (tf_ink2_nvfp4_gu, tf_ink2_mxfp8_gu), down over w2
(tf_ink2_nvfp4_down, tf_ink2_mxfp8_down) and the combine (tf_ink2_combine), with their launcher and a
kernel-contract entry at Mini's shapes. It is HIP3 of the HIP column on #4274 (issuecomment-7123193251), started after
ashhart's go (issuecomment-7132785932). Kernels only: no engine, router, glue or loop.

The go asks for this, verbatim:

Keep the checkpoint's stored formats (NVFP4 and MXFP8 decoded in registers, FP32 sums) and the same rounding points as
the CUDA and Metal paths. Every output bit should match the serial reference; we don't accept tolerances or
lower-precision shortcuts, even behind a switch.

So every registration compares each output's bits with families/inkling2/loop_model.zig. No float64 bound is used.

Arithmetic, as loop_model.zig has it:

  • NVFP4 weights decode as bf16(E2M1 * E4M3 * (bf16(amax) / bf16(denominator))), one fp32 division for the outer
    factor. The low nibble is the even input.
  • MXFP8 weights decode as bf16(E4M3 * 2^(scale - 127)) through ldexp. Scale 255 is 2^128 (code 0x30 gives 2^127),
    as in the reference and Metal, not the infinity of CUDA's e8m0(255).
  • Every dot is one fp32 chain in input order from zero, with contraction off, rounded once to bf16: 2,304 inputs for
    gate/up, 1,152 for down. No activation is quantized.
  • w13 interleaves the gate on row 2j and the up on row 2j + 1. The activation is
    bf16(softcap4(g) * sigmoid(g) * softcap25(u)) on the bf16 g and u, left to right in fp32.
  • The 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.
  • A NaN output is 0x7fc0. An id past the 128 experts gives a NaN row (gate/up, down) and never reads past the weights;
    the combine skips it.

The activation's tanh and exp. The reference evaluates the 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: 3,162 of the 131,072 factor values
below differ. So experts.hpp ports Zig 0.17's f32 tanh, expm1, exp and ldexp operation for operation, with each
constant's exact bits. tf_ink2_act_factors writes both factors, softcap4(g) * sigmoid(g) and softcap25(u), at all
65,536 bf16 inputs, and the contract holds all 131,072 values to Zig's bits (NaN as a class). A host test shows that
loop_model's expertActivation is one fp32 product of those two factors rounded once to bf16, over all 65,536 g by 64
u and the reverse, so the factors' bits fix every activation output. On the host, Zig's @exp equals the compiler-rt
port on all 2^32 f32 inputs, with and without libc.

Design.

  • A gate/up or down block has 256 threads and holds 64 outputs of one expert. It serves up to eight of that expert's
    routes in a launch, so a weight decoded once serves every token routed to it. The block of an expert's first route
    does the work; the blocks of its other routes find that earlier id and return.
  • Each 64-input tile of the block's rows is loaded with 16-byte loads, two tiles in flight, and decoded once into bf16
    in LDS by all 256 threads. The loads are unconditional and the barriers fence LDS only, so the next tiles' loads stay
    in flight while a tile's chains run. NVFP4 decodes through a per-expert table of all 256 E4M3 scale codes times the 8 E2M1
    magnitudes, built with the formula above; the sign flips the bf16 bits, because (-a) * b * phi is -(a * b * phi)
    exactly. MXFP8 decodes through a table of the 256 E4M3 values and the same ldexp.
  • Each output's chain then runs from LDS, acc = acc + w * x in input order, the gate's and up's chains interleaved.
    The tiles change where the weights come from, not the order or the rounding of any sum.
  • The decode loops index their registers with constants only, so no kernel uses scratch.
  • The combine runs one thread an output, 64 a block.
  • The group builds with the strict flags (-O2 -fno-fast-math -fdenormal-fp-math=ieee, -ffp-contract=off). It builds
    for gfx1030, gfx1100, gfx1151 and gfx1201 with no chip-specific path.
  • The launcher imports only hip. It refuses, before any launch, a reduction past 2,304 inputs or not made of whole
    scale groups, codes not aligned for their loads (8 bytes NVFP4, 16 bytes MXFP8), an NVFP4 call without amax or
    denominator, a call with no rows or outputs, a combine with no slots or more than 16, and more than 65,535 routes.

Speed, measured on gfx1151. I used a small harness that loads this group's code object, as the build makes it, and
launches it at Mini's shapes. Every route got a different expert, and the ids rotated over all 128 experts between
launches, so the weights were not cached. Times are rocprofv3 kernel-trace medians over 60 launches. The 64768ff and
head columns come from one run with the two code objects alternated twice; the first version's from an earlier run of
the same harness. Bytes are packed weights plus scales plus activations and outputs. The machine's read bandwidth is
240 GB/s, measured with a 1 GiB read kernel (median of 20); the stated peak is 256 GB/s (LPDDR5X-8000, 256 bits).
"First version" is this branch's fourth commit, which ran one thread an output, each thread reading and decoding its
own rows; 64768ff is the fifth.

Kernel Tokens First version, us 64768ff, us This head, us MB read GB/s Share of 240 GB/s
tf_ink2_nvfp4_gu 1 617.4 264.9 225.3 23.91 106 44%
tf_ink2_mxfp8_gu 1 660.0 259.8 241.9 43.82 181 75%
tf_ink2_nvfp4_down 1 328.2 138.4 104.4 12.00 115 48%
tf_ink2_mxfp8_down 1 209.3 132.3 126.9 21.95 173 72%
tf_ink2_combine 1 5.2 5.2 5.2 0.04 8.0 3%
tf_ink2_nvfp4_gu 4 4,629.8 887.5 728.5 95.64 131 55%
tf_ink2_mxfp8_gu 4 4,990.7 835.6 820.8 175.27 214 89%
tf_ink2_nvfp4_down 4 1,116.0 451.5 330.5 48.00 145 60%
tf_ink2_mxfp8_down 4 580.4 423.2 407.7 87.81 215 90%
tf_ink2_combine 4 6.2 6.2 6.2 0.17 26.6 11%
tf_ink2_nvfp4_gu 8 8,996.9 1,747 1,403 191.29 136 57%
tf_ink2_mxfp8_gu 8 9,321.8 1,644 1,595 350.54 220 92%
tf_ink2_nvfp4_down 8 2,094.9 860 631 95.99 152 63%
tf_ink2_mxfp8_down 8 1,069.3 810 782 175.62 225 94%
tf_ink2_combine 8 8.4 8.4 8.4 0.33 39.6 16%

The combine is the same kernel in all three columns.

When the tokens share their experts (all of them on the same eight), each decoded weight serves every token: at 8 tokens
on 64768ff, tf_ink2_nvfp4_gu takes 441.7 us and tf_ink2_mxfp8_gu 435.9 us, for 24.07 and 43.98 MB.

One decode token's routed experts take 334.9 us on an NVFP4 layer and 374.0 us on an MXFP8 one. A token runs 48 layer
visits (layers 6-17 run three times; NVFP4 on 44 of them, MXFP8 on 4), which comes to 16.2 ms. The llama.cpp Vulkan
baseline on this machine (21.9 tok/s, IQ4_NL, posted on #4274) leaves 45.7 ms for the whole token, so the routed experts
take 36% of it. At 240 GB/s their bytes would take 7.7 ms; this is 2.1x that.

Questions for you; say which you want changed:

  1. NVFP4 still trails MXFP8: 44-48% of the bandwidth at one token and 55-63% at 4 and 8 tokens, against 72-75% and
    89-94%. Keeping two tiles in flight (the last commit) raised NVFP4 from 37% at one token. A 128-input NVFP4 down
    tile is 13% faster at one token but level at 8, and on gate/up it needs 129 VGPRs, so I left it out. I have not
    found the rest yet.
  2. Reduction order. These kernels keep loop_model's one chain an output in input order. If that order ever stops a
    kernel from reaching the bandwidth, would you accept an order the reference defines and every backend follows, such
    as 32 lane-strided fp32 chains joined by a fixed tree, or one partial sum a scale group? Every output would still
    equal the serial reference bit for bit. And does CUDA's mma path give loop_model's bits today, since the mma does
    not sum in input order?
  3. A launch groups its routes by expert by having each block scan the ids before its route. That is cheap at decode and
    at the contract's 64-token rows, but grows with the square of the routes. Long prompts would want a grouping plan
    built once a layer; should that come with the engine slice?
  4. tf_ink2_act_factors exists only for the contract's proof, and its native launch flag (the device's tanhf and
    expf) only for the control. It ships in the inkling2_experts image. Would you rather have it in the controls' code
    object (contract_controls.hip)?
  5. Duplicate ids in the combine. combineExperts refuses a token whose ids repeat; the kernel sums both terms, as
    Metal's combine does. No test covers it. Should the kernel write NaN instead, or is the router's top-k enough?
  6. The hipcc version. The records come from ROCm 10.1's hipcc (HIP 7.16), the compiler whose usage the existing records
    hold. The Ubuntu hipcc (HIP 7.1, clang 21) does not build here, because the build derives a device-library path
    that package does not have. With HIP 7.16, 11 records in other groups are stale on main as well (below).

Checks on this head

  • Head commit: 262b048, on main 3795e60.
  • 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 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-experts-hip-host test-inkling2-hip-host -Dhip=true: 22 of 22 passed (the launcher's
      grids and refusals on a mock runtime; the factor identity, the scale-255 decode, the stress rows' margins and the
      combine order on the host; the attention plan).
    • zig build test on a clean tree of this head: 13,493 of 13,587 passed, 93 skipped, 1 failed. The failure is
      stage_hip_test "every staged call on HIP memory equals the reference, whole and in parts", which fails on main
      3795e60 as well (13,492 of 13,586 there).
    • zig build test -Dhip=true on the same tree: 1,504 of the 1,526 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 main and this head on gfx1151: 619 kernels identical, the 6 new ones added, no
      spill and no scratch in any of them. Four affine_dot2_block<DotBF16, N> kernels in tiles/dot2.hip differ (N = 2,
      3, 5 and 6), which this branch does not touch; two builds of main alone differ in four of the same kernels
      (N = 2, 3, 5 and 6).
  • The new tests fail before their change:
    • the factor registration, run on the device's tanhf and expf before the port: 3162 of 131072 factors differ; first the gate factor at bf16 0x33b2: 0x33320001 where Zig gives 0x33320000;
    • the launcher's host tests before gateUp, down and combine existed: three compile errors; before the
      256-thread launch, its two grid tests expected 256-thread blocks and found 64;
    • the gate/up, down and combine registrations before their kernels: the image stopped with HipFailed, because
      tf_ink2_nvfp4_gu was not in the code object.
    • The four distinct-expert cells were added before the tiled kernels and passed on the one-thread-an-output kernels,
      so the tiled kernels were held to the same bits from the start.
  • 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.

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_experts); none replaces another kernel.
    Each output's bits are compared with loop_model's at gates 1 and 3:

    • tf_ink2_act_factors: all 65,536 bf16 inputs, both factors, Zig's bits.
    • tf_ink2_nvfp4_gu (ids 0-7) and tf_ink2_mxfp8_gu (ids 120-127): 1, 4, 16 and 64 tokens on eight experts, so
      every expert serves several tokens, with edges at 1, 63, 64 and 65 outputs and 32 and 64 inputs; 10 shapes each.
    • tf_ink2_nvfp4_down (ids 0-7) and tf_ink2_mxfp8_down (ids 120-127): the same rows and edges; 10 shapes each.
    • Four cells, one for each projection kernel, at 4 and 8 tokens whose 32 and 64 routes each read their own expert.
    • Two one-hot down cells cover every MXFP8 (code, scale) pair and every NVFP4 (code, scale) pair, both nibbles, at
      eight amax values (73,728 rows each, NaN and infinite weights included).
    • tf_ink2_combine: 1, 16 and 2,048 tokens, with the output edges; 7 shapes.
    • The MXFP8 cells reach Mini's last experts through a weight base that many experts early.
    • Gate 1 plants NaN and both infinities in the inputs, an id past the experts, a NaN code (MXFP8), an infinite amax
      (NVFP4) and, for the combine, an infinite weight and ids of 200 and -1.
    • Gate 4's rows: 128 terms of 1.5 * 2^16 * (1 + 2^-7), 129 of -1.5 * 2^16 and a +1 alone in its scale group. They
      sum exactly in fp32 in any order; fp16 sums are not finite and bf16 sums miss by 256x (gate/up, after the
      activation) and 2,621,184x (down). The combine's terms by ascending id are 2^20, 3, 5, 7, 9, 11, -2^20 and 1;
      bf16 misses by 249x.
  • A planted control for each new kernel, each one red at shapes through the device's inputs or launch only:

    • the factors through the device's own tanhf and expf: 3,162 of 131,072 differ;
    • NVFP4 gate/up given w13 as gate rows then up rows, not interleaved;
    • MXFP8 gate/up with one input a bf16 step up;
    • NVFP4 down reading each row's scales one group late;
    • the combine given its fp32 route weights rounded to bf16.
  • Each backend's SUMMARY line and exit status (gfx1151, ROCm 10.1's hipcc, HIP 7.16):

    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 11718 ms, limits 5 ms (exit 0)

    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 10338 ms, limits 4 ms (exit 0)

    image inkling2, the attention, which this branch does not touch, run at 64768ff (smoke; the last commit changes only experts.hip and its records): 13 kernels: 13 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 red as planted, 0 missed (exit 0).

    zig build hip-kernel-contract-limits: all 24 inkling2_experts records PASS on the four chips. The step exits 1
    with 11 problems, the same 11 as 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_experts.zig), VGPRs on gfx1030 / gfx1100 / gfx1151 / gfx1201; no scratch on any chip:

    Launch Threads VGPRs LDS bytes
    tf_ink2_nvfp4_gu 256 92 / 90 / 89 / 89 25,096
    tf_ink2_mxfp8_gu 256 91 / 87 / 86 / 86 25,096
    tf_ink2_nvfp4_down 256 74 / 72 / 72 / 72 16,648
    tf_ink2_mxfp8_down 256 73 / 69 / 69 / 69 16,648
    tf_ink2_combine 64 7 / 7 / 7 / 7 0
    tf_ink2_act_factors 256 17 / 17 / 17 / 17 0
  • 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.
  • 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.

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