diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index 3831efd9..7dba1b8f 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -248,6 +248,10 @@ 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_r: op_join_a writing the routed arm's two inputs as well -- the router's norm into + * b_rn and the experts' fp8 codes into b_hq / b_hqs (gemma4k norm_add_norm_route) -- where the + * layer's gate_up is block fp8. op_rnorm and op_enorm are then declared and not issued. */ + rad_op op_join_r = 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. */ @@ -1013,7 +1017,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * libref has no row for the joins on purpose, so "nothing serves them" stays reachable. */ const char* fuse_env = std::getenv("RADIANCE_GEMMA4_FUSE"); const bool fuse_joins = !(fuse_env && fuse_env[0] == '0'); - int n_joins = 0; + int n_joins = 0, n_route = 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 @@ -1157,13 +1161,37 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* bf16 and one element: the reference multiplies the bf16 stream by it. */ y.w_scalar = decl_w(b, nm.f("blk.%lld.layer_scalar", ll), RAD_BF16, {1}, A, N, gl); - if (fuse_joins) + /* The routed arm's two input norms -- the router's gain and the experts' pre-norm -- are + * declared here, ahead of the attention join, which writes both inputs where gemma4k + * serves `norm_add_norm_route` and an op names its weights after they are declared. */ + if (m.moe) { + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), + src("pre_feedforward_layernorm_2.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); + y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, + gl); + y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); + } + + /* THE ATTENTION JOIN, and on a layer whose gate_up is block fp8 the routed arm's two + * inputs with it: the router's norm (rmsnorm's expression, its mult hidden^-0.5) and the + * experts' E4M3 codes (rmsnorm_quant_fp8's) from the norm of x the join already takes -- + * two launches a layer fewer, and two reads of x. Then norm_add_norm, then the chain. */ + if (fuse_joins && m.moe && y.gu_fp8) + y.op_join_r = rw(b, RAD_OP(b, "norm_add_norm_route", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16"), + RAD_F64("mult", 1.0 / std::sqrt((double)E)), + RAD_INT("group", RAD_FP8_BLOCK)), + RAD_WEIGHTS(y.w_apost, y.w_fnorm, y.w_rscale, y.w_enorm)), + {m.b_o, m.b_x}, {m.b_x, m.b_h, m.b_rn, m.b_hq, m.b_hqs}); + if (fuse_joins && !y.op_join_r) y.op_join_a = rw(b, RAD_OP(b, "norm_add_norm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(y.w_apost, y.w_fnorm)), {m.b_o, m.b_x}, {m.b_x, m.b_h}); - if (!y.op_join_a) { + if (!y.op_join_a && !y.op_join_r) { y.op_apost = rmsnorm(T, E, y.w_apost, 1.0, m.b_o, m.b_o); y.op_add_a = binop("add", T, E, m.b_x, m.b_o, m.b_x); y.op_fnorm = rmsnorm(T, E, y.w_fnorm, 1.0, m.b_x, m.b_h); @@ -1180,19 +1208,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c src("post_feedforward_layernorm_1.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), src("post_feedforward_layernorm_2.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), - src("pre_feedforward_layernorm_2.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), src("router.proj.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), src("router.scale"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%lld.ffn_exp_scale", ll), src("router.per_expert_scale"))); y.w_fpost1 = decl_w(b, nm.f("blk.%lld.ffn_post_norm1.weight", ll), RAD_F32, {E}, A, N, gl); y.w_fpost2 = decl_w(b, nm.f("blk.%lld.ffn_post_norm2.weight", ll), RAD_F32, {E}, A, N, gl); - y.w_enorm = decl_w(b, nm.f("blk.%lld.ffn_norm_exps.weight", ll), RAD_F32, {E}, A, N, gl); /* THE ROUTER IS REPLICATED (rad_block_moe_fp8.h argues it): every rank routes every * token the same way from the same residual stream. */ y.w_router = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.weight", ll), RAD_BF16, {m.n_expert, E}, A, N, gl); - y.w_rscale = decl_w(b, nm.f("blk.%lld.ffn_gate_inp.scale", ll), RAD_F32, {E}, A, N, gl); y.w_escale = decl_w(b, nm.f("blk.%lld.ffn_exp_scale", ll), RAD_BF16, {m.n_expert}, A, N, gl); /* THE EXPERTS: whole experts, this rank's run of them (their name maps and encodings @@ -1425,7 +1448,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_WEIGHTS(y.w_scalar)), {m.b_x}, {m.b_x}); } - n_joins += (y.op_join_a ? 1 : 0) + (y.op_join_f ? 1 : 0); + n_joins += (y.op_join_a || y.op_join_r ? 1 : 0) + (y.op_join_f ? 1 : 0); + n_route += y.op_join_r ? 1 : 0; /* THE TAP: a row copy of the layer's output into the column slice a tap owns, DECLARED * HERE, after the layer's last op, because that is where step() issues it. The buffer @@ -1455,8 +1479,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const bool ov_off = ov_env && ov_env[0] == '0'; m.overlap = W > 1 && m.moe && g.wire_exact && T >= 2 * m.moe_rows && !ov_off; for (const Layer& y : m.layers) - m.overlap = m.overlap && y.op_join_a && y.op_join_f && y.next_norm && y.op_ar_o && - y.op_ar_f; + m.overlap = m.overlap && (y.op_join_a || y.op_join_r) && y.op_join_f && y.next_norm && + y.op_ar_o && y.op_ar_f; if (m.overlap) { RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_o)); RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_ff2)); @@ -1512,6 +1536,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c n_joins, (long long)(m.moe ? 2 * m.n_layer : m.n_layer), !fuse_joins ? " -- RADIANCE_GEMMA4_FUSE=0, the rmsnorm / add / mul_weight chain" : n_joins == 0 ? " -- not served (load gemma4k), the rmsnorm / add / mul_weight chain" : ""); + if (m.moe && m.n_gu_fp8 > 0) + rad_note(b, "routed inputs: %d of %d fp8 layers take the router's norm and the experts' " + "codes from the attention join (gemma4k norm_add_norm_route)%s", + n_route, m.n_gu_fp8, + n_route ? "" : " -- the rmsnorm and rmsnorm_quant_fp8 launches instead"); if (m.ks.nh > 0) rad_note(b, "sliding attention: q %s", m.qrow == 1 ? "read in the fused qkv row (gemma4k attn_paged_qrow)" @@ -1556,8 +1585,9 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t const int64_t n = (end - r0 < m.moe_rows) ? (end - r0) : m.moe_rows; int32_t* const counts = rad_route_counts(c, (int)(&y - m.layers.data()), NL); const RadOperand ecnt = counts ? praw(counts, RAD_I32, NL) : brows(m.b_ecnt, NL); - RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), - brow_slice(m.b_rn, r0, n, E)); + if (!y.op_join_r) /* the attention join wrote the router's input otherwise */ + RAD_ISSUE_N(c, y.op_rnorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_rscale), + brow_slice(m.b_rn, r0, n, E)); /* One launch, two or three: the router, its top-k and the sort (see declare). */ const bool rfused = y.op_router_fused && n <= y.router_fused_rows; const bool pair = !rfused && y.op_topk_scatter && n <= y.topk_scatter_rows; @@ -1589,12 +1619,13 @@ static void routed(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t RAD_ISSUE_N(c, y.op_emul, n, brow_slice(m.b_ew, r0, n, K), brow_slice(m.b_es, r0, n, K), brow_slice(m.b_ew, r0, n, K)); } - /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent). */ - if (y.gu_fp8) + /* rmsnorm_quant_fp8's operands: x, residual (absent), w, q, scale, out_bf16 (absent) -- + * where the attention join did not write the codes already. */ + if (y.gu_fp8 && !y.op_join_r) RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_NONE, RAD_W(y.w_enorm), brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK), RAD_NONE); - else + else if (!y.gu_fp8) RAD_ISSUE_N(c, y.op_enorm, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_enorm), brow_slice(m.b_hx, r0, n, E)); if (!rfused && !pair) @@ -1696,7 +1727,11 @@ static void trunk(RadCtx* c, const Model& m, const RadBatch* batch) { attend(c, m, y, li, batch); RAD_ISSUE(c, y.op_o, brows(y.full ? m.b_attf : m.b_atts, T), RAD_W(y.w_o), brows(m.b_o, T)); if (y.op_ar_o) RAD_ISSUE_N(c, y.op_ar_o, T * E, brows(m.b_o, T), RAD_NONE); - if (y.op_join_a) { + if (y.op_join_r) { + RAD_ISSUE(c, y.op_join_r, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), + RAD_W(y.w_fnorm), brows(m.b_h, T), RAD_W(y.w_rscale), brows(m.b_rn, T), + RAD_W(y.w_enorm), brows(m.b_hq, T), brows(m.b_hqs, T)); + } else if (y.op_join_a) { RAD_ISSUE(c, y.op_join_a, brows(m.b_o, T), RAD_W(y.w_apost), brows(m.b_x, T), RAD_W(y.w_fnorm), brows(m.b_h, T)); } else { @@ -1804,8 +1839,14 @@ static void out_proj(RadCtx* c, const Model& m, const Layer& y, int64_t r0, int6 * routed, so its feed-forward reduction is one run. */ static void arms(RadCtx* c, const Model& m, const Layer& y, int64_t T, int64_t r0, int64_t n) { const int64_t E = m.E, F = m.n_ff; - RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), - brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); + if (y.op_join_r) + RAD_ISSUE_N(c, y.op_join_r, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E), + RAD_W(y.w_rscale), brow_slice(m.b_rn, r0, n, E), RAD_W(y.w_enorm), + brow_slice(m.b_hq, r0, n, E), brow_slice(m.b_hqs, r0, n, E / RAD_FP8_BLOCK)); + else + RAD_ISSUE_N(c, y.op_join_a, n, brow_slice(m.b_o, r0, n, E), RAD_W(y.w_apost), + brow_slice(m.b_x, r0, n, E), RAD_W(y.w_fnorm), brow_slice(m.b_h, r0, n, E)); RAD_ISSUE_N(c, y.op_gu, n, brow_slice(m.b_h, r0, n, E), RAD_W(y.w_gu), brow_slice(m.b_gu, r0, n, 2 * F)); RAD_ISSUE_N(c, y.op_act, n, bcol_at(m.b_gu, r0, 2 * F, 0, F, n), diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 065ed250..21daa5d8 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -542,10 +542,13 @@ expert parity, so a rank holds an even number of experts. **Kernels.** `--kernels gemma4k,libr4d,libavx`, **gemma4k first.** It serves all of the trunk's attention -- the sliding layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, four, eight ranks) -- plus `pair_argmax` and the fusions: the two sandwich-norm joins -(`norm_add_norm`, `join_add_scale`), `expert_scale`, and `attn_paged_qrow`, the sliding layers' -attention reading q where the fused qkv projection left it. The plugin declares each one's unfused -form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast` lifting q -for `attn_paged` -- and the startup notes say which were taken. The drafter's residual add, norm +(`norm_add_norm`, `join_add_scale`), `norm_add_norm_route` -- on a layer whose gate_up is block +fp8, the attention join writing the router's input and the experts' fp8 codes from the norm it +already takes, in place of an `rmsnorm` and an `rmsnorm_quant_fp8` -- `expert_scale`, and +`attn_paged_qrow`, the sliding layers' attention reading q where the fused qkv projection left it. +The plugin declares each one's unfused form where nothing serves it -- the rmsnorm / add chain, +`embed_lookup` + `mul`, a `cast` lifting q for `attn_paged` -- and the startup notes say which +were taken. The drafter's residual add, norm and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch an input (ten a draft pass), and the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves it. libr4d has h256/gqa2 and h512/gqa8 rows as well, written for the dense 31B; with gemma4k first the 26B-A4B runs on the diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 2ff9fe8d..cc9b1ba9 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1859,7 +1859,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct at al | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_G4K_WMMA` | `0` keeps `gemma4k`'s prefill attention on its scalar kernel instead of the WMMA one. An A/B switch and a way out if the matrix path misbehaves on a card; read once | -| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | +| `RADIANCE_GEMMA4_FUSE` | `0` makes `arch/gemma4` declare the chains instead of `gemma4k`'s fusions: the rmsnorm / add chain for the sandwich joins (`norm_add_norm`, `norm_add_norm_route`, `join_add_scale`), `embed_lookup` + `mul` for `expert_scale`, and a `cast` lifting q for `attn_paged` for `attn_paged_qrow`. An A/B switch; read at declare | | `RADIANCE_GEMMA4_OVERLAP` | `0` runs every `arch/gemma4` prefill chunk whole, its all-reduces on the compute stream, instead of as two slices whose all-reduces ride a second stream beside the other slice's compute. An A/B switch; read at declare | There is also a family of instruments for engine development — `RADIANCE_DEBUG_*` (residual probes, diff --git a/docs/OPS.md b/docs/OPS.md index ac97377f..cf34483c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -299,6 +299,7 @@ rounding. | op | params | operands | |---|---|---| | `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` | +| `norm_add_norm_route` | `M`(range) `n` `eps`:f64 `dtype` `mult`:f64 `group` | `a`, `w_a`w, `x`:inout, `w_y`w → `y`; `w_r`w → `r`; `w_e`w → `q`, `qs` | | `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`? | | `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout | | `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | @@ -315,6 +316,14 @@ differ from the chain only in the order a sum of squares is added in: with the s bit-identical to it, and against a chain summed in another block width a norm factor can differ in its last bit. +`norm_add_norm_route` is `norm_add_norm` and, from the same norm of the `x` it writes, a MoE +layer's two routed inputs: `r = rmsnorm(x) * w_r * mult` -- `rmsnorm`'s expression with `mult` -- +and `q`, `qs` = `rmsnorm_quant_fp8` of `x` under `w_e`: E4M3 codes of the bf16-rounded norm, an +f32 scale per (row, `group` columns) of `amax / 448` (1 for an all-zero group), the value over it +clamped to +-448. `n` is whole groups and `group` 128. In Gemma 4 it replaces the router's +`rmsnorm` and the experts' `rmsnorm_quant_fp8`, two launches a layer that read back the `x` the +join had just written. + `expert_scale` is `ew[t, k] = ew[t, k] * w_e[ids[t, k]]` over `[M, top_k]`, `w_e` an `[n_expert]` table and an id outside it reading 0: Gemma 4's per_expert_scale on the renormalised routing weights, in place of an `embed_lookup` of the table by the ids and a `mul` into the weights. One diff --git a/gemma4k/g4k.h b/gemma4k/g4k.h index 8350d8be..3ae85a65 100644 --- a/gemma4k/g4k.h +++ b/gemma4k/g4k.h @@ -27,9 +27,11 @@ int64_t g4k_attn_h512_scratch(const RadArgs* a); int g4k_pair_argmax_f32(const RadArgs* a, RadStream s); /* Gemma 4's sandwich-norm joins, one kernel each (g4k_norm.hip): - * norm_add_norm operands a, w_a, x (inout), w_y, y - * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ + * norm_add_norm operands a, w_a, x (inout), w_y, y + * norm_add_norm_route the same, then w_r, r, w_e, q, qs: the routed arm's two inputs + * join_add_scale operands d, w_d, r, w_r, w_j, x (inout), s */ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream s); +int g4k_norm_add_norm_route_bf16(const RadArgs* a, RadStream s); /* expert_scale: each routing weight times its expert's scale, in place (g4k_escale.hip): * operands ids, w_e, ew (inout) */ diff --git a/gemma4k/g4k_norm.hip b/gemma4k/g4k_norm.hip index 66d1d0d2..fc58bc69 100644 --- a/gemma4k/g4k_norm.hip +++ b/gemma4k/g4k_norm.hip @@ -20,6 +20,16 @@ * and, rarely, a bf16 output by one ulp. The arch plugin asks for these first and falls back to * the chain where nothing serves them (gemma4.cpp). * + * AND THE ROUTED ARM'S TWO INPUTS (norm_add_norm_route). The 26B-A4B's router reads norm(x) * w_r * + * hidden^-0.5 and its experts norm(x) * w_e, quantised to E4M3 -- two more launches a layer + * (`rmsnorm`, `rmsnorm_quant_fp8`), each reading back the x norm_add_norm has just written and + * taking the sum of squares norm_add_norm has just taken. The route form writes both from the norm + * factor it holds: the router's row by libr4d's rmsnorm expression, ((x * s) * w) * mult, and the + * experts' codes as libr4d's rmsnorm_quant_fp8 writes them -- the bf16-rounded norm, a scale of + * amax * (1 / 448) a 128 columns (1 where the group is all zero), 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. + * * One 256-thread block a row: a decode step is a handful of rows, so the row is latency-bound and * a block's three reductions beat seven launches. Values a later stage reuses stay in registers * (PER a thread, 12 to n = 3072 and kMaxPer = 24 to 6144; the row table says so). @@ -99,22 +109,30 @@ struct NormArgs { 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 */ + /* norm_add_norm_route: the router's input, the experts' codes and their scales; the router's + * gain is w2 and the experts' w3 */ + uint16_t* rt; long long rt_ld; + uint8_t* q; long long q_ld; + float* qs; long long qs_ld; + float mult; int n; float eps; }; -/* t = norm(a) * w_a; x += t; y = norm(x) * w_y */ -template +/* t = norm(a) * w_a; x += t; y = norm(x) * w_y -- and with ROUTE, from the same norm of x, the + * router's input norm(x) * w_r * mult and the experts' norm(x) * w_e as E4M3 codes and scales */ +template __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { __shared__ float lds[kWaves]; + __shared__ float gmax[ROUTE ? PER * kWaves : 1]; const int tid = (int)threadIdx.x, n = A.n; const long long m = (long long)blockIdx.x; const uint16_t* ar = A.a + m * A.a_ld; uint16_t* xr = A.x + m * A.x_ld; uint16_t* yr = A.y + m * A.y_ld; - /* every operand of the row in flight at once: the block output, the residual, both gains */ - float av[PER], xv[PER], wa[PER], wy[PER]; + /* every operand of the row in flight at once: the block output, the residual, the gains */ + float av[PER], xv[PER], wa[PER], wy[PER], wr[ROUTE ? PER : 1], we[ROUTE ? PER : 1]; #pragma unroll for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; @@ -123,6 +141,10 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { xv[k] = in ? bf2f(xr[i]) : 0.0f; wa[k] = in ? A.w0[i] : 0.0f; wy[k] = in ? A.w1[i] : 0.0f; + if constexpr (ROUTE) { + wr[k] = in ? A.w2[i] : 0.0f; + we[k] = in ? A.w3[i] : 0.0f; + } } float ss = 0.0f; #pragma unroll @@ -140,10 +162,45 @@ __global__ __launch_bounds__(kThreads) void norm_add_norm_kernel(NormArgs A) { ss += xv[k] * xv[k]; } const float sx = norm_factor(block_sum(ss, lds), n, A.eps); + uint16_t* rr = ROUTE ? A.rt + m * A.rt_ld : nullptr; #pragma unroll for (int k = 0; k < PER; ++k) { const int i = tid + k * kThreads; - if (i < n) yr[i] = f2bf((xv[k] * sx) * wy[k]); + if (i < n) { + yr[i] = f2bf((xv[k] * sx) * wy[k]); + if constexpr (ROUTE) { + rr[i] = f2bf(((xv[k] * sx) * wr[k]) * A.mult); + av[k] = rbf((xv[k] * sx) * we[k]); /* the experts' row, as quantised */ + } + } else if constexpr (ROUTE) { + av[k] = 0.0f; + } + } + if constexpr (ROUTE) { + /* group 2k + tid / 128 at slot k is waves 0..3 or 4..7: each wave's max, then its four */ + const int wave = tid >> 5, half = tid >> 7; +#pragma unroll + for (int k = 0; k < PER; ++k) { + float mx = fabsf(av[k]); +#pragma unroll + for (int d = 16; d >= 1; d >>= 1) mx = fmaxf(mx, shfl_xor(mx, d)); + if (lane_id() == 0) gmax[k * kWaves + wave] = mx; + } + __syncthreads(); + uint8_t* qr = A.q + m * A.q_ld; + float* sr = A.qs + m * A.qs_ld; +#pragma unroll + for (int k = 0; k < PER; ++k) { + const int i = tid + k * kThreads; + if (i >= n) continue; /* n is whole groups: a group is in or out */ + const float* g = gmax + k * kWaves + 4 * half; + const float am = fmaxf(fmaxf(g[0], g[1]), fmaxf(g[2], g[3])); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + const float v = fminf(fmaxf(av[k] * inv, -448.0f), 448.0f); + qr[i] = (uint8_t)(__builtin_amdgcn_cvt_pk_fp8_f32(v, v, 0, false) & 0xff); + if ((tid & 127) == 0) sr[i >> 7] = sc; + } } } @@ -224,14 +281,17 @@ __global__ __launch_bounds__(kThreads) void join_add_scale_kernel(NormArgs A) { /* ------------------------------------------------------------------ host: the launch adapters */ -/* [rows..., n] with a dense last axis: its row count and pitch, or false */ -static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { - if (!t || t->dtype != RAD_BF16 || t->rank < 1) return false; +/* [rows..., n] of `dt` with a dense last axis: its row count and pitch, or false */ +static bool rows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1) return false; if (rad_tensor_lastdim(t) != n || (t->stride[t->rank - 1] != 1)) return false; *rows = rad_tensor_rows(t); *ld = rad_tensor_row_pitch(t); return *ld >= n || *rows <= 1; } +static bool rows_of(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) { + return rows_as(t, RAD_BF16, n, rows, ld); +} static bool gain(const RadTensor* w, int64_t n) { return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n && (w->rank == 0 || w->stride[w->rank - 1] == 1); @@ -272,11 +332,54 @@ int g4k_norm_add_norm_bf16(const RadArgs* a, RadStream stream) { P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; P.n = (int)n; P.eps = eps; if (n <= (int64_t)kThreads * 12) - G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12>), dim3((unsigned)M), dim3(kThreads), + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12, false>), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); else - G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), dim3(kThreads), + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel), dim3((unsigned)M), + dim3(kThreads), (hipStream_t)stream, P); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* operands: a, w_a, x (inout), w_y, y, w_r, r, w_e, q, qs */ +int g4k_norm_add_norm_route_bf16(const RadArgs* a, RadStream stream) { + using namespace g4kn; + if (!a || a->n_t < 10) return RAD_E_INVAL; + int64_t n = 0; + float eps = 0.0f; + if (int rc = params(a, &n, &eps)) return rc; + if (n % 128 || rad_args_geti_or(a, "group", 0) != 128) return RAD_E_SHAPE; + const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), + *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4), *Wr = rad_arg_in(a, 5), + *R = rad_arg_in(a, 6), *We = rad_arg_in(a, 7), *Q = rad_arg_in(a, 8), + *S = rad_arg_in(a, 9); + if (!A_ || !X || !Y || !R || !Q || !S) return RAD_E_INVAL; + if (!gain(Wa, n) || !gain(Wy, n) || !gain(Wr, n) || !gain(We, n)) return RAD_E_DTYPE; + int64_t ra = 0, la = 0, rx = 0, lx = 0, ry = 0, ly = 0, rr = 0, lr = 0, rq = 0, lq = 0, + rs = 0, ls = 0; + if (!rows_of(A_, n, &ra, &la) || !rows_of(X, n, &rx, &lx) || !rows_of(Y, n, &ry, &ly) || + !rows_of(R, n, &rr, &lr) || !rows_as(Q, RAD_F8E4M3, n, &rq, &lq) || + !rows_as(S, RAD_F32, n / 128, &rs, &ls)) + return RAD_E_SHAPE; + const int64_t M = rx; /* the step's rows: the stream's view */ + if (M <= 0) return RAD_OK; + if (ra < M || ry < M || rr < M || rq < M || rs < M || M > 0x7fffffff) return RAD_E_SHAPE; + NormArgs P{}; + P.a = (const uint16_t*)A_->data; P.a_ld = la; + P.x = (uint16_t*)X->data; P.x_ld = lx; + P.y = (uint16_t*)Y->data; P.y_ld = ly; + P.rt = (uint16_t*)R->data; P.rt_ld = lr; + P.q = (uint8_t*)Q->data; P.q_ld = lq; + P.qs = (float*)S->data; P.qs_ld = ls; + P.w0 = (const float*)Wa->data; P.w1 = (const float*)Wy->data; + P.w2 = (const float*)Wr->data; P.w3 = (const float*)We->data; + P.mult = (float)rad_args_getf_or(a, "mult", 1.0); + P.n = (int)n; P.eps = eps; + if (n <= (int64_t)kThreads * 12) + G4K_LAUNCH(G4K_KNAME(norm_add_norm_kernel<12, true>), dim3((unsigned)M), dim3(kThreads), (hipStream_t)stream, P); + else + G4K_LAUNCH(G4K_KNAME(norm_add_norm_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 47b4e2be..72dc4907 100644 --- a/gemma4k/g4k_rows.cpp +++ b/gemma4k/g4k_rows.cpp @@ -11,6 +11,8 @@ * norm_add_norm and join_add_scale, ops this library DEFINES: Gemma 4's two sandwich-norm joins, * each one kernel in place of a chain of rmsnorm / add / mul_weight launches, rounding where the * chain rounds (g4k_norm.hip). The arch plugin asks for them and falls back to the chain. + * norm_add_norm_route is the attention join writing the routed arm's two inputs as well -- the + * router's norm and the experts' fp8 codes -- in place of an rmsnorm and an rmsnorm_quant_fp8. * * Put it AHEAD of libr4d for Gemma 4 (`--kernels gemma4k,libr4d,...`). The hierarchy is absolute, * and libr4d has rows at h256/gqa2 and h512/gqa8 too -- written for the dense 31B, which has no @@ -40,6 +42,7 @@ #define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } #define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } #define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } +#define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } namespace { @@ -74,6 +77,26 @@ static const RadOperandSpec oNan[] = { { "w_y", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pRoute[] = { + { "M", RAD_P_INT, RAD_REQUIRED, 0 }, + { "n", RAD_P_INT, RAD_REQUIRED, 0 }, + { "eps", RAD_P_F64, RAD_REQUIRED, 0 }, + { "dtype", RAD_P_STR, RAD_REQUIRED, 0 }, + { "mult", RAD_P_F64, RAD_REQUIRED, 0 }, + { "group", RAD_P_INT, RAD_REQUIRED, 0 }, +}; +static const RadOperandSpec oRoute[] = { + { "a", RAD_OPD_IN, 0 }, + { "w_a", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_INOUT, 0 }, + { "w_y", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, + { "w_r", RAD_OPD_WEIGHT, 0 }, + { "r", RAD_OPD_OUT, 0 }, + { "w_e", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "qs", RAD_OPD_OUT, 0 }, +}; static const RadOperandSpec oJas[] = { { "d", RAD_OPD_IN, 0 }, { "w_d", RAD_OPD_WEIGHT, 0 }, @@ -138,6 +161,11 @@ static const RadOpSchema kSchemas[] = { "t = rmsnorm(a) * w_a; x = x + t; y = rmsnorm(x) * w_y, over [M, n] rows; every value the " "unfused rmsnorm, add, rmsnorm chain stores is rounded to the activation dtype at the same " "point. A post-norm, the residual add and the next pre-norm (Gemma's sandwich)." }, + { "norm_add_norm_route", ROW(pRoute), ROW(oRoute), + "norm_add_norm, then from the same rmsnorm of the x it writes r = rmsnorm(x) * w_r * mult " + "and the E4M3 codes q of rmsnorm(x) * w_e with an f32 scale qs per (row, `group` columns): " + "rmsnorm_quant_fp8's codes, taken over the bf16-rounded norm. A MoE layer's router input and " + "its experts' fp8 input, written by the attention join that already holds the norm." }, { "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; and with w_n and y, y = rmsnorm(x) * w_n over the x written. Rounding where the " @@ -301,17 +329,36 @@ static bool hgain(const RadTensor* w, int64_t n) { return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n; } -int norm_add_norm_host(const RadArgs* a, RadStream) { - if (!a || a->n_t < 5) return RAD_E_INVAL; +/* [rows..., n] of `dt`, dense last axis, for the route form's fp8 codes and f32 scales */ +static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) { + if (!t || t->dtype != dt || t->rank < 1 || rad_tensor_lastdim(t) != n) return false; + if (t->stride[t->rank - 1] != 1) return false; + *rows = rad_tensor_rows(t); + *ld = rad_tensor_row_pitch(t); + return true; +} + +/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */ +static int nan_host(const RadArgs* a, bool route) { + if (!a || a->n_t < (route ? 10 : 5)) 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 float mult = (float)rad_args_getf_or(a, "mult", 1.0); const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2), *Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4); - if (n <= 0 || !A_ || !X || !Y) return RAD_E_INVAL; - if (!hgain(Wa, n) || !hgain(Wy, n)) return RAD_E_DTYPE; - int64_t ra, la, rx, lx, ry, ly; + const RadTensor *Wr = route ? rad_arg_in(a, 5) : nullptr, *R = route ? rad_arg_in(a, 6) : nullptr; + const RadTensor *We = route ? rad_arg_in(a, 7) : nullptr, *Q = route ? rad_arg_in(a, 8) : nullptr; + const RadTensor *S = route ? rad_arg_in(a, 9) : nullptr; + if (n <= 0 || !A_ || !X || !Y || (route && (!R || !Q || !S))) return RAD_E_INVAL; + if (route && (n % 128 || rad_args_geti_or(a, "group", 0) != 128)) return RAD_E_SHAPE; + if (!hgain(Wa, n) || !hgain(Wy, n) || (route && (!hgain(Wr, n) || !hgain(We, n)))) + return RAD_E_DTYPE; + int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0; if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE; - if (ra < rx || ry < rx) return RAD_E_SHAPE; + if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) || + !hrows_as(S, RAD_F32, n / 128, &rs, &ls))) + return RAD_E_SHAPE; + if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE; const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data; std::vector v((size_t)n), xv((size_t)n); for (int64_t m = 0; m < rx; ++m) { @@ -327,9 +374,33 @@ int norm_add_norm_host(const RadArgs* a, RadStream) { } const float sx = hnorm(xv.data(), n, eps); for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]); + if (!route) continue; + /* the router's row, and the experts' as rmsnorm_quant_fp8 writes it (v holds it) */ + const float *wr = (const float*)Wr->data, *we = (const float*)We->data; + uint16_t* rrow = (uint16_t*)R->data + m * lr; + uint8_t* qrow = (uint8_t*)Q->data + m * lq; + float* srow = (float*)S->data + m * ls; + for (int64_t i = 0; i < n; ++i) { + rrow[i] = hf2b(((xv[(size_t)i] * sx) * wr[i]) * mult); + v[(size_t)i] = hrbf((xv[(size_t)i] * sx) * we[i]); + } + for (int64_t g = 0; g < n / 128; ++g) { + float am = 0.0f; + for (int64_t i = g * 128; i < g * 128 + 128; ++i) + am = std::fmax(am, std::fabs(v[(size_t)i])); + const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f; + const float inv = 1.0f / sc; + srow[g] = sc; + for (int64_t i = g * 128; i < g * 128 + 128; ++i) { + const float c = std::fmin(std::fmax(v[(size_t)i] * inv, -448.0f), 448.0f); + qrow[i] = rad_f32_to_fp8e4m3(c); + } + } } return RAD_OK; } +int norm_add_norm_host(const RadArgs* a, RadStream) { return nan_host(a, false); } +int norm_add_norm_route_host(const RadArgs* a, RadStream) { return nan_host(a, true); } int join_add_scale_host(const RadArgs* a, RadStream) { if (!a || a->n_t < 7) return RAD_E_INVAL; @@ -431,6 +502,10 @@ G4K_ATTN_C(cH512x8B, 512, 8, "bf16", 0) G4K_ATTN_C(cH512x8F, 512, 8, "fp8_e4m3", /* the device kernels hold 24 elements a thread over a 256-thread block */ static const RadConstraint cJoin[] = { C_GE("n", 1), C_LE("n", 6144), C_IN("dtype", "bf16") }; static const RadConstraint cJoinHost[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; +static const RadConstraint cRoute[] = { C_GE("n", 128), C_LE("n", 6144), C_DIV("n", 128), + C_EQ("group", 128), C_IN("dtype", "bf16") }; +static const RadConstraint cRouteHost[] = { C_GE("n", 128), C_DIV("n", 128), C_EQ("group", 128), + C_IN("dtype", "bf16") }; static const RadConstraint cPick[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32") }; static const RadConstraint cEscale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16") }; @@ -490,6 +565,20 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_HOST, 10, ROW(cJoinHost), NOTUNE, nullptr, nullptr, norm_add_norm_host, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }, + { "norm_add_norm_route_bf16", "norm_add_norm_route", "norm", + "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", + "n <= 6144 in whole 128-column groups, any M, row pitches honoured", + "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", + RAD_DOMAIN_DEVICE, 10, ROW(cRoute), NOTUNE, + nullptr, nullptr, g4k_norm_add_norm_route_bf16, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, + { "norm_add_norm_route_bf16_host", "norm_add_norm_route", "norm", + "norm_add_norm, and the routed arm's router input and fp8 expert input from the same norm", + "any [M, n] in whole 128-column groups", + "bf16 activations, f32 gains; E4M3 codes with an f32 scale a 128 columns", + RAD_DOMAIN_HOST, 10, ROW(cRouteHost), NOTUNE, + nullptr, nullptr, norm_add_norm_route_host, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr }, { "join_add_scale_bf16", "join_add_scale", "norm", "two arms' post-norms, sum, norm, residual add, layer scalar: one block a row", "n <= 6144, any M, row pitches honoured", "bf16 activations, f32 gains, bf16 scalar", diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4a01dd66..2ab1ac44 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -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 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); +} diff --git a/tests/g4k_emu/emu/emu.cpp b/tests/g4k_emu/emu/emu.cpp index f3f70c19..f35435a3 100644 --- a/tests/g4k_emu/emu/emu.cpp +++ b/tests/g4k_emu/emu/emu.cpp @@ -1,4 +1,5 @@ #include "hip/hip_runtime.h" +#include "rad_plugin.h" #include #include @@ -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; diff --git a/tests/g4k_emu/emu/hip/hip_runtime.h b/tests/g4k_emu/emu/hip/hip_runtime.h index d17a081f..af77b8d6 100644 --- a/tests/g4k_emu/emu/hip/hip_runtime.h +++ b/tests/g4k_emu/emu/hip/hip_runtime.h @@ -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; }; diff --git a/tests/g4k_emu/test_norm.cpp b/tests/g4k_emu/test_norm.cpp index 38f1598a..c63a1397 100644 --- a/tests/g4k_emu/test_norm.cpp +++ b/tests/g4k_emu/test_norm.cpp @@ -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 q0((size_t)R * ldq); + std::vector 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 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 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; }