libr4d, arch/gemma4_bf16: at four ranks the 31B's junctions carry the all-reduce in front of them

ar_rmsnorm_quant_i8_4rank is the wide family's exact four-rank one-shot with the junction (the
residual add, the sandwich norm and the int8 quantiser) as its epilogue, as ar_hc_write_4rank is
that one-shot with hc_write. The reduce is the standalone exact all-reduce's arithmetic element by
element (fp32 from zero, ranks ascending, one rounding to bf16), so the reduced row matches it to
the bit, and the junction is rmsnorm_quant_i8's over that row. It shares the standalone
all-reduce's transport and instance and ends the engine's link hold itself, as docs/TP4.md asks of
a new collective row.

Every block takes one handshake, a system-scope release by its first thread and a system-scope
acquire by every wave. Both fences are needed: on 4x R9700 behind an EPYC root complex, dropping
either left the readers with stale scratch on nearly every element. `nblocks` 2 and 4 (fewer
handshakes, each block owning several rows) are tune points, off by default.

r4d_selftest's case of the same name holds every rank's reduced row, residual, output, codes and
scales byte for byte to all_reduce followed by rmsnorm_quant_i8 on four cards, at 1, 8, 40 and 97
rows of 5376 and 64 rows of 2816. r4d_selftest is now installed in the image, so a card box can run
the rows' checks without a build tree.

At four ranks a 31B decode step issued 121 standalone all-reduces, 119 of them followed by a
separate norm launch. The plugin now declares ar_rmsnorm_quant_i8_4rank for steps of up to 4 rows
(kAr4FoldRows), where it serves every junction but the last layer's feed-forward one: a decode step
issues 2 standalone reductions. Taller steps, every speculative verify among them, issue the pair
(the all-reduce, then rmsnorm_quant_i8): a one-shot sends three times the message a rank, and at 16
rows the standalone all-reduce's exact two-shot beats the fold's per-row handshakes.

On 4x R9700 (the w4a8 container, tp 4, two rounds): plain decode 90 / 90 / 89-90 tok/s against
86 / 87 / 86 for code / prose / story, and 85 against 82 after a 6442-token prompt, +4.7%; a
DFlash verify at 16 rows measured 300 tok/s on the pair against 276 on the fold, hence the band.
Both paths give the same bytes. Where no library declares the fold, every step issues the pair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
AshlynandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-21 09:22:06 +02:00
1 parent 4246a1dd04
commit 5f78a1d0cd
12 files changed
+737 -37

No files matched your search

+51 -11
View File
@@ -12,6 +12,7 @@
#include <arch/rad_block_gemma4_vision.h> #include <arch/rad_block_gemma4_vision.h>
#include <arch/rad_gemma4_chat.h> #include <arch/rad_gemma4_chat.h>
#include <algorithm>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cmath> #include <cmath>
@@ -546,9 +547,25 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
/* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the /* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the
* layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With
* `res` null it is the plain norm of `x`, the first block's entry. */ * `res` null it is the plain norm of `x`, the first block's entry. */
/* The four-rank fold's band. libr4d's exact all-reduce is a one-shot up to this many elements
* (R4D_AR_WIDE_ONESHOT_MAX_ELEMS) and a two-shot above, and the fused junction at four ranks is
* that one-shot with the junction as its epilogue: three times the message per rank on the link,
* which pays at decode heights and not at a prefill's. So at four ranks op_ar serves the rows a
* one-shot would, 97 at 5376, and a taller step issues the all-reduce and the junction apart.
*
* Within that band the fold pays only at the bottom. On 4x R9700 (2026-10-17, same image) a plain
* decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify
* (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact
* two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs
* cross near 4-5 rows, so the fold serves up to kAr4FoldRows rows and a taller step issues the
* pair. */
static constexpr int64_t kArOneShotElems = 524288;
static constexpr int64_t kAr4FoldRows = 4;
struct G4Junction { struct G4Junction {
rad_op op = 0; rad_op op = 0;
rad_op op_ar = 0; /* the same with the two-rank exact all-reduce of `x` in front, or 0 */ rad_op op_ar = 0; /* the same with the exact all-reduce of `x` in front, or 0 */
int64_t ar_rows = 0; /* the most rows op_ar serves: the step's at two ranks, a band at four */
rad_buf x = 0, res = 0, q8 = 0, s8 = 0; rad_buf x = 0, res = 0, q8 = 0, s8 = 0;
rad_weight w = 0, wp = 0, sc = 0; rad_weight w = 0, wp = 0, sc = 0;
@@ -571,11 +588,16 @@ struct G4Junction {
const rad_buf wr[3] = { q8, s8, res }; const rad_buf wr[3] = { q8, s8, res };
rad_op_reads (b, op, rd, res ? 2 : 1); rad_op_reads (b, op, rd, res ? 2 : 1);
rad_op_writes(b, op, wr, res ? 3 : 2); rad_op_writes(b, op, wr, res ? 3 : 2);
/* With the all-reduce in front, at two ranks on the exact wire: `x` is then a rank's /* With the all-reduce in front, at two or four ranks on the exact wire: `x` is then a
* partial sum of a column-sharded linear. With the lossy wire allowed, the standalone * rank's partial sum of a column-sharded linear. With the lossy wire allowed, the
* all-reduce is kept, since it may choose that wire. */ * standalone all-reduce is kept, since it may choose that wire. At four ranks the fold is
if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { * the one-shot's and serves only its band (kArOneShotElems, kAr4FoldRows). */
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), const bool four = g.world == 4;
const int64_t hi = four ? std::min<int64_t>(kAr4FoldRows, std::min<int64_t>(g.max_tok, kArOneShotElems / g.n_embd))
: g.max_tok;
if (res && g.wire_exact && (g.world == 2 || four) && hi >= 1 &&
rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
const RadParam pa[] = { RAD_RANGE("M", 1, hi), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw); op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw);
@@ -583,6 +605,7 @@ struct G4Junction {
const rad_buf wa[4] = { x, q8, s8, res }; const rad_buf wa[4] = { x, q8, s8, res };
rad_op_reads (b, op_ar, rd, 2); rad_op_reads (b, op_ar, rd, 2);
rad_op_writes(b, op_ar, wa, 4); rad_op_writes(b, op_ar, wa, 4);
ar_rows = hi;
} }
} }
return RAD_OK; return RAD_OK;
@@ -1098,6 +1121,7 @@ struct Model {
G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */ G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */
bool fuse = false; bool fuse = false;
bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */
int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */
}; };
static Model g_model[MAX_RANKS]; static Model g_model[MAX_RANKS];
@@ -1320,12 +1344,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
} }
} }
m.fuse = ok; m.fuse = ok;
bool ar = ok && g.world == 2; bool ar = ok && (g.world == 2 || g.world == 4);
int64_t rows = g.max_tok;
for (int64_t l = 0; ar && l < m.n_main; ++l) { for (int64_t l = 0; ar && l < m.n_main; ++l) {
const Layer& lay = m.layers[(size_t)l]; const Layer& lay = m.layers[(size_t)l];
ar = lay.j_am.op_ar != 0 && (l + 1 >= m.n_main || lay.j_ma.op_ar != 0); ar = lay.j_am.op_ar != 0 && (l + 1 >= m.n_main || lay.j_ma.op_ar != 0);
if (ar) rows = std::min(rows, lay.j_am.ar_rows);
if (ar && l + 1 < m.n_main) rows = std::min(rows, lay.j_ma.ar_rows);
} }
m.fuse_ar = ar; m.fuse_ar = ar;
m.ar_rows = ar ? rows : 0;
} }
/* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */ /* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */
@@ -1385,6 +1413,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
g.rank, g.world, (long long)g.n_layer, (long long)n_global, g.rank, g.world, (long long)g.n_layer, (long long)n_global,
(long long)(g.n_layer - n_global), (long long)sliding_win, (long long)(g.n_layer - n_global), (long long)sliding_win,
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g);
if (m.fuse && (g.world == 2 || g.world == 4)) {
if (!m.fuse_ar)
rad_note(b, "residual junctions: the all-reduce in front of each issued apart");
else if (g.world == 4)
rad_note(b, "residual junctions: the all-reduce in front of each folded in at steps of "
"%lld rows or fewer (the four-rank one-shot), issued apart above",
(long long)m.ar_rows);
else
rad_note(b, "residual junctions: the all-reduce in front of each folded in");
}
return RAD_OK; return RAD_OK;
} }
@@ -1420,15 +1458,17 @@ static void step(RadCtx* c, const RadBatch* batch) {
const int64_t T = batch->n_tok; const int64_t T = batch->n_tok;
if (m.fuse) m.j0.step(c, T); if (m.fuse) m.j0.step(c, T);
/* the junctions carry the reductions in front of them in a step their fold serves */
const bool far = m.fuse_ar && T <= m.ar_rows;
for (size_t li = 0; li < m.layers.size(); ++li) { for (size_t li = 0; li < m.layers.size(); ++li) {
const Layer& l = m.layers[li]; const Layer& l = m.layers[li];
const bool last = li + 1 == m.layers.size(); const bool last = li + 1 == m.layers.size();
l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar); l.attn.step(c, batch, m.fuse, m.fuse, far);
if (m.fuse) l.j_am.step(c, T, m.fuse_ar); if (m.fuse) l.j_am.step(c, T, far);
l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar); l.mlp.step(c, batch, m.fuse, m.fuse && !last, far);
if (m.fuse && !last) { if (m.fuse && !last) {
/* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */
l.j_ma.step(c, T, m.fuse_ar); l.j_ma.step(c, T, far);
continue; continue;
} }
/* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the
+13
View File
@@ -698,6 +698,19 @@ the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits
proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the
copy the head reads the bf16 table, and the startup note names which head is in use. copy the head reads the bf16 table, and the startup note names which head is in use.
**The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front
of it (`ar_rmsnorm_quant_i8`). At four it does too, at decode heights. libr4d's
`ar_rmsnorm_quant_i8_4rank` is the exact four-rank one-shot with the junction as its epilogue,
byte-identical to `all_reduce` + `rmsnorm_quant_i8`. A one-shot sends three times the message per
rank, so the plugin declares it only up to 4 rows and issues the pair in a taller step. On 4x
R9700 the fold made plain decode 5.6% faster (94 against 89 tok/s) and a DFlash verify (16 rows)
9% slower (276 against 300), where the standalone all-reduce is the exact two-shot. A decode step
at tp 4 then has two standalone reductions (the embedding's and the last feed-forward's) where it
had 121. It gives the pair's greedy text byte for byte. At sixteen rows of 5376 the junction is
55 us against 22 at one row (--profile-ops): its handshakes, not its bytes, set it.
`r4d_selftest --case ar_rmsnorm_quant_i8_4rank` checks it on four cards, and the startup note says
which form a deployment takes.
**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the **FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the
container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up
`[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped `[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped
+8
View File
@@ -2122,6 +2122,14 @@ so the gather half writes `y` before it is reduced in place, and the five gather
mean what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On either wire it is byte-identical mean what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On either wire it is byte-identical
to the three kernels it replaces. to the three kernels it replaces.
`ar_rmsnorm_quant_i8` is the exact `all_reduce` of `x` followed by `rmsnorm_quant_i8`'s junction
over the reduced sum, at two ranks and at four. At four it is the exact one-shot's transport with
the junction as its epilogue: a block owns whole rows, and the fold is element by element in the
norm's partition, each element the one-shot's arithmetic (fp32 from zero, ascending rank order,
one rounding to bf16), so it is byte-identical to `all_reduce` + `rmsnorm_quant_i8`. A one-shot
sends (ranks - 1) times the message a rank, so it is for decode heights; above them a caller
issues the pair, whose `all_reduce` goes two-shot.
## Vocabulary edges ## Vocabulary edges
| op | params | operands | | op | params | operands |
+4
View File
@@ -223,6 +223,10 @@ add_executable(r4d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r4d_selftest.cpp)
target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME}) target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Installed beside the tools, so the image can run the rows' own card checks without a build tree:
# r4d_selftest /opt/radiance/share/radiance/kernels/libr4d.so [--case <row>]
# The collective cases need every card of the box in the container.
install(TARGETS r4d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# C++17: at C++20 clang tightens the address-space check on # C++17: at C++20 clang tightens the address-space check on
# __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17. # __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17.
+11
View File
@@ -747,6 +747,17 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq); int drain, int acq);
// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC
// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, and
// the engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h).
int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2,
long peer_flags0, long peer_flags1, long peer_flags2,
long my_scratch, long my_flags, long seq_ctrs,
long slot_stride16, long x, long res, long w, long wp, long sc,
int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, int rank,
long stream, int nblocks, int drain, int acq, int pub,
long gate, long gate_ctr);
// ---- sampling ---------------------------------------------------------------------------------- // ---- sampling ----------------------------------------------------------------------------------
// //
+80 -21
View File
@@ -602,11 +602,11 @@ extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int
return ar_ln_init(p, n_p, rank, world, 1, out); return ar_ln_init(p, n_p, rank, world, 1, out);
} }
/* The four-rank ar_hc_write and ar_gather_hc_write. The key is {rank, 4, bf16, M_hi * n}, shared /* The four-rank ar_hc_write, ar_gather_hc_write and ar_rmsnorm_quant_i8 (the norm declares no
* with a standalone all_reduce band only where the bounds agree. Either way is safe on one stream: * `wire`). The key is {rank, 4, bf16, M_hi * n}, shared with a standalone all_reduce band only where
* every wide kernel advances the instance's seq counters once per all-reduce and writes only its * the bounds agree. Either way is safe on one stream: every wide kernel advances the instance's seq
* (parity, source) slot (r4d_ar_wide.h), so ops on one instance interleave in any order all ranks * counters once per all-reduce and writes only its (parity, source) slot (r4d_ar_wide.h), so ops on
* share. Exact wire only; `wire` 6 is refused. */ * one instance interleave in any order all ranks share. Exact wire only; `wire` 6 is refused. */
static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host, static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host,
void** out) { void** out) {
if (!out) return RAD_E_INVAL; if (!out) return RAD_E_INVAL;
@@ -1345,18 +1345,22 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
* all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */ * all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */
enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC }; enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC };
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { /* The operands and their rules, the same at every width. */
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); struct ArQ8Args {
if (!in) return RAD_E_STATE; const RadTensor *x = nullptr, *rs = nullptr, *w = nullptr, *q = nullptr, *sc = nullptr;
if (in->world != 2) return RAD_E_SHAPE; const RadTensor *ob = nullptr, *wp = nullptr, *sl = nullptr;
const RadTensor* x = r4d_opt(a, AQ8_X); long long M = 0, K = 0, yp = 0, rp = 0;
const RadTensor* rs = r4d_opt(a, AQ8_RES); };
const RadTensor* w = r4d_opt(a, AQ8_W);
const RadTensor* q = r4d_opt(a, AQ8_Q); static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) {
const RadTensor* sc = r4d_opt(a, AQ8_S); const RadTensor* x = o->x = r4d_opt(a, AQ8_X);
const RadTensor* ob = r4d_opt(a, AQ8_Y); const RadTensor* rs = o->rs = r4d_opt(a, AQ8_RES);
const RadTensor* wp = r4d_opt(a, AQ8_WP); const RadTensor* w = o->w = r4d_opt(a, AQ8_W);
const RadTensor* sl = r4d_opt(a, AQ8_SC); const RadTensor* q = o->q = r4d_opt(a, AQ8_Q);
const RadTensor* sc = o->sc = r4d_opt(a, AQ8_S);
const RadTensor* ob = o->ob = r4d_opt(a, AQ8_Y);
const RadTensor* wp = o->wp = r4d_opt(a, AQ8_WP);
const RadTensor* sl = o->sl = r4d_opt(a, AQ8_SC);
if (!x || !w || !q || !sc) return RAD_E_INVAL; if (!x || !w || !q || !sc) return RAD_E_INVAL;
if ((wp || sl) && !rs) return RAD_E_INVAL; if ((wp || sl) && !rs) return RAD_E_INVAL;
if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE; if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE;
@@ -1375,6 +1379,18 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0; const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */ if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */
if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL; if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL;
o->M = M; o->K = K; o->yp = yp; o->rp = rp;
return RAD_OK;
}
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
ArQ8Args v;
const int arc = ar_q8_args(a, in, &v);
if (arc != RAD_OK) return arc;
const long long M = v.M, K = v.K;
R4dArCfg cfgv; R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv); r4d_cfg_ar(a, &cfgv);
@@ -1385,13 +1401,56 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
if (nblocks < 1) nblocks = 1; if (nblocks < 1) nblocks = 1;
const int e = r4d_ar_rmsnorm_quant_i8( const int e = r4d_ar_rmsnorm_quant_i8(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(wp), r4d_addr(sl), in->slot16, r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl),
sl ? (sl->dtype == RAD_F32) : 0, r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), w->dtype == RAD_F32, (int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
(int)rp, (int)yp, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq); v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain,
cfgv.acq);
return e == 0 ? RAD_OK : RAD_E_SHAPE; return e == 0 ? RAD_OK : RAD_E_SHAPE;
} }
/* The same at four ranks, on the wide family's one-shot transport (r4d_rmsnorm_quant_i8.hip's
* ar_rmsnorm_quant_i8_wide_kernel), the one ar_hc_write_4rank rides, with the junction as its
* epilogue. The operands and the norm's width are the two-rank form's. The block count is one per
* row, capped by the wide family's flag array in the launcher and by the instance here. The
* instance is the four-rank family's {rank, 4, bf16, M_hi * n} (ar_hc_wide_init), so it is a
* standalone all_reduce band's where the two bounds agree, which is safe on one stream for the
* reason that init gives. The plugin issues it only at one-shot heights: each rank sends three
* times the message, which the two-shot the standalone takes above them does not. */
extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 4) return RAD_E_SHAPE;
if (in->dtype != 0) return RAD_E_DTYPE;
ArQ8Args v;
const int arc = ar_q8_args(a, in, &v);
if (arc != RAD_OK) return arc;
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
/* The fence-free forms rest on fine-grained P2P scratch and a store drain; the host mailbox
* (pinned host memory, cached on the way) keeps both fences. */
if (in->host || cfgv.drain != 3) {
if (cfgv.pub == 2) cfgv.pub = 1;
if (cfgv.acq == 2) cfgv.acq = 0;
}
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)v.M;
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
/* One handshake, the junction after it local: the release is the one-shot's. */
const long gate = link_gate(a), early = in->host ? 0L : gate;
const int e = r4d_ar_rmsnorm_quant_i8_4rank(
in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
in->peer_flags[0], in->peer_flags[1], in->peer_flags[2],
in->my_scratch, in->my_flags, in->my_seq, in->slot16,
r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl),
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc),
(int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks,
cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L);
if (e != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* The all-reduce with the gated residual write: `all_reduce` of `y`, then `hc_write` of the reduced /* The all-reduce with the gated residual write: `all_reduce` of `y`, then `hc_write` of the reduced
* `y` into `h`, in one kernel. A block whose output feeds a hyper-connection write skips its own * `y` into `h`, in one kernel. A block whose output feeds a hyper-connection write skips its own
* collective when this runs. * collective when this runs.
+13 -2
View File
@@ -54,7 +54,9 @@ __device__ __forceinline__ void r4d_ar_drain(int drain) {
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
} }
// acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system, // acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system,
// 2 none -- fine-grained scratch only. // 2 none -- fine-grained scratch only. Every thread of the block runs it after the handshake, so at
// 0 or 1 that is one system-scope invalidate a wave. The P2P scratch is fine-grained (the reads
// bypass L2; r4d_ar_entry.hip's allocation says why), so 2 is the documented design there.
__device__ __forceinline__ void r4d_ar_acquire(int acq) { __device__ __forceinline__ void r4d_ar_acquire(int acq) {
if (acq == 1) __threadfence_system(); if (acq == 1) __threadfence_system();
else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
@@ -74,7 +76,16 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>
const int tid = threadIdx.x; const int tid = threadIdx.x;
if (tid == 0) { if (tid == 0) {
if (drain == 2) __threadfence_system(); if (drain == 2) __threadfence_system();
if (pub) { if (pub == 2) {
// No release fence: the flags go out behind the data with nothing written back. Meant for
// a P2P instance with drain 3, on the reasoning that fine-grained scratch stores reach past
// L2. They do not: on 4x R9700 the readers saw stale scratch on nearly every element
// (r4d_selftest, 2026-10-17), so no tuned point selects pub 2 (tArQ84); it is kept only
// as the measured negative.
#pragma unroll
for (int p = 0; p < NPEERS; ++p)
r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
} else if (pub) {
// One system writeback for the whole publish, then relaxed stores. Per-peer release stores // One system writeback for the whole publish, then relaxed stores. Per-peer release stores
// would add writebacks that order nothing, since the flags go to different peers. // would add writebacks that order nothing, since the flags go to different peers.
__builtin_amdgcn_fence(__ATOMIC_RELEASE, ""); __builtin_amdgcn_fence(__ATOMIC_RELEASE, "");
+1
View File
@@ -461,6 +461,7 @@ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream);
+174
View File
@@ -33,6 +33,7 @@
#include "r4d_emit.h" #include "r4d_emit.h"
#include "r4d_common.h" #include "r4d_common.h"
#include "r4d_ar_seq.h" #include "r4d_ar_seq.h"
#include "r4d_ar_wide.h"
#include <cstdint> #include <cstdint>
namespace { namespace {
@@ -223,6 +224,97 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
} }
} }
// ---------------------------------------------------------------------------------------------
// The same junction with the four-rank all-reduce in front: the wide family's exact one-shot
// (r4d_ar_oneshot_Nrank_exact.hip) with the junction as its epilogue, as ar_hc_write_4rank is that
// one-shot with hc_write. Up to the reduce it is that one-shot's transport step for step (the same
// seq take over R4D_AR_WIDE_MAX_BLOCKS counters, the same handshake value 2*s, the same (parity,
// source) slots), so it shares an instance with the standalone all_reduce on one stream
// (r4d_ar_wide.h). Two things differ, both for the junction:
//
// * A block owns whole rows, the two-rank fused form's partition, since a post-norm's sum of
// squares closes over one row. Every rank runs the same grid over the same M, so block b's
// words are the same words on every rank and the per-block handshake pairs them.
// * The reduce is element by element in the norm's partition (thread t folds columns t, t+THR,
// ...), so the post-norm's sum of squares is the standalone norm's. Each element is ar_vsum's
// arithmetic exactly: fp32 from 0.0f, the ranks in ascending order, one rounding to bf16 as the
// __hip_bfloat16 cast rounds (bf16_hi_rne_nan). So the reduced row is the standalone exact
// all-reduce's to the bit, and what follows is rmsnorm_quant_i8's junction over it.
//
// In place is safe for the reason the hc_write form gives: a thread reads every source of an element
// before it stores it, its block pushed that element to every peer before the handshake, and no peer
// reads this rank's `x`.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, int WS>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
R4DArWidePeers<int4, WS - 1> peers, const int4* __restrict__ my_base,
unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n,
float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int drain,
int acq, int pub, long long* gate, unsigned int* gate_ctr) {
constexpr int NPEERS = WS - 1;
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
__shared__ unsigned int s_seq, s_slot;
const int b = (int)blockIdx.x, nb = (int)gridDim.x;
const uint32_t tid = threadIdx.x;
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
const long long gate_word = r4d_ar_link_word(gate, tid);
r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); /* device-resident, replay-safe */
const unsigned int s = s_seq;
const int parity = (int)s_slot;
/* push my rows into every peer's (parity, my rank) slot; `x` is a tight [M][n] of bf16 */
int4* ps[NPEERS];
#pragma unroll
for (int p = 0; p < NPEERS; ++p)
ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16;
const int wpr = (int)(n >> 3);
const int4* const in4 = (const int4*)x;
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) {
const int4 v = in4[k];
#pragma unroll
for (int p = 0; p < NPEERS; ++p) ps[p][k] = v;
}
r4d_ar_handshake<WS>(peers, my_flags, b, rank, 2u * s, drain, acq, pub);
/* The one-shot's release: the fold and the junction behind it are local VRAM traffic, so the
* last block past its handshake ends the engine's hold on the link (r4d_ar_seq.h). Every block
* owns at least one row and takes exactly one handshake, so every path reaches it. */
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, tid);
/* the sources in ascending global rank, this rank's own from `x` (its own slot is never
* written), the peers' from their slots in my scratch */
const uint16_t* src[WS];
#pragma unroll
for (int r = 0; r < WS; ++r)
src[r] = r == rank ? (const uint16_t*)x
: (const uint16_t*)(my_base + ((size_t)parity * WS + r) *
(size_t)slot_stride16);
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
for (int row = r0; row < r1; ++row) {
const size_t o = (size_t)row * n;
uint16_t* __restrict__ xr = x + o;
float ss = 0.0f;
for (uint32_t i = tid; i < n; i += THR) {
float acc = 0.0f;
#pragma unroll
for (int r = 0; r < WS; ++r) acc += bf2f(src[r][o + i]);
const uint16_t a = (uint16_t)(bf16_hi_rne_nan(acc) >> 16);
xr[i] = a;
if (POST) { const float v = bf2f(a); ss += v * v; }
}
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
junction_row<WF32, RES, POST, SCL, THR>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row,
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm);
__syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */
}
}
} // namespace } // namespace
// ============================================================== the plugin ABI entry point // ============================================================== the plugin ABI entry point
@@ -350,3 +442,85 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
#undef R4D_ARQ8_T #undef R4D_ARQ8_T
return hipGetLastError() == hipSuccess ? 0 : -4; return hipGetLastError() == hipSuccess ? 0 : -4;
} }
// The four-rank form's launch. The IPC arguments are r4d_ar_oneshot_4rank_exact's -- each peer's
// scratch and flags in ascending peer rank, this rank's own, the device-resident sequence counters
// and the per-source slot stride -- and the rest is the junction's. The checks are the wide
// launchers' (rank range, the message inside one slot, the grid inside the flag array, every
// allocation's extent), returned as codes rather than thrown, for the reason this file gives.
extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1,
long peer_scratch2, long peer_flags0,
long peer_flags1, long peer_flags2, long my_scratch,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long wp, long sc,
int sc_f32, long y, long q, long s, int M, int n,
float eps, float wadd, int w_f32, int r_ld, int y_ld,
int rank, long stream, int nblocks, int drain, int acq,
int pub, long gate, long gate_ctr) {
constexpr int WS = 4, NPEERS = WS - 1;
const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 };
const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 };
if (!x || !w || !q || !s) return -1;
if (!my_scratch || !my_flags || !seq_ctrs) return -1;
if (gate && !gate_ctr) return -1; /* the release counts blocks in the instance's counter */
if (rank < 0 || rank >= WS) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 16) return -3;
if ((wp || sc) && !res) return -5;
if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6;
if ((long)M * n / 8 > slot_stride16) return -7; /* the message inside one source slot */
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
R4DArWidePeers<int4, NPEERS> peers{};
for (int i = 0; i < NPEERS; ++i) {
if (!ps[i] || !pf[i]) return -1;
peers.scratch[i] = (int4*)ps[i];
peers.flags[i] = (unsigned int*)pf[i];
peers.rank[i] = i < rank ? i : i + 1; /* ascending global rank, this one removed */
}
int nb = nblocks < 1 ? 1 : nblocks;
if (nb > M) nb = M; /* a block owns whole rows */
if (nb > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_AR_WIDE_MAX_BLOCKS;
try {
const long slot_bytes = 2L * WS * slot_stride16 * 16;
const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int);
r4d_ar_check_extent(my_scratch, slot_bytes, "ar_rmsnorm_quant_i8", "my_scratch");
r4d_ar_check_extent(my_flags, flag_bytes, "ar_rmsnorm_quant_i8", "my_flags");
r4d_ar_check_extent(seq_ctrs, 2L * R4D_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int),
"ar_rmsnorm_quant_i8", "seq_ctrs");
for (int i = 0; i < NPEERS; ++i) {
r4d_ar_check_extent(ps[i], slot_bytes, "ar_rmsnorm_quant_i8", "peer scratch");
r4d_ar_check_extent(pf[i], flag_bytes, "ar_rmsnorm_quant_i8", "peer flags");
}
} catch (...) {
return -8;
}
const int thr = r4d_act_threads(M, n);
const size_t lds = (size_t)n * sizeof(uint16_t);
#define R4D_ARQ8W_T(WF, RS, PO, SC, T) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_wide_kernel<WF, RS, PO, SC, T, WS>), dim3((uint32_t)nb), \
dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \
(const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(signed char*)q, (float*)s, (uint16_t*)y, peers, (const int4*)my_scratch, \
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, drain, acq, \
pub, (long long*)gate, (unsigned int*)gate_ctr)
#define R4D_ARQ8W(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_ARQ8W_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_ARQ8W_T(WF, RS, PO, SC, 512); \
else R4D_ARQ8W_T(WF, RS, PO, SC, 256); } while (0)
#define R4D_ARQ8W_W(WF) \
do { if (!res) R4D_ARQ8W(WF, false, false, false); \
else if (!wp && !sc) R4D_ARQ8W(WF, true, false, false); \
else if (wp && !sc) R4D_ARQ8W(WF, true, true, false); \
else if (wp && sc) R4D_ARQ8W(WF, true, true, true); \
else R4D_ARQ8W(WF, true, false, true); } while (0)
if (w_f32) R4D_ARQ8W_W(true);
else R4D_ARQ8W_W(false);
#undef R4D_ARQ8W_W
#undef R4D_ARQ8W
#undef R4D_ARQ8W_T
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+49 -3
View File
@@ -3080,7 +3080,7 @@ static const RadOpSchema kSchemas[] = {
"gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in " "gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in "
"one pass."), "one pass."),
SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8, SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8,
"the two-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."), "the two- or four-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."),
SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."), "silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."),
SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
@@ -4452,6 +4452,10 @@ static const RadConstraint cGeluMulQuantI8[] = {
static const RadConstraint cArRmsNormQuantI8[] = { static const RadConstraint cArRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P, C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P,
}; };
/* The same at four ranks, on the wide family's transport. */
static const RadConstraint cArRmsNormQuantI84[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 4), C_P2P,
};
static const RadConstraint cHadQuantActI8[] = { static const RadConstraint cHadQuantActI8[] = {
C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"),
}; };
@@ -4662,7 +4666,8 @@ static const RadTunable tAttnSplit[] = {
/* ------------------------------------------------------------------- all-reduce launch geometry /* ------------------------------------------------------------------- all-reduce launch geometry
* *
* Four independent axes of the handshake: nblocks, nthreads, drain and acq. (`pub` is 1 in every * Four independent axes of the handshake: nblocks, nthreads, drain and acq. (`pub` is 1 in every
* arm, a constant in r4d_ar_entry.hip.) nblocks 0 scales with the message and clamps; drain 3 is * arm but the four-rank junction's, tArQ84, where it is an axis.) nblocks 0 scales with the message
* and clamps; drain 3 is
* s_wait_storecnt, the correct wait for the fine-grained uncached IPC scratch. * s_wait_storecnt, the correct wait for the fine-grained uncached IPC scratch.
* *
* rad-tune cannot reach these rows: the two-rank kernels need a real peer over IPC and rad-tune * rad-tune cannot reach these rows: the two-rank kernels need a real peer over IPC and rad-tune
@@ -4683,6 +4688,28 @@ static const RadTunable tAr[] = {
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
}; };
/* The four-rank fused junction (ar_rmsnorm_quant_i8_4rank): tAr's axes, its own value sets.
* On 4x R9700 over PCIe P2P a junction costs about 22 us at one row of 5376 and 57 us at sixteen
* (--profile-ops): it is bound by its handshakes, not its bytes.
*
* Every block takes one handshake, a system-scope release by its first
* thread and a system-scope acquire by every wave. Both are needed: on 4x R9700 behind an EPYC
* root complex, dropping either (an acq 2 and a pub 2 that were here, r4d_selftest 2026-10-16 and
* -17) left the readers with stale scratch on nearly every element, so the peers' stores do not
* reach them past the writer's L2 without the writeback. What can move is how many handshakes a
* call takes: fewer blocks (2 or 4, each owning several rows) take fewer. The defaults are the
* forms that have run on cards; the others are for RADIANCE_TUNE until they have. None of them
* changes the result. */
static const int64_t kArQ84Nblocks[] = { 0, 2, 4, 8, 16, 24 };
static const int64_t kArQ84Acq[] = { 0, 1 };
static const int64_t kArQ84Pub[] = { 1 };
static const RadTunable tArQ84[] = {
{ "nblocks", kArQ84Nblocks, NELEM(kArQ84Nblocks), 0, "blocks in the grid. 0 = one a row, clamped" },
{ "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "unused: the norm's width sets the block for bit-exactness" },
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
{ "acq", kArQ84Acq, NELEM(kArQ84Acq), 0, "acquire after the flag read: 0 system invalidate a wave, 1 full fence" },
{ "pub", kArQ84Pub, NELEM(kArQ84Pub), 1, "release before the flag store: 1 one system writeback" },
};
/* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at /* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at
* TP4 (qwen4exp_fp8) runs each all-reduce of a 2048-row piece beside the other piece's MoE passes, * TP4 (qwen4exp_fp8) runs each all-reduce of a 2048-row piece beside the other piece's MoE passes,
* where the size-chosen 24 blocks hold a third of the card while they wait on the link. With every * where the size-chosen 24 blocks hold a third of the card while they wait on the link. With every
@@ -7563,6 +7590,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cArRmsNormQuantI8), ROW(tAr), nullptr, ROW(cArRmsNormQuantI8), ROW(tAr), nullptr,
r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 }, r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 },
/* Its arithmetic is the four-rank exact one-shot's fold followed by the two-rank form's junction,
* each the code those two run. r4d_selftest's case of the same name holds it byte for byte to
* all_reduce + rmsnorm_quant_i8 on a four-card box, and the engine to a decode step's text against
* a build that issues the pair. Both have run on cards that way (the 31B's fused junctions, and
* r4d_selftest on four R9700s). */
{ "ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8", "quant",
"the four-rank exact one-shot all-reduce and the junction after it -- post-norm of the reduced "
"sum, residual add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel",
"exactly 4 ranks; n a multiple of 16, x unpitched (it is the message); a block owns whole rows; "
"exact wire; one-shot, so (ranks - 1) x the message a rank -- for decode heights",
"bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum "
"rounded to bf16 as the standalone exact all-reduce stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cArRmsNormQuantI84), ROW(tArQ84), nullptr,
r4d_rad_ar_hc_wide_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8_4rank, nullptr, nullptr,
nullptr, nullptr },
{ "had_quant_act_i8", "had_quant_act_i8", "quant", { "had_quant_act_i8", "had_quant_act_i8", "quant",
"block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes "
"int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels " "int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels "
@@ -8783,6 +8827,7 @@ extern "C" int rad_kernel_collective(int i) {
r4d_rad_ar_oneshot_4rank_exact, r4d_rad_ar_twoshot_4rank_exact, r4d_rad_ar_oneshot_4rank_exact, r4d_rad_ar_twoshot_4rank_exact,
r4d_rad_ar_twoshot_4rank_ti8, r4d_rad_ar_gather_4rank, r4d_rad_ar_twoshot_4rank_ti8, r4d_rad_ar_gather_4rank,
r4d_rad_ar_hc_write_4rank, r4d_rad_ar_gather_hc_write_4rank, r4d_rad_ar_hc_write_4rank, r4d_rad_ar_gather_hc_write_4rank,
r4d_rad_ar_rmsnorm_quant_i8_4rank,
}; };
for (RadLaunchFn f : kReleasing) for (RadLaunchFn f : kReleasing)
if (k->launch == f) return 2; if (k->launch == f) return 2;
@@ -8862,7 +8907,8 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) {
out->nthreads = TUNE(a, tAr, "nthreads"); out->nthreads = TUNE(a, tAr, "nthreads");
out->drain = TUNE(a, tAr, "drain"); out->drain = TUNE(a, tAr, "drain");
out->acq = TUNE(a, tAr, "acq"); out->acq = TUNE(a, tAr, "acq");
out->pub = 1; /* not an axis; see the note at tAr */ /* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */
out->pub = TUNE(a, tArQ84, "pub");
} }
extern "C" void r4d_cfg_topk(const RadArgs* a, R4dTopkCfg* out) { extern "C" void r4d_cfg_topk(const RadArgs* a, R4dTopkCfg* out) {
out->rc = 0; /* derived from pt1 at issue; see the note at tTopk */ out->rc = 0; /* derived from pt1 at issue; see the note at tTopk */
+252
View File
@@ -22508,6 +22508,251 @@ static void ar_hc_write_case(const Plugin& pl, const std::vector<int>& devs, con
} }
} }
/* ------------------------------------------------------------------ the fused junction (ar_rmsnorm_quant_i8_4rank) */
/* The four-rank all-reduce with the sandwich-norm junction as its epilogue, against the chain it
* replaces: the exact all-reduce (ar_vsum's f32 ascending-rank fold rounded once to bf16, as
* ar_hc_write_case's oracle folds it), then the single-rank `rmsnorm_quant_i8` row over that sum on
* the first card. The fused row's epilogue is that row's device function, so the check is
* byte-exact on everything it leaves: the reduced x on every rank, the residual, the bf16 norm
* output, the codes and the per-row scales.
*
* Tensor parallel replicates the residual stream, so every rank gets the same one, and x is each
* rank's own partial sum. The three forms the single-rank check walks (the plain norm, the
* junction, the junction with its scalar) run at decode heights, at the one-shot limit of the 31B's
* width (97 rows of 5376, more rows than the wide family has blocks), and at the 26B's width.
*
* The scalar form is also launched as the engine launches a collective it holds the link for, with
* an odd `link_gate` word on each card (rad_abi.h, rad_kernel_collective): over P2P the row must
* end the hold itself, leaving the word even and returning RAD_LINK_ENDED, and through the host
* mailbox it must leave the word alone and return RAD_OK. */
struct ArQ8 {
const RadKernelInfo* row = nullptr;
int rank = 0, dev = 0;
int64_t M = 0, K = 0;
bool res = false, scal = false;
bool gated = false; /* hand the launch an odd `link_gate` word */
long long gate_after = -1; /* ...and what the launch left in it */
void* inst = nullptr;
int rc_init = RAD_E_STATE, rc_launch = RAD_OK;
const std::vector<uint16_t>* r_in = nullptr; /* the replicated residual, w and w_post */
const std::vector<uint16_t>* w = nullptr;
const std::vector<uint16_t>* wp = nullptr;
uint16_t sc = 0;
std::vector<uint16_t> x_in; /* this rank's partial sum */
std::vector<uint16_t> x_out, r_out, y_out; /* what it leaves behind */
std::vector<uint8_t> q_out;
std::vector<float> s_out;
};
static void ar_q8_worker(ArQ8* t) {
if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; }
const int64_t M = t->M, K = t->K;
std::vector<RadParam> ps = { PI("world_size", 4), PI("M", M), PI("n", K), PF("eps", 1e-6),
PS("dtype", "bf16"), PF("wadd", 0.0) };
t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, 4, &t->inst);
if (t->rc_init != RAD_OK) return;
/* Allocated here and not through dalloc, whose list four rank threads would race on. */
void* x = nullptr; void* r = nullptr; void* w = nullptr; void* wp = nullptr; void* sc = nullptr;
void* q = nullptr; void* s = nullptr; void* y = nullptr; void* gw = nullptr;
const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2;
const bool mem = hipMalloc(&x, xb) == hipSuccess && hipMalloc(&r, xb) == hipSuccess &&
hipMalloc(&w, wb) == hipSuccess && hipMalloc(&wp, wb) == hipSuccess &&
hipMalloc(&sc, 4) == hipSuccess && hipMalloc(&q, (size_t)(M * K)) == hipSuccess &&
hipMalloc(&s, (size_t)M * 4) == hipSuccess && hipMalloc(&y, xb) == hipSuccess &&
(!t->gated || hipMalloc(&gw, 8) == hipSuccess);
if (!mem) {
t->rc_launch = RAD_E_NOMEM;
} else {
/* The engine's hold, as the engine sets it: an odd word on this card for the launch. */
if (gw) {
const long long one = 1;
st_memcpy(gw, &one, 8, hipMemcpyHostToDevice);
ps.push_back(PI("link_gate", (long long)(uintptr_t)gw));
}
st_memcpy(x, t->x_in.data(), xb, hipMemcpyHostToDevice);
st_memcpy(r, t->r_in->data(), xb, hipMemcpyHostToDevice);
st_memcpy(w, t->w->data(), wb, hipMemcpyHostToDevice);
st_memcpy(wp, t->wp->data(), wb, hipMemcpyHostToDevice);
st_memcpy(sc, &t->sc, 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(x, RAD_BF16, { M, K }), T(r, RAD_BF16, { M, K }), T(w, RAD_BF16, { K }),
T(q, RAD_I8, { M, K }), T(s, RAD_F32, { M }), T(y, RAD_BF16, { M, K }),
T(wp, RAD_BF16, { K }), T(sc, RAD_BF16, { 1 }) };
if (!t->res) { absent(ts[1]); absent(ts[6]); }
if (!t->scal) absent(ts[7]);
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.instance = t->inst;
a.rank = t->rank;
a.world_size = 4;
t->rc_launch = t->row->launch(&a, nullptr);
st_stream_sync(nullptr);
t->x_out.resize((size_t)(M * K));
t->r_out.resize((size_t)(M * K));
t->y_out.resize((size_t)(M * K));
t->q_out.resize((size_t)(M * K));
t->s_out.resize((size_t)M);
st_memcpy(t->x_out.data(), x, xb, hipMemcpyDeviceToHost);
st_memcpy(t->r_out.data(), r, xb, hipMemcpyDeviceToHost);
st_memcpy(t->y_out.data(), y, xb, hipMemcpyDeviceToHost);
st_memcpy(t->q_out.data(), q, (size_t)(M * K), hipMemcpyDeviceToHost);
st_memcpy(t->s_out.data(), s, (size_t)M * 4, hipMemcpyDeviceToHost);
if (gw) st_memcpy(&t->gate_after, gw, 8, hipMemcpyDeviceToHost);
}
for (void* p : { x, r, w, wp, sc, q, s, y, gw }) if (p) st_free(p);
}
static bool nm_ends_with(const char* s, const char* tail) {
const size_t n = std::strlen(s), k = std::strlen(tail);
return n >= k && std::strcmp(s + n - k, tail) == 0;
}
static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<int>& devs,
const char* name) {
const RadKernelInfo* row = find(pl, name);
const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8");
if (!row || !rq) { ok(name, false, "row absent"); return; }
if ((int)devs.size() < 4) { skip(name, "needs 4 gfx1201 cards"); return; }
const int world = 4;
const bool host = nm_ends_with(name, "_host"); /* the mailbox twin leaves the hold alone */
struct Shape { int64_t M, K; };
const Shape shapes[] = { { 1, 5376 }, { 8, 5376 }, { 40, 5376 }, { 97, 5376 }, { 64, 2816 } };
const std::string nm(name);
for (const Shape& sh : shapes) {
const int64_t M = sh.M, K = sh.K;
std::vector<uint16_t> hr((size_t)(M * K)), hw((size_t)K), hp((size_t)K);
for (int64_t i = 0; i < M; ++i)
for (int64_t c = 0; c < K; ++c)
hr[(size_t)(i * K + c)] = h_to_bf16(0.019f * (float)((i * 13 + c * 29) % 67) - 0.6f);
for (int64_t c = 0; c < K; ++c) {
hw[(size_t)c] = h_to_bf16(0.004f * (float)((c * 19) % 51) - 0.1f);
hp[(size_t)c] = h_to_bf16(0.9f + 0.003f * (float)((c * 7) % 41));
}
const uint16_t hs = h_to_bf16(0.373f);
/* Each rank's partial sum, with per-group magnitudes an order apart and one outlier a row,
* as the single-rank check makes them, shifted by rank so the four differ. */
std::vector<std::vector<uint16_t>> hx((size_t)world, std::vector<uint16_t>((size_t)(M * K)));
for (int r = 0; r < world; ++r)
for (int64_t i = 0; i < M; ++i)
for (int64_t c = 0; c < K; ++c) {
const float m = std::ldexp(1.0f, (int)((c / 384) % 6) - 3);
const float v = m * (0.037f * (float)((i * 29 + c * 13 + r * 17) % 71) - 1.3f);
hx[(size_t)r][(size_t)(i * K + c)] =
h_to_bf16(c == (i * 37 + r * 11) % K ? v * 19.0f : v);
}
/* The fold: f32, ascending rank, rounded once. */
std::vector<uint16_t> xsum((size_t)(M * K));
for (int64_t i = 0; i < M * K; ++i) {
float acc = 0.0f;
for (int r = 0; r < world; ++r) acc += h_bf16(hx[(size_t)r][(size_t)i]);
xsum[(size_t)i] = h_to_bf16(acc);
}
for (const int form : { 0, 1, 2 }) { /* the plain norm, the junction, with the scalar */
const bool res = form > 0, scal = form == 2;
const std::string at = " M=" + std::to_string(M) + " n=" + std::to_string(K) +
(form == 0 ? ", plain" : form == 1 ? ", junction"
: ", junction with scalar");
/* The chain on the first card: rmsnorm_quant_i8 over the reduced sum. */
st_set_device(devs[0]);
const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2;
void* d_x = dalloc(xb); void* d_r = dalloc(xb); void* d_w = dalloc(wb);
void* d_p = dalloc(wb); void* d_sc = dalloc(4); void* d_q = dalloc((size_t)(M * K));
void* d_s = dalloc((size_t)M * 4); void* d_y = dalloc(xb);
if (!d_x || !d_r || !d_w || !d_p || !d_sc || !d_q || !d_s || !d_y) {
ok((nm + at + " alloc").c_str(), false, "hipMalloc failed");
return;
}
st_memcpy(d_x, xsum.data(), xb, hipMemcpyHostToDevice);
st_memcpy(d_r, hr.data(), xb, hipMemcpyHostToDevice);
st_memcpy(d_w, hw.data(), wb, hipMemcpyHostToDevice);
st_memcpy(d_p, hp.data(), wb, hipMemcpyHostToDevice);
st_memcpy(d_sc, &hs, 2, hipMemcpyHostToDevice);
const std::vector<RadParam> pn = { PI("M", M), PI("n", K), PF("eps", 1e-6),
PS("dtype", "bf16"), PF("wadd", 0.0) };
const int rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }),
res ? T(d_r, RAD_BF16, { M, K }) : T(nullptr, RAD_BF16, {}),
T(d_w, RAD_BF16, { K }), T(d_q, RAD_I8, { M, K }),
T(d_s, RAD_F32, { M }), T(d_y, RAD_BF16, { M, K }),
res ? T(d_p, RAD_BF16, { K }) : T(nullptr, RAD_BF16, {}),
scal ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) },
pn);
if (rc != RAD_OK) {
ok((nm + at + ": the single-rank chain").c_str(), false, "rc=" + std::to_string(rc));
continue;
}
std::vector<uint16_t> want_r((size_t)(M * K)), want_y((size_t)(M * K));
std::vector<uint8_t> want_q((size_t)(M * K));
std::vector<float> want_s((size_t)M);
st_memcpy(want_r.data(), d_r, xb, hipMemcpyDeviceToHost);
st_memcpy(want_y.data(), d_y, xb, hipMemcpyDeviceToHost);
st_memcpy(want_q.data(), d_q, (size_t)(M * K), hipMemcpyDeviceToHost);
st_memcpy(want_s.data(), d_s, (size_t)M * 4, hipMemcpyDeviceToHost);
std::vector<ArQ8> t((size_t)world);
std::vector<std::thread> th;
for (int r = 0; r < world; ++r) {
ArQ8& x = t[(size_t)r];
x.row = row; x.rank = r; x.dev = devs[(size_t)r];
x.M = M; x.K = K; x.res = res; x.scal = scal; x.gated = scal;
x.r_in = &hr; x.w = &hw; x.wp = &hp; x.sc = hs;
x.x_in = hx[(size_t)r];
th.emplace_back(ar_q8_worker, &x);
}
for (std::thread& x : th) x.join();
st_set_device(devs[0]);
bool up = true, ran = true;
std::string rcs;
const int want_rc = scal && !host ? RAD_LINK_ENDED : RAD_OK;
bool released = true;
for (const ArQ8& x : t) {
up = up && x.rc_init == RAD_OK; ran = ran && x.rc_launch == want_rc;
rcs += std::to_string(x.rc_init) + "/" + std::to_string(x.rc_launch) + " ";
if (scal) released = released && x.gate_after == (host ? 1 : 0);
}
ok((nm + at + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs);
if (!up) return;
ok((nm + at + " launch").c_str(), ran, "init/launch rc " + rcs + "(want " +
std::to_string(want_rc) + ")");
if (scal) {
std::string g;
for (const ArQ8& x : t) g += std::to_string(x.gate_after) + " ";
ok((nm + at + (host ? ": the mailbox twin leaves the engine's link hold alone"
: ": the launch ends the engine's link hold itself")).c_str(),
released, "link_gate words after the launch: " + g);
}
if (ran) {
int64_t bx = 0, br = 0, by = 0, bq = 0, bs = 0, nz = 0;
for (const ArQ8& x : t) {
for (int64_t i = 0; i < M * K; ++i) {
bx += x.x_out[(size_t)i] != xsum[(size_t)i];
if (res) br += x.r_out[(size_t)i] != want_r[(size_t)i];
by += x.y_out[(size_t)i] != want_y[(size_t)i];
bq += x.q_out[(size_t)i] != want_q[(size_t)i];
}
for (int64_t i = 0; i < M; ++i)
bs += std::memcmp(&x.s_out[(size_t)i], &want_s[(size_t)i], 4) != 0;
}
for (int64_t i = 0; i < M * K; ++i) nz += want_q[(size_t)i] != 0;
char d[200];
std::snprintf(d, sizeof d, "over four ranks: reduced x %lld, residual %lld, bf16 %lld, "
"codes %lld, scales %lld differ; %lld of %lld codes nonzero",
(long long)bx, (long long)br, (long long)by, (long long)bq,
(long long)bs, (long long)nz, (long long)(M * K));
ok((nm + at + ": every rank holds the bytes of the all-reduce and the "
"single-rank junction").c_str(),
bx == 0 && br == 0 && by == 0 && bq == 0 && bs == 0 && nz > M * K / 2, d);
}
if (row->fini) for (ArQ8& x : t) if (x.inst) row->fini(x.inst);
}
}
}
/* ------------------------------------------------------------------ the device sweep */ /* ------------------------------------------------------------------ the device sweep */
/* embed_lookup_q against a host gather of the same bytes, through the host side's own conversions. /* embed_lookup_q against a host gather of the same bytes, through the host side's own conversions.
@@ -25695,6 +25940,13 @@ static void device_phase(const Plugin& pl) {
} }
/* The wide rows at every width are dispatched above and skip themselves, naming the width /* The wide rows at every width are dispatched above and skip themselves, naming the width
* they need, on a box with fewer cards. */ * they need, on a box with fewer cards. */
/* The junction's fused all-reduce at four ranks, and its host twin. */
for (const char* n : { "ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8_4rank_host" }) {
if (!sel(n)) continue;
if (!g_case) std::printf("\ncross-rank, fused with the sandwich-norm junction\n");
std::printf(" %s\n", n);
ar_rmsnorm_quant_i8_wide_case(pl, devs, n);
}
auto skip_pair = [](const char* base, const char* why) { auto skip_pair = [](const char* base, const char* why) {
for (const std::string& n : { std::string(base), std::string(base) + "_host" }) for (const std::string& n : { std::string(base), std::string(base) + "_host" })
if (sel(n.c_str())) skip(n.c_str(), why); if (sel(n.c_str())) skip(n.c_str(), why);
+81
View File
@@ -6702,6 +6702,87 @@ TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) {
CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0); CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0);
} }
/* At four ranks the junctions carry their reductions at decode heights, in the same issue order as
* at two ranks (only the embedding's and the last layer's feed-forward reduction stand alone),
* through ar_rmsnorm_quant_i8 declared at world_size 4 up to 4 rows (kAr4FoldRows: where the fold
* still beats the pair, inside libr4d's one-shot band of 524288 / 5376 = 97). A taller step, a DFlash
* verify's 16 rows included, issues each reduction and its junction apart, and where no library
* declares the fold every step issues the pair. */
TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_decode_heights) {
const int L = 12;
std::vector<std::string> folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" };
std::vector<std::string> apart = folded;
for (int l = 0; l < L; ++l) {
const bool global = (l + 1) % 6 == 0;
for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); }
for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
"ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" })
folded.push_back(s);
for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q",
"all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8",
"gemm_nt_q", "all_reduce" })
apart.push_back(s);
if (l < L - 1) {
folded.push_back("ar_rmsnorm_quant_i8");
apart.push_back("rmsnorm_quant_i8");
} else {
for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) folded.push_back(s);
for (const char* s : { "rmsnorm", "add", "scale" }) apart.push_back(s);
}
}
for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) {
folded.push_back(s);
apart.push_back(s);
}
/* a decode step folds */
CHECK_EQ(join(gemma4_w4_step({}, 4)), join(folded));
auto declare4 = [](RadBuilder& b) {
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
b.encs = { { "attn_q.", w4 }, { "attn_k.", w4 }, { "attn_v.", w4 }, { "attn_o.", w4 },
{ "ffn_gate_up.", w4 }, { "ffn_down.", w4 } };
RadModelMeta meta = gemma4_meta();
RadBuildCtx ctx = build_ctx(0, 4);
return gemma4_bf16::declare(&b, &meta, &ctx);
};
RadBuilder b;
CHECK_OK(declare4(b));
CHECK(noted(b, "folded in at steps of 4 rows or fewer"));
auto fold_hi = [](const RadBuilder& bb, int* n) {
int64_t hi = -1;
*n = 0;
for (const auto& o : bb.ops) {
if (o.op != "ar_rmsnorm_quant_i8") continue;
++*n;
CHECK_EQ(pint(&o, "world_size"), 4);
for (const auto& p : o.p)
if (p.key == "M") hi = p.ihi;
}
return hi;
};
int n_ar = 0;
CHECK_EQ(fold_hi(b, &n_ar), 4);
CHECK_EQ(n_ar, 2 * L - 1);
/* a verify's height and a step past the one-shot's band both issue the pair */
const int32_t out[1] = { 127 };
for (int rows : { 16, 128 }) {
RadBatch tall = one_prompt(rows, out);
RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &tall;
gemma4_bf16::step(&c, &tall);
CHECK(c.step_fail.empty());
CHECK_EQ(join(issued_ops(b, c)), join(apart));
}
/* no library declares the fold: none declared, every step issues the pair */
RadBuilder off;
off.undeclared.insert("ar_rmsnorm_quant_i8");
CHECK_OK(declare4(off));
CHECK(noted(off, "issued apart"));
for (const auto& o : off.ops) CHECK(o.op != "ar_rmsnorm_quant_i8");
}
/* ==================================================================== the step lint, checked */ /* ==================================================================== the step lint, checked */
namespace { namespace {