From 171dcee15b51d6c238f84f6605d46ff64cd4d98f Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 11 Oct 2026 13:30:32 -0500 Subject: [PATCH] gemma4k, arch/gemma4: the feed-forward join writes the next layer's input norm join_add_scale takes an optional gain `w_n` and output `y` (both or neither) and, given them, writes y = rmsnorm(x) * w_n over the residual it has just stored -- the next layer's input_layernorm, or the final norm after the last layer. Those norms read the x the join writes and nothing else, so each was a launch of its own and a second read of the row; now it is a fourth reduction in a block that already holds x in registers. On the 26B-A4B that is 30 launches a forward pass the fewer (29 input norms and the final norm), at decode a step's worth of ~8 us launches. Rounding where the chain rounds: y is taken over the bf16 x the join stores, with libr4d's expression, so g4k_emu holds it to the chain bit for bit (+next cases, decode to prefill heights, odd widths and pitches) and to the host arm within a flipped rounding. arch/gemma4 declares every layer's input-norm gain ahead of the layers so a join can name the next one's; where a join resolves, the norm it replaces is neither declared nor issued, and where it does not, the chain is as before. docs/OPS.md: the row and its paragraph. arch_test: fused, the only x -> h rmsnorm is layer 0's and every join writes h; refused, all thirteen come back. Not yet run on the cards. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4/gemma4.cpp | 42 +++++++++++++++++++++++++-------- docs/OPS.md | 6 +++-- gemma4k/g4k_norm.hip | 46 ++++++++++++++++++++++++++++++------- gemma4k/g4k_rows.cpp | 23 +++++++++++++++---- tests/arch_test.cpp | 36 +++++++++++++++++++++++++++++ tests/g4k_emu/test_norm.cpp | 42 ++++++++++++++++++++++----------- 6 files changed, 158 insertions(+), 37 deletions(-) diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 20d15d5c..68fe853c 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -234,6 +234,11 @@ struct Layer { * routed layer's fpost1 + fpost2 + fsum + fpost + add_f + scale. Zero where not served, and * then the chain above is declared and issued instead. */ rad_op op_join_a = 0, op_join_f = 0; + /* op_join_f also writes the NEXT norm -- the following layer's input norm, or the final norm + * after the last layer -- into `h`, with that norm's gain `w_next`; the norm it replaces is + * then neither declared nor issued. */ + bool next_norm = false; + rad_weight w_next = 0; /* the drafter's tap, on a layer the drafter reads (see declare) */ rad_op op_tap = 0; }; @@ -989,6 +994,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c int n_joins = 0; const int A = RAD_ACCESS_PER_TOKEN, N = RAD_SHARD_NONE; + /* EVERY LAYER'S INPUT NORM GAIN, AHEAD OF THE LAYERS: a feed-forward join writes the next + * layer's input norm (join_add_scale's `y`) and so names that layer's gain before the layer + * itself is declared. */ + for (int64_t l = 0; l < m.n_layer; ++l) { + const long long ll = (long long)l; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), + nm.ckpt("%s.layers.%lld.input_layernorm.weight", L, ll))); + m.layers[(size_t)l].w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, + {E}, A, N, grp_layer((int)l)); + } + for (int64_t l = 0; l < m.n_layer; ++l) { Layer& y = m.layers[(size_t)l]; y.full = full[(size_t)l]; @@ -1000,13 +1016,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(rad_bind_layer_kv(b, li, k.kv)); /* ------------------------------------------------ attention: weights */ - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_norm.weight", ll), src("input_layernorm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_q_norm.weight", ll), src("self_attn.q_norm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_k_norm.weight", ll), src("self_attn.k_norm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_output.weight", ll), src("self_attn.o_proj.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.attn_post_norm.weight", ll), src("post_attention_layernorm.weight"))); - y.w_anorm = decl_w(b, nm.f("blk.%lld.attn_norm.weight", ll), RAD_F32, {E}, A, N, gl); /* bf16 gains: `qk_norm_rope` reads its gains at the activation's width. */ y.w_qn = decl_w(b, nm.f("blk.%lld.attn_q_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); y.w_kn = decl_w(b, nm.f("blk.%lld.attn_k_norm.weight", ll), RAD_BF16, {k.hd}, A, N, gl); @@ -1049,7 +1063,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ------------------------------------------------ attention: ops, in issue order (the * attention op is declared ahead of its kv_store, which reads the block size off it). */ - y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); + if (!(l > 0 && m.layers[(size_t)l - 1].next_norm)) + y.op_anorm = rmsnorm(T, E, y.w_anorm, 1.0, m.b_x, m.b_h); if (!y.full) { y.op_qkv = gemm(T, k.q() + 2 * k.kv_dim(), E, y.w_qkv, m.b_h, m.b_qkv); y.op_qknr = rw(b, RAD_OP(b, "qk_norm_rope", @@ -1294,11 +1309,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (!y.op_enorm || !y.op_egu || !y.op_edn || (y.dn_fp8 && !y.op_eq)) return RAD_E_INVAL; if (W > 1) y.op_ar_f = allreduce(2 * T * E, m.b_ff2); if (fuse_joins) + { + /* ...and the norm that reads the x it writes: the next layer's input norm, or the + * final norm after the last layer -- one launch and one read of x the less. */ + const rad_weight w_next = l + 1 < m.n_layer ? m.layers[(size_t)l + 1].w_anorm + : m.w_onorm; y.op_join_f = rw(b, RAD_OP(b, "join_add_scale", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar)), - {m.b_ff2, m.b_x}, {m.b_x}); + RAD_WEIGHTS(y.w_fpost1, y.w_fpost2, y.w_fpost, y.w_scalar, + w_next)), + {m.b_ff2, m.b_x}, {m.b_x, m.b_h}); + if (y.op_join_f) { y.next_norm = true; y.w_next = w_next; } + } if (!y.op_join_f) { y.op_fpost1 = rmsnorm(T, E, y.w_fpost1, 1.0, m.b_ff2, m.b_ff2); y.op_fpost2 = rmsnorm(T, E, y.w_fpost2, 1.0, m.b_ff2, m.b_ff2); @@ -1335,7 +1358,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c {m.b_x}, {m.b_dfsrc}); } - m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); + if (m.layers.empty() || !m.layers.back().next_norm) + m.op_onorm = rmsnorm(T, E, m.w_onorm, 1.0, m.b_x, m.b_h); m.op_gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", E), RAD_STR("dtype", "bf16")), @@ -1514,7 +1538,7 @@ static void step(RadCtx* c, const RadBatch* batch) { const RadOperand bt = praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0); const RadOperand su = praw(used, RAD_I32, batch->n_seq); - RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); + if (y.op_anorm) RAD_ISSUE(c, y.op_anorm, brows(m.b_x, T), RAD_W(y.w_anorm), brows(m.b_h, T)); if (!y.full) { const int64_t qd = k.q(), kvd = k.kv_dim(); RAD_ISSUE(c, y.op_qkv, brows(m.b_h, T), RAD_W(y.w_qkv), brows(m.b_qkv, T)); @@ -1559,7 +1583,7 @@ static void step(RadCtx* c, const RadBatch* batch) { if (y.op_join_f) { RAD_ISSUE(c, y.op_join_f, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), RAD_W(y.w_fpost), - brows(m.b_x, T), RAD_W(y.w_scalar)); + brows(m.b_x, T), RAD_W(y.w_scalar), RAD_W(y.w_next), brows(m.b_h, T)); } else { RAD_ISSUE(c, y.op_fpost1, brows(m.b_ff2, T), RAD_W(y.w_fpost1), brows(m.b_ff2, T)); RAD_ISSUE(c, y.op_fpost2, brow_slice(m.b_ff2, T, T, E), RAD_W(y.w_fpost2), @@ -1585,7 +1609,7 @@ static void step(RadCtx* c, const RadBatch* batch) { } } - RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); + if (m.op_onorm) RAD_ISSUE(c, m.op_onorm, brows(m.b_x, T), RAD_W(m.w_onorm), brows(m.b_h, T)); if (batch->n_out > 0) { RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T), praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); diff --git a/docs/OPS.md b/docs/OPS.md index cbb4451d..08359947 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -299,13 +299,15 @@ rounding. | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | -| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w | +| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? | Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add` and `mul_weight`. `norm_add_norm` is `t = rmsnorm(a) * w_a; x += t; y = rmsnorm(x) * w_y` -- a post-norm, the residual add, the next pre-norm. `join_add_scale` is `x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s` -- two arms' post-norms, their sum, its norm, the residual add and a -one-element layer scalar (Gemma 4's MoE feed-forward). Every value the chain stores is rounded to +one-element layer scalar (Gemma 4's MoE feed-forward) -- and, given `w_n` and `y` (both or +neither), `y = rmsnorm(x) * w_n` over the `x` it writes: the next layer's input norm, or the final +norm after the last layer, which would otherwise be a launch of its own reading that `x` back. Every value the chain stores is rounded to the activation dtype at the same point, so the two differ from the chain only in the order a sum of squares is added in: with the same order they are bit-identical to it, and against a chain summed in another block width a norm factor can differ in its last bit. diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip index dea63fd4..a84fde2a 100644 --- a/gemma4k/g4k_norm.hip +++ b/gemma4k/g4k_norm.hip @@ -7,9 +7,10 @@ * norm_add_norm the attention's join: t = norm(a) * w_a; x += t; y = norm(x) * w_y * (post_attention_layernorm, the residual add, pre_feedforward_layernorm) * join_add_scale the feed-forward's: d' = norm(d) * w_d; r' = norm(r) * w_r; - * j = norm(d' + r') * w_j; x = (x + j) * s + * j = norm(d' + r') * w_j; x = (x + j) * s; and optionally y = norm(x) * w_n * (post_feedforward_layernorm_1 and _2, the arms' sum, post_feedforward_layernorm, - * the residual add, layer_scalar) + * the residual add, layer_scalar -- and the NEXT layer's input_layernorm, or the + * final norm after the last layer, which read the x this writes) * * THE SAME FUNCTION AS THE CHAIN, ROUNDING FOR ROUNDING. Every value the chain stores as bf16 is * rounded to bf16 here at the same point, and every element is computed with libr4d's own @@ -74,6 +75,7 @@ struct NormArgs { const float* w0; /* w_a, or w_d */ const float* w1; /* w_y, or w_r */ const float* w2; /* w_j */ + const float* w3; /* w_n, the next norm's gain (or null) */ const uint16_t* s; /* the layer scalar, bf16, one element */ int n; float eps; @@ -118,7 +120,9 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { } } -/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s */ +/* x = (x + norm(norm(d) * w_d + norm(r) * w_r) * w_j) * s, and with NEXT y = norm(x) * w_n: the + * next layer's input norm taken over the bf16 x this stores, which is what that norm would read. */ +template __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { __shared__ float lds[kWaves]; const int tid = (int)threadIdx.x, n = A.n; @@ -155,13 +159,28 @@ __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { } const float sj = norm_factor(block_sum(ss, lds), n, A.eps); const float sc = bf2f(*A.s); + ss = 0.0f; #pragma unroll for (int k = 0; k < kMaxPer; ++k) { const int i = tid + k * kThreads; if (i < n) { const float j = rbf((dv[k] * sj) * A.w2[i]); const float x1 = rbf(bf2f(xr[i]) + j); - xr[i] = f2bf(x1 * sc); + const uint16_t xn = f2bf(x1 * sc); + xr[i] = xn; + rv[k] = bf2f(xn); /* the new x, kept for the next norm */ + } else { + rv[k] = 0.0f; + } + if (NEXT) ss += rv[k] * rv[k]; + } + if (NEXT) { + const float sn = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* yr = A.y + m * A.y_ld; +#pragma unroll + for (int k = 0; k < kMaxPer; ++k) { + const int i = tid + k * kThreads; + if (i < n) yr[i] = f2bf((rv[k] * sn) * A.w3[i]); } } } @@ -219,7 +238,7 @@ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } -/* operands: d, w_d, r, w_r, w_j, x (inout), s */ +/* operands: d, w_d, r, w_r, w_j, x (inout), s, w_n?, y? -- the last two both or neither */ int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { using namespace g4kn; if (!a || a->n_t < 7) return RAD_E_INVAL; @@ -232,20 +251,31 @@ int g4k_join_add_scale_bf16(const RadArgs* a, RadStream stream) { if (!D || !R || !X || !Sc) return RAD_E_INVAL; if (!gain(Wd, n) || !gain(Wr, n) || !gain(Wj, n)) return RAD_E_DTYPE; if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; - int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0; + const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr, + *Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr; + if (!Wn != !Y) return RAD_E_INVAL; + if (Wn && !gain(Wn, n)) return RAD_E_DTYPE; + int64_t rd = 0, ld = 0, rr = 0, lr = 0, rx = 0, lx = 0, ry = 0, ly = 0; if (!rows_of(D, n, &rd, &ld) || !rows_of(R, n, &rr, &lr) || !rows_of(X, n, &rx, &lx)) return RAD_E_SHAPE; + if (Y && !rows_of(Y, n, &ry, &ly)) return RAD_E_SHAPE; const int64_t M = rx; /* the step's rows: the stream's view */ if (M <= 0) return RAD_OK; - if (rd < M || rr < M || M > 0x7fffffff) return RAD_E_SHAPE; + if (rd < M || rr < M || (Y && ry < M) || M > 0x7fffffff) return RAD_E_SHAPE; NormArgs P{}; P.d = (const uint16_t*)D->data; P.d_ld = ld; P.r = (const uint16_t*)R->data; P.r_ld = lr; P.x = (uint16_t*)X->data; P.x_ld = lx; P.w0 = (const float*)Wd->data; P.w1 = (const float*)Wr->data; P.w2 = (const float*)Wj->data; P.s = (const uint16_t*)Sc->data; + if (Y) { P.w3 = (const float*)Wn->data; P.y = (uint16_t*)Y->data; P.y_ld = ly; } P.n = (int)n; P.eps = eps; - G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + if (Y) + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); + else + G4K_LAUNCH(G4K_KNAME(join_add_scale_kernel), dim3((unsigned)M), dim3(kThreads), + (hipStream_t)stream, P); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } diff --git a/gemma4k/g4k_rows.cpp b/gemma4k/g4k_rows.cpp index 7376d9e6..4bfd8eca 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -82,6 +82,8 @@ static const RadOperandSpec oJas[] = { { "w_j", RAD_OPD_WEIGHT, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, + { "w_n", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 1 }, }; static const RadOpSchema kSchemas[] = { { "pair_argmax", ROW(pPick), ROW(oPick), @@ -95,8 +97,9 @@ static const RadOpSchema kSchemas[] = { "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, { "join_add_scale", ROW(pJoin), ROW(oJas), "x = (x + rmsnorm(rmsnorm(d) * w_d + rmsnorm(r) * w_r) * w_j) * s, over [M, n] rows, s one " - "element; rounding where the unfused chain rounds. Two arms' post-norms, their sum, its norm, " - "the residual add and a per-layer scalar (Gemma 4's feed-forward join)." }, + "element; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding where the " + "unfused chain rounds. Two arms' post-norms, their sum, its norm, the residual add, a " + "per-layer scalar and the next layer's input norm (Gemma 4's feed-forward join)." }, }; /* ==================================================================== operand descriptions @@ -279,6 +282,9 @@ int norm_add_norm_host(const RadArgs* a, RadStream) { int join_add_scale_host(const RadArgs* a, RadStream) { if (!a || a->n_t < 7) return RAD_E_INVAL; + const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr, + *Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr; + if (!Wn != !Y) return RAD_E_INVAL; const int64_t n = rad_args_geti_or(a, "n", 0); const double eps = rad_args_getf_or(a, "eps", 1e-6); const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2), @@ -287,9 +293,11 @@ int join_add_scale_host(const RadArgs* a, RadStream) { if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL; if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE; if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE; - int64_t rd, ld, rr, lr, rx, lx; + if (Wn && !hgain(Wn, n)) return RAD_E_DTYPE; + int64_t rd, ld, rr, lr, rx, lx, ry = 0, ly = 0; if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE; - if (rd < rx || rr < rx) return RAD_E_SHAPE; + if (Y && !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; + if (rd < rx || rr < rx || (Y && ry < rx)) return RAD_E_SHAPE; const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data; const float sc = hb2f(*(const uint16_t*)Sc->data); std::vector dv((size_t)n), rv((size_t)n); @@ -305,6 +313,13 @@ int join_add_scale_host(const RadArgs* a, RadStream) { for (int64_t i = 0; i < n; ++i) { const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i])); xr[i] = hf2b(x1 * sc); + rv[(size_t)i] = hb2f(xr[i]); + } + if (Y) { + const float* wn = (const float*)Wn->data; + uint16_t* yr = (uint16_t*)Y->data + m * ly; + const float sn = hnorm(rv.data(), n, eps); + for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((rv[(size_t)i] * sn) * wn[i]); } } return RAD_OK; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 47bee29c..881da9f7 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3640,3 +3640,39 @@ TEST(gemma4_sliding_attention_reads_q_in_the_fused_row) { CHECK(std::find(at->reads.begin(), at->reads.end(), (rad_buf)qkv) != at->reads.end()); CHECK_EQ(count_op(b, "cast"), 0); /* no drafter here, so no taps either */ } + +/* The feed-forward join writes the next layer's input norm: with the joins served, the only + * rmsnorm from the residual `x` into `h` is layer 0's (nothing precedes it), the final norm is the + * last join's, and every join writes `h`. Refused, the chain declares all of them again. */ +TEST(gemma4_feed_forward_join_writes_the_next_input_norm) { + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + if (refuse) { b.refuse.insert("norm_add_norm"); b.refuse.insert("join_add_scale"); } + RadModelMeta meta = gemma4_moe_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4::declare(&b, &meta, &ctx)); + const int x = buf_named(b, "x"), h = buf_named(b, "h"); + REQUIRE(x > 0 && h > 0); + int x_to_h = 0, joins_to_h = 0; + for (const auto& o : b.ops) { + if (!o.resolved) continue; + const bool rx = std::find(o.reads.begin(), o.reads.end(), (rad_buf)x) != o.reads.end(); + const bool wh = std::find(o.writes.begin(), o.writes.end(), (rad_buf)h) != o.writes.end(); + if (o.op == "rmsnorm" && rx && wh) ++x_to_h; + if (o.op == "join_add_scale" && wh) ++joins_to_h; + } + /* fused: layer 0's input norm. Chained: six input norms, six pre-feedforward norms, the + * final norm. */ + CHECK_EQ(x_to_h, refuse ? 13 : 1); + CHECK_EQ(joins_to_h, refuse ? 0 : 6); + + 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()); + const std::vector issued = issued_ops(b, c); + CHECK_EQ(count_issued(issued, "join_add_scale"), refuse ? 0 : 6); + CHECK_EQ(count_issued(issued, "logits_gemm"), 1); + } +} diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp index 32c89094..7e09c672 100644 --- a/tests/g4k_emu/test_norm.cpp +++ b/tests/g4k_emu/test_norm.cpp @@ -135,28 +135,30 @@ static int case_nan(int M, int n, int pad, int extra_rows) { return ok ? 0 : 1; } -static int case_jas(int M, int n, int pad, int extra_rows) { +/* `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; const float eps = 1e-6f; /* the two arms as one [2M, n] buffer, as the plugin holds them: dense rows, then routed */ - auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f); - auto wd = gains(n), wr = gains(n), wj = gains(n); + auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f), y0 = randb((size_t)R * ld, 1.f); + auto wd = gains(n), wr = gains(n), wj = gains(n), wn = gains(n); uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f); - auto xd = x, xh = x; - RadTensor t[7] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n), + auto xd = x, xh = x, yd = y0, yh = y0; + RadTensor t[9] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n), rows(ff.data() + (size_t)M * ld, RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n), - vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1) }; + vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1), + vec(wn.data(), RAD_F32, n), rows(yd.data(), RAD_BF16, M, n, ld) }; RadParam p[4]{}; 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"; - RadArgs ar{}; ar.t = t; ar.n_t = 7; ar.p = p; ar.n_p = 4; + RadArgs ar{}; ar.t = t; ar.n_t = next ? 9 : 7; ar.p = p; ar.n_p = 4; if (g4k_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; } - t[5].data = xh.data(); + t[5].data = xh.data(); t[8].data = yh.data(); if (host_row("join_add_scale")->launch(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: host launch failed"); return 1; } - Tally tx; + Tally tx, ty; for (int m = 0; m < R; ++m) { const size_t o = (size_t)m * ld; - if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; continue; } - for (int i = n; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; + if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; } + for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); std::vector dv((size_t)n), rv((size_t)n), sv((size_t)n); for (int i = 0; i < n; ++i) { dv[(size_t)i] = b2f(ff[o + i]); rv[(size_t)i] = b2f(ff[(size_t)M * ld + o + i]); } const auto d1 = chain_norm(dv, wd.data(), n, eps); /* rmsnorm (arm 1) */ @@ -166,10 +168,19 @@ static int case_jas(int M, int n, int pad, int extra_rows) { std::vector cx((size_t)n); for (int i = 0; i < n; ++i) cx[(size_t)i] = f2b(rb(b2f(x[o + i]) + j[(size_t)i]) * b2f(sc)); /* add, mul_weight */ cmp(&xd[o], cx.data(), &xh[o], n, tx); + if (next) { /* the next rmsnorm */ + std::vector xv((size_t)n); + for (int i = 0; i < n; ++i) xv[(size_t)i] = b2f(cx[(size_t)i]); + const auto yn = chain_norm(xv, wn.data(), n, eps); + std::vector cy((size_t)n); + for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(yn[(size_t)i]); + cmp(&yd[o], cy.data(), &yh[o], n, ty); + } } - const bool ok = tx.chain_bad == 0 && tx.host_bad == 0 && tx.pad == 0; - std::printf("join_add_scale M %3d n %4d pitch %4d: vs chain %ld differ; vs host arm %ld differ, worst %.1e of the " - "row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, tx.host_diff, tx.worst, tx.pad, + const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0; + std::printf("join_add_scale%s M %3d n %4d pitch %4d: vs chain %ld/%ld differ; vs host arm %ld/%ld differ, worst %.1e " + "of the row rms; padding touched %ld -> %s\n", next ? "+next" : " ", M, n, ld, tx.chain_bad, + ty.chain_bad, tx.host_diff, ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad, ok ? "PASS" : "FAIL"); return ok ? 0 : 1; } @@ -183,6 +194,9 @@ int main() { fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1); fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0); fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1); + /* 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); std::printf("norm joins: %d failure(s)\n", fails); return fails ? 1 : 0; }