gemma4k, arch/gemma4: norm_add_norm_route -- the attention join writes the routed arm's inputs

The 26B-A4B's router reads rmsnorm(x) * w_r * hidden^-0.5 and its experts rmsnorm(x) * w_e,
quantised to E4M3 for the fp8 gate_up: an `rmsnorm` and an `rmsnorm_quant_fp8` a layer, each
reading back the x norm_add_norm has just written and taking the sum of squares it has just taken.
At decode that is 60 launches a step (8.3 and 7.8 us under --profile-ops on 4x R9700); at a
prefill, eleven passes of each a layer per 20K-token request.

norm_add_norm_route is norm_add_norm, then from the norm factor it already holds the router's row
by rmsnorm's expression, ((x * s) * w_r) * mult, and the experts' codes as rmsnorm_quant_fp8 writes
them: the bf16-rounded norm, a scale of amax * (1 / 448) a 128 columns (1 for an all-zero group),
the value times its reciprocal clamped to +-448, one v_cvt_pk_fp8_f32. Element i is thread i % 256
at slot i / 256, so a group is four waves at one slot -- a wave's max, then the four through LDS.
Its own name rather than optional operands on norm_add_norm: the codes need whole 128-column
groups, which the plain join does not, and the arch falls back cleanly where it does not resolve.
A device row and a host arm (one helper with norm_add_norm's), the schema, OPS.md.

arch/gemma4 asks for it on every layer whose gate_up is block fp8 -- the user's fp8gu container,
every layer -- and then issues neither op_rnorm nor op_enorm; it declares both still, and
norm_add_norm and the chain behind it, for where it does not resolve. The routed arm's two norm
gains are declared ahead of the attention join now, which names them. The overlap takes either
join. A startup note counts the layers that take it.

The same rounding as the chain, but for the order a sum of squares is added in, as every join here:
g4k_emu holds the kernel to a chain summed in its block order bit for bit -- x, y, the router's
row, every code and scale -- at the 26B-A4B's 2816 at four heights, at 128, 3072, 3200 and 6144,
and with an all-zero group; against the host arm, no code more than a step off. The emulator gains
v_cvt_pk_fp8_f32, through the project's saturating encoder. arch_test: with fp8 gate_up experts the
route op resolves on all six layers, a decode step issues it and no rmsnorm_quant_fp8 and one
rmsnorm fewer a layer; refused, norm_add_norm and both launches; a tp-4 prefill through the
overlap issues it a slice and keeps every reduction ordered.

Not yet run on the cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
AshlynandClaude Opus 5.5 committed 2026-10-12 14:40:04 -05:00
1 parent efff69be1d
commit 7a1ae22690
11 files changed
+449 -43

No files matched your search

+60
View File
@@ -4058,3 +4058,63 @@ TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second
CHECK(c.joins.empty());
for (const auto& i : c.issues) CHECK_EQ(i.lane, 0);
}
/* THE ATTENTION JOIN WRITES THE ROUTED ARM'S INPUTS on a layer whose gate_up is block fp8
* (gemma4k norm_add_norm_route): the router's norm into moe_rn and the experts' codes into
* moe_hq / moe_hqs, so a step issues neither the router's rmsnorm nor rmsnorm_quant_fp8. Refused,
* norm_add_norm and the two launches. A tp-4 prefill through the overlap keeps every reduction
* ordered with the route form too. */
TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) {
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
std::map<std::string, int> issued[2];
for (int refuse = 0; refuse < 2; ++refuse) {
RadBuilder b;
b.encs = { { "ffn_gate_up_exps", fp8 } };
if (refuse) b.refuse.insert("norm_add_norm_route");
RadModelMeta meta = gemma4_moe_meta();
RadBuildCtx ctx = build_ctx();
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
CHECK_EQ(count_resolved(b, "norm_add_norm_route"), refuse ? 0 : 6);
CHECK_EQ(count_resolved(b, "norm_add_norm"), refuse ? 6 : 0);
CHECK(noted(b, refuse ? "routed inputs: 0 of 6" : "routed inputs: 6 of 6"));
if (!refuse) {
const RecOp* r = find_op(b, "norm_add_norm_route");
REQUIRE(r != nullptr);
for (const char* name : { "moe_rn", "moe_hq", "moe_hqs", "x", "h" })
CHECK(std::count(r->writes.begin(), r->writes.end(),
(rad_buf)buf_named(b, name)) == 1);
}
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
RadBatch batch = decode_batch();
c.batch = &batch;
gemma4::step(&c, &batch);
CHECK(c.step_fail.empty());
for (const auto& n : issued_ops(b, c)) ++issued[refuse][n];
}
CHECK_EQ(issued[0]["norm_add_norm_route"], 6);
CHECK_EQ(issued[0]["norm_add_norm"], 0);
CHECK_EQ(issued[0]["rmsnorm_quant_fp8"], 0);
CHECK_EQ(issued[1]["norm_add_norm_route"], 0);
CHECK_EQ(issued[1]["norm_add_norm"], 6);
CHECK_EQ(issued[1]["rmsnorm_quant_fp8"], 6);
CHECK_EQ(issued[1]["rmsnorm"] - issued[0]["rmsnorm"], 6); /* the router's input norm */
CHECK_EQ(issued[0]["moe_gemm_q"], 6);
/* tp 4, an 8192-token chunk in two slices */
RadBuilder b;
b.encs = { { "ffn_gate_up_exps", fp8 } };
RadModelMeta meta = gemma4_moe_meta();
RadBuildCtx ctx = build_ctx(0, 4);
ctx.max_tok = 8192;
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
CHECK(noted(b, "prefill overlap: a chunk of two routed passes"));
const int32_t out[1] = { 8191 };
RadBatch batch = one_prompt(8192, out);
RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &batch;
gemma4::step(&c, &batch);
CHECK(c.step_fail.empty());
CHECK_EQ(races(b, c), 0);
CHECK_EQ(count_issued(issued_ops(b, c), "norm_add_norm_route"), 12);
CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0);
}
+6
View File
@@ -1,4 +1,5 @@
#include "hip/hip_runtime.h"
#include "rad_plugin.h"
#include <cstdio>
#include <cstdlib>
@@ -102,6 +103,11 @@ int emu_bpermute(int addr, int v) {
return S.slot[w][par][(addr >> 2) & 31];
}
int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); }
int emu_cvt_pk_fp8(float a, float b, int old, bool hi) {
const unsigned pk = (unsigned)rad_f32_to_fp8e4m3(a) | ((unsigned)rad_f32_to_fp8e4m3(b) << 8);
const unsigned o = (unsigned)old;
return (int)(hi ? ((o & 0xffffu) | (pk << 16)) : ((o & 0xffff0000u) | pk));
}
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
+5
View File
@@ -45,6 +45,11 @@ emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): a and b as two codes into the low half of `old` (hi false)
* or its high half, the other half kept; round to nearest even. The project's saturating encoder,
* rad_f32_to_fp8e4m3, is the same function on the +-448 a kernel clamps to first. */
int emu_cvt_pk_fp8(float a, float b, int old, bool hi);
#define __builtin_amdgcn_cvt_pk_fp8_f32(a, b, old, hi) emu_cvt_pk_fp8((a), (b), (old), (hi))
extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */
struct alignas(8) uint2 { unsigned x, y; };
+89 -1
View File
@@ -6,7 +6,9 @@
* BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in
* index order -- what a different libr4d block width does too -- and may differ by a flipped
* rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be
* left alone. */
* left alone. The route form's chain adds the router's rmsnorm (with its mult) and libr4d's
* rmsnorm_quant_fp8 of the experts' norm -- amax * (1 / 448) a group, the clamped value encoded by
* the emulator's v_cvt_pk_fp8_f32, the saturating encoder every fp8 cast here uses. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "g4k.h"
@@ -135,6 +137,87 @@ static int case_nan(int M, int n, int pad, int extra_rows) {
return ok ? 0 : 1;
}
/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts'
* E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns,
* so that group's amax is 0 and its scale the quantiser's 1. */
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) {
const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3;
const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n);
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
auto r0 = randb((size_t)R * ld, 1.f);
auto wa = gains(n), wy = gains(n), wr = gains(n), we = gains(n);
if (zero_group && n >= 256) for (int i = 128; i < 256; ++i) we[(size_t)i] = 0.0f;
std::vector<uint8_t> q0((size_t)R * ldq);
std::vector<float> s0((size_t)R * lds);
for (auto& v : q0) v = (uint8_t)(rng() & 0xff);
for (auto& v : s0) v = -7.0f;
auto xd = x, yd = y0, rd = r0, xh = x, yh = y0, rh = r0;
auto qd = q0, qh = q0;
auto sd = s0, sh = s0;
RadTensor t[10] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n),
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
rows(yd.data(), RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n),
rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128};
RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6;
if (g4k_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data();
if (host_row("norm_add_norm_route")->launch(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; }
Tally tx, ty, tr;
long q_chain = 0, s_chain = 0, q_host_bad = 0, touched = 0;
for (int m = 0; m < R; ++m) {
const size_t o = (size_t)m * ld, oq = (size_t)m * ldq, os = (size_t)m * lds;
if (m >= M) {
for (int i = 0; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
for (int i = 0; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
for (int i = 0; i < lds; ++i) touched += sd[os + i] != s0[os + i];
continue;
}
for (int i = n; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
for (int i = n; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
for (int i = G; i < lds; ++i) touched += sd[os + i] != s0[os + i];
std::vector<float> av((size_t)n), xv((size_t)n);
for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]);
const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */
std::vector<uint16_t> cx((size_t)n), cy((size_t)n), cr((size_t)n);
for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */
const float f = block_factor(xv, n, eps);
for (int i = 0; i < n; ++i) {
cy[(size_t)i] = f2b((xv[(size_t)i] * f) * wy[(size_t)i]); /* rmsnorm */
cr[(size_t)i] = f2b(((xv[(size_t)i] * f) * wr[(size_t)i]) * mult); /* the router's */
}
cmp(&xd[o], cx.data(), &xh[o], n, tx);
cmp(&yd[o], cy.data(), &yh[o], n, ty);
cmp(&rd[o], cr.data(), &rh[o], n, tr);
for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */
float h[128], am = 0.0f;
for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); }
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc;
s_chain += sd[os + g] != sc;
if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain;
for (int j = 0; j < 128; ++j) {
const int i = g * 128 + j;
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
/* vs the host arm: one code step is an eighth of its value at most, which is no
* more than an eighth of the group's amax; a scale an ulp off moves less */
const double dv = std::fabs((double)rad_fp8e4m3_to_f32(qd[oq + i]) * sd[os + g] -
(double)rad_fp8e4m3_to_f32(qh[oq + i]) * sh[os + g]);
if (dv > (double)am / 8 + 1e-30) ++q_host_bad;
}
}
}
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 &&
tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0;
std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld,
zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain,
tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL");
return ok ? 0 : 1;
}
/* `next`: also the next layer's input norm, y = norm(x) * w_n over the x the join writes */
static int case_jas(int M, int n, int pad, int extra_rows, bool next = false) {
const int ld = n + pad, R = M + extra_rows;
@@ -200,6 +283,11 @@ int main() {
/* and with the next layer's input norm folded in */
for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true);
fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true);
/* the route form: the 26B-A4B's width at decode, verify and prefill heights, the edge between the
* 12- and 24-a-thread kernels, one group, the limit, and a group whose norm is all zero */
for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2);
fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1);
fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true);
std::printf("norm joins: %d failure(s)\n", fails);
return fails ? 1 : 0;
}