diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 7b2cabbe..34c2ba87 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -563,10 +563,15 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai * 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. */ + * cross near 4-5 rows. From 5 rows libr4d's four-rank row takes its tail form instead (axis + * `tail`): the standalone two-shot with the junction run after it in the same launch, behind a + * card-local count, so the junction costs neither a handshake nor a launch. With it a DFlash2 + * verify (8 rows) folds and gains ~1% (348 / 258 / 187 / 516 against 345 / 255 / 185 / 511 tok/s, + * code / prose / story / long, 4x R9700; replies identical), where the one-shot fold there lost + * 6%. So the fold serves up to kAr4FoldRows rows, a z-lab DFlash verify's 16 included, and a + * taller step issues the pair. */ static constexpr int64_t kArOneShotElems = 524288; -static constexpr int64_t kAr4FoldRows = 4; +static constexpr int64_t kAr4FoldRows = 16; struct G4Junction { rad_op op = 0; diff --git a/docs/OPS.md b/docs/OPS.md index b8be4ef2..39bc6a0b 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2152,6 +2152,12 @@ one rounding to bf16), so it is byte-identical to `all_reduce` + `rmsnorm_quant_ 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. +From 5 to 32 rows (the `tail` axis, on by default) the four-rank row takes a third form: the +standalone exact two-shot over words, on the blocks the standalone `all_reduce` takes for that +message, with the junction as its tail -- one more block a row, which waits on a card-local count +of the transport blocks (no cross-card handshake), acquires, and runs `rmsnorm_quant_i8`'s row at +its own width. The bytes are the pair's; the launch the junction would take is saved. + ## Vocabulary edges | op | params | operands | diff --git a/libr4d/r4d.h b/libr4d/r4d.h index e62ee672..d414dea5 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -766,8 +766,10 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, 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). +// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the +// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with +// `tail_nbt` blocks (positive), the standalone two-shot on that many with the junction as its tail, +// counting on the two words at `tail_ctr` (ar_rmsnorm_quant_i8_tail_kernel). 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, @@ -775,7 +777,7 @@ int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long 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); + long gate, long gate_ctr, long tail_ctr, int tail_nbt); // ---- sampling ---------------------------------------------------------------------------------- // diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index f735b5b9..aeb48aa0 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -399,7 +399,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, * changes: kernels touch other ranks only through those two, so no card addresses another's * VRAM. A message then crosses two links instead of one; only rows requiring device.p2p == 0 * take this path (r4d_rows.cpp). Sequence counters stay in VRAM, since only their own rank - * reads them. */ + * reads them, and coarse-grained: only this rank's kernels touch them, with device- and + * agent-scope atomics, which then complete in L2 rather than past it -- the first returning + * atomic of every launch (r4d_ar_seq_take) is on the push's path. */ R4D_TRY("ar_ipc_alloc", if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (host) { @@ -409,7 +411,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); } - sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen)); + sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); /* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly * the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half @@ -665,6 +667,22 @@ static int nb_for(long words16, int max_nb) { return (int)nb; } +/* The four-rank exact one-shot's two-shot band (r4d_rad_ar_oneshot_4rank_exact from ts_min), over + * the words of one shard: one block per 672 words, floor 2, + * ceiling max_nb. A two-shot takes two handshakes, each a PCIe round trip a block, so small shards + * want fewer blocks than nb_for's floor of 4: at a DFlash2 verify's 8 rows of 5376 at tp 4 (1344 + * words a shard) two blocks run the exact two-shot in 20.2 us against 22.8 at four, and from 16 + * rows (2688 words, four blocks either way) the two rules agree (4x R9700, a four-card + * microbenchmark of this kernel, 2026-10-17). The block count moves no byte: every word is folded + * by one thread in ascending rank order whatever the grid. */ +static int nb_for_shard(long shard16, int max_nb) { + long nb = shard16 / 672; + if (nb < 2) nb = 2; + if (nb > max_nb) nb = max_nb; + if (nb > shard16) nb = shard16 > 0 ? shard16 : 1; + return (int)nb; +} + /* Shared front half of every all-reduce launch: find the instance, check the message against * init's sizing, resolve the tuned point. Every kernel of the family is safe in place (`y` absent * or equal to `x`); each entry point says why. */ @@ -959,6 +977,31 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; const ArInst* in = c.in; + /* From `ts_min` elements, the exact two-shot on this instance: the same fold per element, so + * the same bytes, for half the bytes a rank (a 16-row verify's message, 516 KiB a card at + * 3x, is what the link waits on). It shares the wide family's flags, counters and slots, and + * a shard pair fits any slot that holds the whole message. */ + const long ts_min = r4d_cfg_ar_ts_min(a); + const long words16 = c.numel * in->esize / 16; + if (ts_min > 0 && c.numel >= ts_min && words16 % in->world == 0 && + 2 * (c.numel * in->esize) / in->world <= in->slot_bytes && + c.numel <= R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) { + R4dArCfg cfgv; + r4d_cfg_ar(a, &cfgv); + int nb = cfgv.nblocks > 0 ? cfgv.nblocks + : nb_for_shard(words16 / in->world, + in->nb_cap > 24 ? 24 : in->nb_cap); + if (nb > in->max_blocks) nb = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; + R4D_TRY("ar_oneshot_4rank_exact (two-shot)", + r4d_ar_twoshot_4rank_exact(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, + c.inp, c.out, c.numel, in->dtype, in->rank, + (long)(uintptr_t)s, nb, c.nthreads, c.drain, c.acq, + c.pub, early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; + } /* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold * itself once the peers' pushes have landed (the kernel after the handshake is local VRAM * traffic); through the host mailbox the reduce reads the bytes across the link, so early @@ -1458,7 +1501,18 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) } 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. */ + /* Above one-shot heights (the plugin's fold band at 5 rows and up), the `tail` axis's form: + * the standalone two-shot over words on the blocks the standalone all_reduce would take for + * this message (nb_for_shard), with the junction as its tail; its two counters are words of the + * instance's zeroed sequence allocation past the landed counter (r4d_ar_seq.h). P2P only. */ + int tail_nbt = 0; + if (r4d_cfg_ar_tail(a) && v.M >= 5 && !in->host) { + const long words16 = (long)v.M * v.K / 8; + tail_nbt = nb_for_shard(words16 / in->world, in->nb_cap > 24 ? 24 : in->nb_cap); + if (tail_nbt > in->max_blocks) tail_nbt = in->max_blocks; + } + const long tail_ctr = in->my_seq + (2L * in->max_blocks + 8) * 4; + /* The junction after the last handshake is local, so either form releases there. */ 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], @@ -1468,7 +1522,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) 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); + cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt); if (e != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 7be88687..1d024781 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -357,6 +357,11 @@ void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*); void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*); void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*); void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*); +/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */ +int r4d_cfg_ar_tail(const RadArgs*); +/* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead + * (0: never); the all-reduce rows' `ts_min` axis. */ +long r4d_cfg_ar_ts_min(const RadArgs*); void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*); void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*); /* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 1fade643..707a644d 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -124,6 +124,30 @@ __device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) { return f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]); } +// The exact all-reduce's fold of one 16-byte word (eight bf16): every source's word loaded first, +// then per element fp32 from 0.0f, the sources in ascending rank, one rounding through +// bf16_hi_rne_nan -- ar_vsum's arithmetic, so the word is the standalone exact all-reduce's. +template +__device__ __forceinline__ int4 fold_word8(const int4* const* src4, size_t k) { + int4 v[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) v[r] = src4[r][k]; + float acc[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const uint16_t* pv = reinterpret_cast(&v[r]); +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += bf2f(pv[j]); + } + int4 a; + uint16_t* pa = reinterpret_cast(&a); +#pragma unroll + for (int j = 0; j < 8; ++j) pa[j] = (uint16_t)(bf16_hi_rne_nan(acc[j]) >> 16); + return a; +} + template __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, @@ -157,19 +181,14 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( // t takes columns t, t+THR, ...), so each thread keeps its own columns in registers and none needs // another's; only the fragment-order store crosses threads, through `ybuf` as before. The sums, // the order they are taken in and every element's arithmetic are junction_row's, so the bytes are. +// One row of it, for this kernel and for the all-reduce's tail (ar_rmsnorm_quant_i8_tail_kernel). template -__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( - const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, +__device__ __forceinline__ void junction_reg_row( + const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, 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, - uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { - extern __shared__ uint16_t ybuf[]; - __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; - const uint32_t row = blockIdx.x, tid = threadIdx.x; - const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; - uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr; - uint16_t* __restrict__ yr = yo ? yo + (size_t)row * y_ld : nullptr; - + signed char* __restrict__ qr, float* __restrict__ Sr, uint16_t* __restrict__ yr, uint32_t n, + float eps, float wadd, uint16_t* ybuf, float* l1, float* l2, float* lm) { + const uint32_t tid = threadIdx.x; uint16_t xv[EPT], rv[EPT]; float gp[EPT], gw[EPT]; #pragma unroll @@ -235,10 +254,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]); const float scale = fmaxf(m, 1e-8f) / 127.f; const float inv = 1.f / scale; - if (tid == 0) S[row] = scale; + if (tid == 0) *Sr = scale; // ---- the codes, in junction_row's fragment order - signed char* __restrict__ qr = q + (size_t)row * n; for (uint32_t i = tid; i < n; i += THR) { const uint32_t s = i >> 4, j = i & 15; const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); @@ -247,6 +265,21 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( } } +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( + const 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, + uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + const uint32_t row = blockIdx.x; + junction_reg_row( + x + (size_t)row * x_ld, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf, + l1, l2, lm); +} + // --------------------------------------------------------------------------------------------- // The same junction with the two-rank all-reduce that precedes it: the branch output is a rank's // partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the whole @@ -256,6 +289,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( // commutes, so both ranks agree) during the post-norm's sum-of-squares pass. A block owns whole // rows, one per block at decode. #define R4D_ARQ8_SPIN_MAX 4000000000ULL +/* The all-reduce's tail form serves up to this many rows: a block a row beside the transport's, + * far under one block a CU on the cards it runs on. */ +#define R4D_ARQ8_TAIL_MAX_ROWS 32 __device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) { __hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); @@ -385,27 +421,30 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( /* 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]; + const int4* src4[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); + src4[r] = r == rank ? (const int4*)x + : 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; + /* The fold a 16-byte word a thread, every source's word in flight at once (the peers' are + * in fine-grained memory, a round trip each), stored back into `x`; then the post-norm's + * sum of squares over the stored row in the norm's partition. Per element it is the fold + * fold_word8 documents, and the sum reads the same rounded values in the same order, so + * the bytes are those of the fold and the sum taken in one pass. */ + for (int k = (int)tid; k < wpr; k += (int)THR) + ((int4*)xr)[k] = fold_word8(src4, (size_t)row * wpr + k); 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; } + if (POST) { + __syncthreads(); /* the folded row, read across the block's threads */ + for (uint32_t i = tid; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; } } float s1 = 0.0f; if (POST) s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + else __syncthreads(); /* junction_row reads the folded row across threads too */ junction_row( 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); @@ -413,6 +452,139 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( } } +// --------------------------------------------------------------------------------------------- +// --------------------------------------------------------------------------------------------- +// The junction as the tail of the standalone exact two-shot, in one launch. Blocks [0, nbt) run +// r4d_ar_twoshot_wide_exact_kernel's body over x in place (r4d_ar_twoshot_Nrank_exact.hip): the same +// shards, words, fold (fp32 from 0.0f in ascending rank, one rounding) and handshakes, so x ends as +// the standalone all-reduce leaves it; each then counts itself in on a word of the instance's +// counter allocation, at agent scope behind a release. Blocks [nbt, nbt + M) are the junction, one +// row each as rmsnorm_quant_i8_reg_kernel runs it (junction_reg_row, the same width and partition): +// each waits for every transport block's count, acquires, and runs its row; the last of them zeroes +// both counts for the next launch. So the junction takes neither a cross-card handshake nor a +// launch of its own: the pair's bytes, one dependent launch fewer. Blocks are dispatched in index +// order, so the transport blocks are resident before any junction block spins; the grid is kept far +// under one block a CU. +// +// tail[0] counts the transport blocks done, tail[1] the junction blocks done; both start at zero +// (the counter allocation is zeroed at init) and the last junction block returns them there. +template +__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_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 peers, const int4* __restrict__ my_base, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, + unsigned int* __restrict__ tail, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, + uint32_t y_ld, int slot_stride16, int rank, int nbt, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { + constexpr uint32_t THR = 1024; + 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, tid = (int)threadIdx.x, nt = (int)THR; + + if (b < nbt) { + // ---- the standalone exact two-shot, x in place, block b of nbt + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); + const unsigned int s = s_seq; + const int parity = (int)s_slot; + int4* const x4 = (int4*)x; + const int n16 = (int)(((long)M * n) >> 3); + const int base = n16 / WS, rem = n16 % WS; + const int sh_max = base + (rem ? 1 : 0); +#define R4D_TT_OFF(o) ((o) * base + ((o) < rem ? (o) : rem)) +#define R4D_TT_LEN(o) (base + ((o) < rem ? 1 : 0)) + const int wd = (sh_max + nbt - 1) / nbt; + const int w0 = b * wd; + int w1 = w0 + wd; if (w1 > sh_max) w1 = sh_max; + int4* pa[NPEERS]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + pa[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* src = x4 + (size_t)R4D_TT_OFF(owner); + int4* dst = pa[p]; + const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner); + for (int k = w0 + tid; k < lim; k += nt) dst[k] = src[k]; + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); + const int4* src[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + src[r] = (r == rank) ? (x4 + (size_t)R4D_TT_OFF(rank)) + : (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16); + int4* my_out = x4 + (size_t)R4D_TT_OFF(rank); + const int my_lim = w1 < R4D_TT_LEN(rank) ? w1 : R4D_TT_LEN(rank); + for (int k = w0 + tid; k < my_lim; k += nt) { + float acc[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const int4 v = src[r][k]; + const __hip_bfloat16* pv = reinterpret_cast(&v); +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += r4d_ar_to_f(pv[j]); + } + int4 o; + __hip_bfloat16* po = reinterpret_cast<__hip_bfloat16*>(&o); +#pragma unroll + for (int j = 0; j < 8; ++j) r4d_ar_from_f(acc[j], po[j]); + my_out[k] = o; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nbt, (unsigned int)tid); + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* srcB = my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16 + sh_max; + int4* dst = x4 + (size_t)R4D_TT_OFF(owner); + const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner); + for (int k = w0 + tid; k < lim; k += nt) dst[k] = srcB[k]; + } +#undef R4D_TT_OFF +#undef R4D_TT_LEN + // ---- every word this block stored in x, published, then counted in + __syncthreads(); + if (tid == 0) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent"); + __hip_atomic_fetch_add(&tail[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + } + return; + } + + // ---- the junction, row b - nbt, once x is whole on this card + const int row = b - nbt; + if (tid == 0) { + unsigned long long z = 0; + while (__hip_atomic_load(&tail[0], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < + (unsigned int)nbt) { + __builtin_amdgcn_s_sleep(1); + if (++z > R4D_AR_SPIN_MAX) __builtin_trap(); + } + } + __syncthreads(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + junction_reg_row( + x + (size_t)row * n, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf, + l1, l2, lm); + __syncthreads(); + if (tid == 0) { + const unsigned int prev = + __hip_atomic_fetch_add(&tail[1], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + if (prev + 1u == (unsigned int)M) { + __hip_atomic_store(&tail[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __hip_atomic_store(&tail[1], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + } + } +} + } // namespace // ============================================================== the plugin ABI entry point @@ -559,6 +731,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long // 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. +// The all-reduce is the one-shot. With `tail_nbt` blocks (positive) it is instead the standalone two-shot over words on that many blocks with the junction as its tail, +// a block a row (ar_rmsnorm_quant_i8_tail_kernel), counting on the two words at `tail_ctr`. 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, @@ -567,7 +741,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat 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) { + int pub, long gate, long gate_ctr, + long tail_ctr, int tail_nbt) { 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 }; @@ -610,6 +785,50 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat const int thr = r4d_act_threads(M, n); const size_t lds = (size_t)n * sizeof(uint16_t); + + /* The junction as the standalone two-shot's tail (ar_rmsnorm_quant_i8_tail_kernel): at the + * junction's register width (1024 threads), up to R4D_ARQ8_TAIL_MAX_ROWS rows. */ + const int ept = n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0; + if (tail_nbt > 0 && tail_ctr && thr == 1024 && ept > 0 && M <= R4D_ARQ8_TAIL_MAX_ROWS && + tail_nbt <= R4D_AR_WIDE_MAX_BLOCKS) { + try { + r4d_ar_check_extent(my_flags, (long)tail_nbt * WS * (long)sizeof(unsigned int), + "ar_rmsnorm_quant_i8", "my_flags"); + r4d_ar_check_extent(tail_ctr, 2L * (long)sizeof(unsigned int), "ar_rmsnorm_quant_i8", + "tail counters"); + for (int i = 0; i < NPEERS; ++i) + r4d_ar_check_extent(pf[i], (long)tail_nbt * WS * (long)sizeof(unsigned int), + "ar_rmsnorm_quant_i8", "peer flags"); + } catch (...) { + return -8; + } +#define R4D_ARQ8T_K(WF, RS, PO, SC, E) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_i8_tail_kernel), \ + dim3((uint32_t)(tail_nbt + M)), dim3(1024), 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, (unsigned int*)tail_ctr, M, (uint32_t)n, eps, \ + wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, \ + tail_nbt, drain, acq, pub, (long long*)gate, (unsigned int*)gate_ctr) +#define R4D_ARQ8T_E(WF, RS, PO, SC) \ + do { if (ept == 4) R4D_ARQ8T_K(WF, RS, PO, SC, 4); \ + else if (ept == 6) R4D_ARQ8T_K(WF, RS, PO, SC, 6); \ + else R4D_ARQ8T_K(WF, RS, PO, SC, 8); } while (0) +#define R4D_ARQ8T_W(WF) \ + do { if (!res) R4D_ARQ8T_E(WF, false, false, false); \ + else if (!wp && !sc) R4D_ARQ8T_E(WF, true, false, false); \ + else if (wp && !sc) R4D_ARQ8T_E(WF, true, true, false); \ + else if (wp && sc) R4D_ARQ8T_E(WF, true, true, true); \ + else R4D_ARQ8T_E(WF, true, false, true); } while (0) + if (w_f32) R4D_ARQ8T_W(true); + else R4D_ARQ8T_W(false); +#undef R4D_ARQ8T_W +#undef R4D_ARQ8T_E +#undef R4D_ARQ8T_K + return hipGetLastError() == hipSuccess ? 0 : -4; + } + #define R4D_ARQ8W_T(WF, RS, PO, SC, T) \ hipLaunchKernelGGL((ar_rmsnorm_quant_i8_wide_kernel), dim3((uint32_t)nb), \ dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 67d2d63b..d64d8665 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4717,15 +4717,25 @@ static const RadTunable tAttnSplit[] = { * On the fp8 fused row only drain and acq apply: it forces `nthreads` to the norm's width for * bit-exactness, and pinning `nblocks` would undo r4d_ar_entry.hip's cap. No axis changes the * result. */ -static const int64_t kArNblocks[] = { 0, 8, 16, 24 }; +static const int64_t kArNblocks[] = { 0, 2, 4, 8, 16, 24 }; static const int64_t kArNthreads[] = { 256, 512, 1024 }; static const int64_t kArDrain[] = { 1, 3 }; static const int64_t kArAcq[] = { 0, 1 }; +/* `ts_min`: from this many elements the four-rank exact one-shot hands the message to the exact + * two-shot on the same instance (the same per-element fold, so the same bytes): a rank then sends + * 1.5x the message instead of 3x, for a second handshake. 32768 is about six rows of 5376, so an + * 8-row DFlash2 verify's all-reduces take the two-shot too (on 4x R9700, 2026-10-17: 297 -> 303 + * tok/s code, long decode 447 -> 460, against 65536 that kept them one-shot); a 16-row verify's + * already did. 0 keeps the one-shot to its band's top. Read only by that + * adapter; declared by every all-reduce table so one RADIANCE_TUNE=all_reduce:ts_min=N pin is legal + * for every row the op resolves to. */ +static const int64_t kArTsMin[] = { 0, 16384, 32768, 65536, 131072, 262144 }; static const RadTunable tAr[] = { { "nblocks", kArNblocks, NELEM(kArNblocks), 0, "blocks in the grid. 0 = scale with the message and clamp" }, { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block; the fused fp8 row overrides this for bit-exactness" }, { "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" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "elements from which the four-rank one-shot takes the exact two-shot; 0 = never" }, }; /* 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 @@ -4739,6 +4749,7 @@ static const RadTunable tAr[] = { * 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 kArQ84Tail[] = { 1, 0 }; static const int64_t kArQ84Nblocks[] = { 0, 2, 4, 8, 16, 24 }; static const int64_t kArQ84Acq[] = { 0, 1 }; static const int64_t kArQ84Pub[] = { 1 }; @@ -4748,6 +4759,7 @@ static const RadTunable tArQ84[] = { { "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" }, + { "tail", kArQ84Tail, NELEM(kArQ84Tail), 1, "from 5 to 32 rows: the standalone two-shot with the junction as its tail, a block a row (no handshake or launch of its own); 0 = the one-shot" }, }; /* 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, @@ -4759,6 +4771,7 @@ static const RadTunable tArTs4Lane[] = { { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block" }, { "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" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" }, }; /* The same axes with narrow defaults, for a collective issued beside compute (`overlap` 1). The * wide launch (up to 24 blocks of 1024 threads spinning on peer flags) suits an all-reduce that has @@ -4770,6 +4783,7 @@ static const RadTunable tArLane[] = { { "nthreads", kArNthreads, NELEM(kArNthreads), 256, "threads per block" }, { "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" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" }, }; /* --------------------------------------------------------------------------------- row top-k @@ -7686,7 +7700,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "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", + "exact wire; one-shot ((ranks - 1) x the message a rank) -- for decode heights; from 5 to 32 " + "rows (axis `tail`) the standalone two-shot with the junction as its tail", "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, @@ -9013,6 +9028,12 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { /* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */ out->pub = TUNE(a, tArQ84, "pub"); } +extern "C" int r4d_cfg_ar_tail(const RadArgs* a) { + return TUNE(a, tArQ84, "tail"); +} +extern "C" long r4d_cfg_ar_ts_min(const RadArgs* a) { + return (long)tune_i(a, tAr, NELEM(tAr), "ts_min"); +} 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->nch = TUNE(a, tTopk, "nch"); diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 227b8914..7b3ac961 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -21553,8 +21553,11 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons runs = { /* bf16: 524288 the one-shot band's top, 524352 the first message the two-shot's rows * take (numel % 64 == 0 either way, so both divide); the shipped chunk sizes; and - * 4194304 again to close the run on a size already folded. */ - { "bf16", { 4194304, 128, 524288, 524352, 4196352, 20971520, 46137344, 4194304 }, 2 }, + * 4194304 again to close the run on a size already folded. 86016, a 16-row verify at + * 5376, and 524288 are past the one-shot row's default ts_min, so that row hands them + * to the two-shot; 128 and 43008 (eight rows) stay on the one-shot. */ + { "bf16", { 4194304, 128, 43008, 86016, 524288, 524352, 4196352, 20971520, 46137344, + 4194304 }, 2 }, /* fp32: words = numel / 4, whole groups of four either side of the same edge. */ { "fp32", { 1048580 - 4, 524352 }, 0 }, }; @@ -22638,6 +22641,7 @@ struct ArQ8 { 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 */ + int tail = -1; /* the `tail` axis pinned, or -1: the default */ void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; const std::vector* r_in = nullptr; /* the replicated residual, w and w_post */ @@ -22657,6 +22661,8 @@ static void ar_q8_worker(ArQ8* t) { 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; + /* The tuned point arrives as a parameter of the launch, as the core appends it. */ + if (t->tail >= 0) ps.push_back(PI("tail", t->tail)); /* 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; @@ -22724,8 +22730,13 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector 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"); + : ", junction with scalar") + + (sh.tail ? ", two-shot with the junction as its tail" : ", one-shot"); /* The chain on the first card: rmsnorm_quant_i8 over the reduced sum. */ st_set_device(devs[0]); @@ -22805,6 +22817,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; @@ -4641,7 +4641,7 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ }; RadBuilder b; CHECK_OK(declare4(b)); - CHECK(noted(b, "folded in at steps of 4 rows or fewer")); + CHECK(noted(b, "folded in at steps of 16 rows or fewer")); auto fold_hi = [](const RadBuilder& bb, int* n) { int64_t hi = -1; *n = 0; @@ -4655,17 +4655,17 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ return hi; }; int n_ar = 0; - CHECK_EQ(fold_hi(b, &n_ar), 4); + CHECK_EQ(fold_hi(b, &n_ar), 16); CHECK_EQ(n_ar, 2 * L - 1); - /* a verify's height and a step past the one-shot's band both issue the pair */ + /* a verify's height folds (libr4d's tail form) and a step past 16 rows issues 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)); + CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded : apart)); }