Merge branch 'pr3-models' into pr4-tests

This commit is contained in:
C_Tamas committed 2026-10-25 17:19:53 +07:00
commit 0e953eb78b
49 files changed
+2104 -209

No files matched your search

+16 -2
View File
@@ -54,6 +54,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
| `gemm_mxfp4a8_gemv` | the same operands for one to eight rows: the weight streamed straight to registers, no LDS staging; WMMA when K is a multiple of 128, `v_dot4` otherwise, chosen from K alone so a row's bits do not depend on M |
| `gemm_mxfp4a8_gemv_wide` | its WMMA form at 9..64 rows: up to four 16-row tiles a wave over each weight word, two 16-column tiles a block on wide, deep weights |
| `gemm_mxfp4a8_gated_gemv` | `gemm_nt_q_gated_mx`: the gemv WMMA form over a gate_up weight with `gated_quant_fp8`'s pass (or GeGLU's `gelu_mul` and `quant_act_fp8`) in its epilogue, M ≤ 8; the [M, 2n] product is never written |
| `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch |
| `gemm_mxfp4a8_decode_shortk` | the decode kernel at 33..64 rows of a wide, short weight (N ≥ 8192, K ≤ 2560), above `gemm_mxfp4a8_gemv_wide`, which loses there |
| `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block |
@@ -197,8 +198,21 @@ rows their outputs differ from the decode row's in the last bf16 place on a few
thousand (within the selftest's bound). A greedy text can therefore differ from one produced
with the decode row at those rows. Within the family a row's bits do not depend on M, as above.
**Tunables.** `gemv` and `gemv_wide` have none, so a `RADIANCE_TUNE` pin on `gemm_nt_q` passes
them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of
**`gemm_mxfp4a8_gated_gemv`** (`gemm_nt_q_gated_mx`, M ≤ 8, K a multiple of 128, N of 256, `act`
`silu`, or `gelu_tanh` without `out_bf16`). The `gemv` WMMA form over a gate_up weight, a block per
16-column tile pair of the gated output (eight K waves on the gate tile, eight on the up tile, in
`gemv`'s K order), the bf16 product and row amaxes in the op's scratch; the last of a 128-column
group's blocks to arrive (a counter keyed on the output) writes the group's codes and scales. Byte
for byte `gemm_mxfp4a8_gemv` followed by `gated_quant_fp8`, or by `gelu_mul` and `quant_act_fp8`
(`r4d_selftest`, M = 1..8, Qwen's and TranslateGemma's gate_up). A decode step of Qwen3.8-27B
at TP2 issues 631 kernels a card, and a dependent kernel costs 3.5-6.4 µs in a replayed graph on
gfx1201 however little it does, so the launch it saves is the point. TranslateGemma 27B alone,
one stream at speculation 7: 144.5 / 144.9 → 151.5 / 150.5 tok/s, measured with the first form of
this row (a block per 128-column group, the same bytes); the tile-pair form, Qwen3.8-27B without
speculation x1 / x4 / x8 +1.4 / +1.8 / +1.5 %.
**Tunables.** `gemv`, `gemv_wide` and `gated_gemv` have none, so a `RADIANCE_TUNE` pin on
`gemm_nt_q` passes them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of
those reaches both. A pin applies to every row serving the op, and an axis a serving row lacks
stops startup by name.
+2 -2
View File
@@ -343,10 +343,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (host) {
sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes);
fl = r4d_ar_host_alloc(flag_words * 4);
fl = r4d_ar_host_alloc((flag_words + 2L * maxb) * 4);
} else {
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
fl = r4d_ar_ipc_alloc((flag_words + 2L * maxb) * 4, 1, handle, &hlen);
}
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen));
+9
View File
@@ -72,6 +72,7 @@ __global__ void r4d_ar_gather_2rank_kernel(
const int w = (n16 + nb - 1) / nb;
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
// Push the chunk to the peer slot and place this rank's own slice (a local store, no handshake)
// while the push is in flight.
@@ -82,6 +83,8 @@ __global__ void r4d_ar_gather_2rank_kernel(
v2 = in4[r4d_g_src(k + 2 * nt, row16, n16, sp16)],
v3 = in4[r4d_g_src(k + 3 * nt, row16, n16, sp16)];
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) +
r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v0;
out4[r4d_g_dst(k + nt, row16, n16, rank, dp16)] = v1;
out4[r4d_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2;
@@ -90,11 +93,13 @@ __global__ void r4d_ar_gather_2rank_kernel(
for (; k < end; k += nt) {
int4 v = in4[r4d_g_src(k, row16, n16, sp16)];
ps[k] = v;
hck += r4d_archk_u4(v, 4u * (unsigned)k);
out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v;
}
}
// Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot
// see the flag before the data.
r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
@@ -110,6 +115,9 @@ __global__ void r4d_ar_gather_2rank_kernel(
}
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
});
// Place the peer's slice, now staged in this rank's scratch.
{
@@ -165,6 +173,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo
int nt = (int)nthreads;
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
r4d_ar_gather_2rank_kernel<<<nb, nt, 0, st>>>(
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out,
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16,
+53 -8
View File
@@ -163,6 +163,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
float* Lsc = (float*)(Lpk + (size_t)cpb * ARN_WV * ARN_NWORD);
const int lig = lane & (ARN_LPG - 1), gw = lane / ARN_LPG;
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
if constexpr (WIRE == 0) {
// Push my rows to the peer slot. A row is K/8 16B words and rows are contiguous, so a row
// range is a word range.
@@ -173,8 +174,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
for (; k + 3 * THR < wend; k += 4 * THR) {
int4 v0 = in4[k], v1 = in4[k + THR], v2 = in4[k + 2 * THR], v3 = in4[k + 3 * THR];
ps[k] = v0; ps[k + THR] = v1; ps[k + 2 * THR] = v2; ps[k + 3 * THR] = v3;
hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + THR)) +
r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * THR)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * THR));
}
for (; k < wend; k += THR) ps[k] = in4[k];
for (; k < wend; k += THR) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); }
} else {
// Rotate, amax, quantise and pack straight into the peer's slot, keeping the same words in
// LDS. A wave owns whole chunks, so every lane emits exactly ARN_NWORD dwords per chunk and the
@@ -201,8 +204,10 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
float scl = (a > 0.f) ? arn_bf16_round(a * (1.0f / (float)ARN_QMAX)) : 1.0f;
if (!(scl > 0.f)) scl = 1.0f;
if (lig == 0) {
p_sc[c * ARN_CG + gl] = (unsigned short)(__float_as_uint(scl) >> 16);
const unsigned short sc16 = (unsigned short)(__float_as_uint(scl) >> 16);
p_sc[c * ARN_CG + gl] = sc16;
Lsc[(size_t)ci * ARN_CG + gl] = scl;
hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
}
const float inv = 1.0f / scl;
#pragma unroll
@@ -217,20 +222,30 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
// Flush lane-contiguously region by region, widest first, so each region is one coalesced
// store of ARN_WV x width bytes (ARN_NWORD is 3).
char* pb = p_pay + (size_t)c * ARN_CBYTES;
const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); // the chunk's first dword
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4)
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) {
*(uint4*)(pb + w4 * 4 * ARN_WV + lane * 16) =
make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]);
if constexpr (ARN_NWORD % 4 >= 2)
hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]),
cd + (unsigned)(w4 * ARN_WV + lane * 4));
}
if constexpr (ARN_NWORD % 4 >= 2) {
*(uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8) =
make_uint2(acc[ARN_NWORD & ~3], acc[(ARN_NWORD & ~3) + 1]);
if constexpr (ARN_NWORD % 2 == 1)
const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2);
hck += r4d_archk_mix(acc[ARN_NWORD & ~3], e) + r4d_archk_mix(acc[(ARN_NWORD & ~3) + 1], e + 1u);
}
if constexpr (ARN_NWORD % 2 == 1) {
*(unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4) = acc[ARN_NWORD - 1];
hck += r4d_archk_mix(acc[ARN_NWORD - 1], cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane));
}
#pragma unroll
for (int w = 0; w < ARN_NWORD; ++w)
Lpk[((size_t)ci * ARN_NWORD + w) * ARN_WV + lane] = acc[w];
}
}
r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
@@ -245,6 +260,35 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel(
}
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
if constexpr (WIRE == 0) {
const int wpr = K >> 3;
for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
} else {
for (int ci = wave; ci < cpb; ci += NW) {
const int c = c00 + ci;
const char* pb = m_pay + (size_t)c * ARN_CBYTES;
const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4);
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4)
h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16),
cd + (unsigned)(w4 * ARN_WV + lane * 4));
if constexpr (ARN_NWORD % 4 >= 2) {
const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8);
const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2);
h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u);
}
if constexpr (ARN_NWORD % 2 == 1)
h += r4d_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4),
cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane));
#pragma unroll
for (int t = 0; t < ARN_ITERS; ++t) {
const int gl = t * ARN_GPW + gw;
if (lig == 0) h += r4d_archk_mix(m_sc[c * ARN_CG + gl], R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl));
}
}
}
});
// The peer's rows are now in my scratch, in the same [M, K] layout as X.
const __hip_bfloat16* P = (const __hip_bfloat16*)ms;
@@ -404,9 +448,10 @@ static size_t ar_ln_lds_bytes(int rows_max, int K, int thr, int wire) {
}
return b;
}
// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words (seq and slot), which
// the runtime places in front of it.
static constexpr size_t kArnLdsCap = 65536 - 16;
// Dynamic LDS ceiling: a workgroup's 64 KiB less the kernel's static words, which the runtime places
// in front of it: seq and slot, and the push check's (r4d_ar_seq.h: two 32-word sums and a flag,
// 260 bytes), rounded up.
static constexpr size_t kArnLdsCap = 65536 - 16 - 512;
// Fewest blocks at which this shape fits: each block owns ceil(M / nb) rows, and on the compressed
// wire each row costs a staging slice and its chunks' packed half. -1 when no block count fits (a
+40 -5
View File
@@ -18,6 +18,7 @@
// * Fine-grained memory (hipDeviceMallocFinegrained) is uncached and posted straight to the
// fabric, so system-scope release/acquire skip the L2 writeback. The drain/acq fences are
// selectable (default drain=1/acq=0 on fine-grained).
#include <cstdlib>
#include "r4d.h"
#include "r4d_ar_seq.h"
#include "r4d_ar_hc.h" // the gather word and the hc write word, shared with the rotated wire
@@ -76,15 +77,26 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
// drain 4, tests only (R4D_AR_TEST_LATE_PUSH, r4d_selftest): the flag goes out before the push
// and the push ~20 us after it, so the peer sees a flag whose bytes have not landed -- what a
// push over PCIe P2P now and then does on its own -- on every launch.
if (drain == 4) {
if (tid == 0) store_sys_rel(&peer_flags[b], s);
const unsigned long long t0 = wall_clock64();
while (wall_clock64() - t0 < 2000ull) __builtin_amdgcn_s_sleep(8); // 100 MHz: 20 us
}
// Push the chunk to the peer slot, 4x unrolled for memory-level parallelism.
{
int k = start + tid;
for (; k + 3 * nt < end; k += 4 * nt) {
int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt];
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) +
r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
}
for (; k < end; k += nt) ps[k] = in4[k];
for (; k < end; k += nt) { const int4 v = in4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); }
}
// Drain modes, ordering the pushes before the release flag so the peer sees data first:
// 0 = none (relies on PCIe posted-write ordering and the release flag)
@@ -94,12 +106,13 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
// 3 = all-thread s_wait_storecnt 0: every wave drains its posted writes with no L2
// writeback-invalidate; PCIe keeps posted writes to one peer ordered, so the release flag
// lands after the data. Correct only for fine-grained memory (coarse leaves data in L2).
r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s, drain == 4);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
if (tid == 0) {
if (drain == 2) __threadfence_system();
store_sys_rel(&peer_flags[b], s);
if (drain != 4) store_sys_rel(&peer_flags[b], s);
unsigned long long z = 0;
// A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes.
while (r4d_ar_seq_behind(load_sys_acq(&my_flags[b]), s)) {
@@ -108,6 +121,9 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel(
}
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
});
// Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch).
{
int k = start + tid;
@@ -147,15 +163,19 @@ __global__ void r4d_ar_hc_write_kernel(
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
{
int k = start + tid;
for (; k + 3 * nt < end; k += 4 * nt) {
int4 v0 = y4[k], v1 = y4[k + nt], v2 = y4[k + 2 * nt], v3 = y4[k + 3 * nt];
ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3;
hck += r4d_archk_u4(v0, 4u * (unsigned)k) + r4d_archk_u4(v1, 4u * (unsigned)(k + nt)) +
r4d_archk_u4(v2, 4u * (unsigned)(k + 2 * nt)) + r4d_archk_u4(v3, 4u * (unsigned)(k + 3 * nt));
}
for (; k < end; k += nt) ps[k] = y4[k];
for (; k < end; k += nt) { const int4 v = y4[k]; ps[k] = v; hck += r4d_archk_u4(v, 4u * (unsigned)k); }
}
r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
@@ -168,8 +188,11 @@ __global__ void r4d_ar_hc_write_kernel(
}
}
__syncthreads();
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
});
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
const int wpr = n >> 3; // 16B words a row
for (int k = start + tid; k < end; k += nt) {
@@ -231,6 +254,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
const int w = (n16 + nb - 1) / nb; // 16B words per block
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
const int wpr = n >> 3; // 16B words a row
const int row_lo = start / wpr;
const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0;
@@ -264,7 +288,9 @@ __global__ void r4d_ar_gather_hc_write_kernel(
const int4 out = r4d_ar_gather_word<INV>(G, inv, s_i, s_w, s_g, row, row - row_lo, i0);
y4[k] = out;
ps[k] = out;
hck += r4d_archk_u4(out, 4u * (unsigned)k);
}
r4d_archk_put(hck, peer_flags, nbw, (unsigned)slot, (unsigned)b, s);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
@@ -277,8 +303,11 @@ __global__ void r4d_ar_gather_hc_write_kernel(
}
}
__syncthreads();
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) {
for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
});
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
for (int k = start + tid; k < end; k += nt) {
const int4 r = vadd<__hip_bfloat16, 8>(y4[k], ms[k]);
@@ -398,6 +427,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
int nt = (int)nthreads;
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
r4d_ar_hc_write_kernel<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
@@ -436,6 +466,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
int nt = (int)nthreads;
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
/* Zeroed including padding: the struct is passed by value, so its tail padding is part of the
* kernel-argument bytes a recorded pass's audit compares. */
R4dArGather G;
@@ -527,6 +558,10 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl
int nt = (int)nthreads;
if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
// Tests only: every push lands after its flag (drain 4 above). Not in the tuning table, so no
// tuner can pick it.
if (const char* e = std::getenv("R4D_AR_TEST_LATE_PUSH"); e && *e == '1') drain = 4;
#define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<T, LN><<<nb, nt, 0, st>>>( \
(const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \
+42 -3
View File
@@ -129,7 +129,8 @@ struct Wht6Chunk {
template <int CG = CHUNK_GROUPS, typename Ld>
__device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_groups, int lane,
int lig, int gw, uint4* p_pay,
unsigned short* p_sc, uint4* l_pay, float* l_sc) {
unsigned short* p_sc, uint4* l_pay, float* l_sc,
unsigned int& hck) {
using Ch = Wht6Chunk<CG>;
const int qmin = -(1 << (BITS - 1)), qmax = (1 << (BITS - 1)) - 1;
unsigned int acc[Ch::NW];
@@ -157,8 +158,10 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group
float sc = (a > 0.f) ? bf16_round(a * (1.0f / (float)qmax)) : 1.0f;
if (!(sc > 0.f)) sc = 1.0f;
if (lig == 0 && live) {
p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16);
const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16);
p_sc[g] = sc16;
l_sc[g] = sc;
hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g);
}
const float inv = 1.0f / sc;
#pragma unroll
@@ -177,6 +180,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
p_pay[o] = q;
l_pay[o] = q;
hck += r4d_archk_u4(q, 4u * (unsigned)o);
}
} else {
unsigned int* pp = reinterpret_cast<unsigned int*>(p_pay);
@@ -186,6 +190,7 @@ __device__ __forceinline__ void wht6_push_chunk(const Ld& ld, int c, int n_group
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
pp[o] = acc[u];
lp[o] = acc[u];
hck += r4d_archk_mix(acc[u], (unsigned)o);
}
}
}
@@ -209,6 +214,34 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne
if (acq) __threadfence_system();
}
// The push check's re-hash of one chunk (r4d_ar_seq.h): the payload words and live scales the
// reduce below reads, at the indices wht6_push_chunk hashed them.
template <int CG = CHUNK_GROUPS>
__device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane,
int lig, int gw, const uint4* m_pay,
const unsigned short* m_sc) {
using Ch = Wht6Chunk<CG>;
if constexpr (Ch::U4) {
#pragma unroll
for (int u = 0; u < Ch::NW / 4; ++u) {
const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane;
h += r4d_archk_u4(m_pay[o], 4u * (unsigned)o);
}
} else {
const unsigned int* mp = reinterpret_cast<const unsigned int*>(m_pay);
#pragma unroll
for (int u = 0; u < Ch::NW; ++u) {
const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane;
h += r4d_archk_mix(mp[o], (unsigned)o);
}
}
#pragma unroll
for (int t = 0; t < Ch::ITERS; ++t) {
const int g = c * CG + t * GPW + gw;
if (lig == 0 && g < n_groups) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g);
}
}
// Reduce: unpack both halves, add in fp32, inverse-rotate, pass each live group's EPL elements to st.
template <int CG = CHUNK_GROUPS, typename St>
__device__ __forceinline__ void wht6_reduce_chunk(const St& st, int c, int n_groups, int lane,
@@ -300,10 +333,16 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel(
#pragma unroll
for (int i = 0; i < EPL; ++i) v[i] = rd_to_f(in[off + i]);
};
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc);
wht6_push_chunk(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck);
r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s);
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
});
const auto st = [&](long off, const float* v) {
#pragma unroll
+7 -1
View File
@@ -139,10 +139,16 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
r4d_ar_hc_write_word(inj, h, row, i0, n, hc, irow, hrow,
reinterpret_cast<const unsigned short*>(&q));
};
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_push_chunk<CG>(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc);
wht6_push_chunk<CG>(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc, hck);
r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, s);
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) {
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_rehash_chunk<CG>(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc);
});
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
for (int c = c0 + wid; c < c1; c += nwarp)
+111
View File
@@ -87,3 +87,114 @@ __device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long wo
__device__ __forceinline__ bool r4d_ar_seq_behind(unsigned int flag, unsigned int want) {
return (int)(flag - want) < 0;
}
// ---- The push check. A peer's push over PCIe P2P can land after its release flag (measured on 2x
// R9700: the reader sometimes found the slot's previous contents right after the handshake, and
// the new bytes ~1 us later), so the flag alone does not say the bytes are there. The pushed bytes
// wait in the writer's L2 for the release's writeback, and that writeback and the flag store reach
// the peer by different paths. The writer sums
// mix(dword, index) over what it pushes and stores the block's sum, salted with its handshake
// value, into the peer's check word for (slot, block): fine-grained words after the flags
// (r4d_ar_entry.hip sizes the allocation). The reader sums the same over the bytes it is about to
// read and reads again until the two agree. A stale element and a stale check word (an older
// handshake value) both disagree, so only the landed push passes; the order the two land in does
// not matter. The sum is order-free, so writer and reader may split the bytes differently.
#define R4D_ARCHK_SALT 0x6C8E9CF5u
#ifndef R4D_ARCHK_DEADLINE
#define R4D_ARCHK_DEADLINE 200000000ull // wall_clock64 ticks (100 MHz): 2 s; a push that never lands is a lockstep fault
#endif
#define R4D_ARCHK_U16 0x80000000u // index space of 16-bit fields (wire scales), apart from dwords
// MurmurHash3's finalizer over (value, index): every bit of the value reaches every bit of the term,
// so a sum of terms changes when any value does. A linear mix is not enough: (v ^ c_e) summed over
// a run of indices can lose v entirely, and a message of one repeated value (a test pattern, a
// zero-filled row) would then pass whatever the slot held.
__device__ __forceinline__ unsigned int r4d_archk_mix(unsigned int v, unsigned int e) {
unsigned int x = v ^ (e * 0x9E3779B9u);
x ^= x >> 16; x *= 0x85EBCA6Bu;
x ^= x >> 13; x *= 0xC2B2AE35u;
x ^= x >> 16;
return x;
}
// A 16B word at dword index `e`.
__device__ __forceinline__ unsigned int r4d_archk_u4(int4 v, unsigned int e) {
return r4d_archk_mix((unsigned int)v.x, e) + r4d_archk_mix((unsigned int)v.y, e + 1u) +
r4d_archk_mix((unsigned int)v.z, e + 2u) + r4d_archk_mix((unsigned int)v.w, e + 3u);
}
__device__ __forceinline__ unsigned int r4d_archk_u4(uint4 v, unsigned int e) {
return r4d_archk_mix(v.x, e) + r4d_archk_mix(v.y, e + 1u) + r4d_archk_mix(v.z, e + 2u) +
r4d_archk_mix(v.w, e + 3u);
}
// The check word of (slot, block) in a flags allocation: two parity slots of nbw words after the
// nbw flags.
__device__ __forceinline__ unsigned int* r4d_archk_word(unsigned int* flags, unsigned int nbw,
unsigned int slot, unsigned int b) {
return flags + nbw + slot * nbw + b;
}
__device__ __forceinline__ unsigned int r4d_archk_wave_sum(unsigned int h) {
for (int o = 16; o > 0; o >>= 1) h += __shfl_xor(h, o, 32);
return h;
}
// Writer: every thread of the block calls this after its pushes, before the handshake's barrier.
// Thread 0 stores the block's sum into the peer's check word.
__device__ __forceinline__ void r4d_archk_put(unsigned int h, unsigned int* peer_flags,
unsigned int nbw, unsigned int slot,
unsigned int b, unsigned int seq,
bool release = false) {
__shared__ unsigned int s_ckp[32];
const unsigned int tid = threadIdx.x, nt = blockDim.x;
h = r4d_archk_wave_sum(h);
if ((tid & 31u) == 0u) s_ckp[tid >> 5] = h;
__syncthreads();
if (tid == 0) {
unsigned int t = 0u;
for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckp[w];
/* The pushed bytes sit in this card's L2 until a system-scope release writes them back. The
* flag's release, right after this, does that, so the word itself can be relaxed (the reader
* re-reads until the bytes agree with it). Where the flag went out before the push (the test
* mode, drain 4) nothing else would write them back before the kernel ends: a release. */
unsigned int* const cw = r4d_archk_word(peer_flags, nbw, slot, b);
if (release)
__hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
else
__hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
}
// Reader: every thread of the block calls this after the handshake; `rehash(h)` adds the thread's
// share of the bytes the block is about to read, with the same loads the kernel then makes.
template <typename F>
__device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned int nbw,
unsigned int slot, unsigned int b,
unsigned int seq, const F& rehash) {
__shared__ unsigned int s_ckw[32];
__shared__ unsigned int s_ckok;
const unsigned int tid = threadIdx.x, nt = blockDim.x;
const unsigned long long t0 = tid == 0 ? wall_clock64() : 0ull;
for (;;) {
/* The check word first, so its round trip overlaps the re-hash's loads. Read before the bytes
* it is compared with, it can only be older than them, and an older word just fails this try. */
const unsigned int want = tid == 0 ? __hip_atomic_load(r4d_archk_word(my_flags, nbw, slot, b),
__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)
: 0u;
unsigned int h = 0u;
rehash(h);
h = r4d_archk_wave_sum(h);
if ((tid & 31u) == 0u) s_ckw[tid >> 5] = h;
__syncthreads();
if (tid == 0) {
unsigned int t = 0u;
for (unsigned int w = 0; w < (nt + 31u) / 32u; ++w) t += s_ckw[w];
const bool ok = t + seq * R4D_ARCHK_SALT == want;
if (!ok && wall_clock64() - t0 > R4D_ARCHK_DEADLINE) __builtin_trap();
s_ckok = ok ? 1u : 0u;
}
__syncthreads();
if (s_ckok) return;
__syncthreads(); // s_ckw and s_ckok are rewritten by the next try
/* Drop the vector caches, so the next try reads the bytes from where the push lands. */
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
__builtin_amdgcn_s_sleep(2);
}
}
+52 -10
View File
@@ -132,13 +132,25 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
constexpr float PGROW = D::GROW;
__shared__ uint16_t sK[KLDS ? TILE * KSTR : 1];
__shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR];
// V4 at TILE 16: dim octet o's 8 rows start S(o) = 16 (o & 3) + 8 ((o >> 2) & 1) + 128 (o >> 2)
// halfwords later, so the 4 (8) octets of a storeV4 store land on distinct banks (unskewed they
// share them: 8 rows = 96 dwords = 0 mod 32). The 128 (o >> 2) term (64 dwords, unseen by the
// banks) keeps octet o's last row clear of octet o + 1's first; multiples of 8 halfwords keep the
// b128 PV read aligned. NWARPS 1 keeps the plain tile: its 10 workgroups a WGP would not fit.
constexpr int VSK = (V4 && TILE == 16 && CTG && NWARPS >= 2) ? 1 : 0;
constexpr int VSKN = HEAD_DIM / 8 - 1;
constexpr int VSKX = VSK ? 16 * (VSKN & 3) + 8 * ((VSKN >> 2) & 1) + 128 * (VSKN >> 2) : 0;
__shared__ uint16_t sV16[V8 ? 1 : HEAD_DIM * VSTR + VSKX];
/* A code-tile row is 16 keys + 8 padding = 24 bytes (six dwords): the sixteen lanes of a
* fragment read hit distinct banks, and a lane's eight codes are one aligned 8-byte load. */
constexpr int VSTR8 = TILE + 8;
__shared__ uint8_t sV8[V8 ? HEAD_DIM * VSTR8 : 1];
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
// The launch is NTHR threads. Stated (k6_v4), so the V4 rounds wholly below NP4 lose their range
// test: as exec-masked blocks, each round's loads issued only after the previous round's returned.
// fp8_v4 keeps the tested rounds: batched there, its 4-row steps ran 6 % slower.
if constexpr (K6) __builtin_assume(tid < NTHR);
const int c = lane & 15, h = lane >> 4;
const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z;
@@ -219,12 +231,19 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
// scale, widened with packed f16 into one dword a dim), fetched in the tile: no prefetch.
constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8);
constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1;
uint32_t v4c[U4][2], v4s[U4];
// The pair's two scales stay apart until storeV4 packs them: packed here, the fetch is waited on
// right after it is issued. fp8_v4 packs here as before, as the prefill kernel keeps it.
constexpr int OLDV4 = V4 && !K6;
uint32_t v4c[U4][2], v4s[U4][2];
auto fetchV4 = [&](int k0, const int* blks) {
#pragma unroll
for (int r = 0; r < U4; ++r) {
const int u = tid + r * NTHR;
if (NP4 % NTHR == 0 || u < NP4) {
// k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR)
// / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch.
if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4
|| (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR
: u < NP4)) : u < NP4)) {
const int kp = u % (TILE / 2), o = u / (TILE / 2);
uint32_t sc[2];
#pragma unroll
@@ -237,7 +256,8 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
}
v4s[r] = sc[0] | (sc[1] << 16);
if constexpr (OLDV4) { v4s[r][0] = sc[0] | (sc[1] << 16); v4s[r][1] = 0; }
else { v4s[r][0] = sc[0]; v4s[r][1] = sc[1]; }
}
}
};
@@ -246,16 +266,21 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
#pragma unroll
for (int r = 0; r < U4; ++r) {
const int u = tid + r * NTHR;
if (NP4 % NTHR == 0 || u < NP4) {
// k6_v4, a partial round (NWARPS 3: the third, warps 0-1): u < NP4 <=> warp < (NP4 - r NTHR)
// / 32 when NP4 is a multiple of 32, tested on the wave-uniform warp: a scalar branch.
if (NP4 % NTHR == 0 || (K6 ? ((r + 1) * NTHR <= NP4
|| (NP4 % 32 == 0 ? __builtin_amdgcn_readfirstlane(warp) * 32 < NP4 - r * NTHR
: u < NP4)) : u < NP4)) {
const int kp = u % (TILE / 2), o = u / (TILE / 2);
// Two's complement nibbles; ^ 8 makes them offset binary (value + 8).
const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u;
const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u;
const h2 s2 = __builtin_bit_cast(h2, v4s[r]);
const h2 s2 = __builtin_bit_cast(h2, OLDV4 ? v4s[r][0] : (v4s[r][0] | (v4s[r][1] << 16)));
const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f };
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp];
uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp
+ (VSK ? 16 * (o & 3) + 8 * ((o >> 2) & 1) + 128 * (o >> 2) : 0)];
#pragma unroll
for (int b = 0; b < 4; ++b) {
const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u;
@@ -507,13 +532,18 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
const uint2 y = swap16_u2p((h == 0) ? hi2 : lo);
p16 = (h == 0) ? D::mk(lo, y) : D::mk(y, hi2);
}
const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0);
// Skewed tile: row 16 G + c is in octet 2 G + (c >> 3), so its S is 16 (c >> 3) here
// plus 32 (G & 1) + 8 ((G >> 1) & 1) + 128 (G >> 1), a compile-time offset below.
const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0)
+ (VSK ? 16 * (c >> 3) : 0);
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
frag16 vb[PF];
#pragma unroll
for (int j = 0; j < PF; ++j) {
const uint16_t* vp = vbase + (g + j) * 16 * VSTR;
const uint16_t* vp = vbase + (g + j) * 16 * VSTR
+ (VSK ? 32 * ((g + j) & 1) + 8 * (((g + j) >> 1) & 1) + 128 * ((g + j) >> 1)
: 0);
if (V8) {
uint32_t w4[4];
fp8x8_to_16x4w<D>(*(const uint2*)&sV8[(c + (g + j) * 16) * VSTR8 +
@@ -958,11 +988,23 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
// head_dim f16, written once and read once): at eight requests 12.8 MB at splits 32 vs 3.2 MB at
// 8, 19% of a 16K step's KV but 1.2% at 128K. The effect fades with depth, never enough to need a
// context term.
//
// The target is 256 workgroups where a workgroup has one or two waves (q_len * gqa <= 32: a plain decode,
// or a 4-row verify of the DFlash2 short block), 128 otherwise. A one- or two-wave workgroup keeps too
// few KV bytes in flight for the card's DRAM at 128 (about one a CU); twice as many reach it. Qwen3.8-27B
// at TP2 on the R9700, k6_v4: r4d_selftest --perfdecattn (2 rounds) 4 x 1 row over 100k 582 -> 464 us,
// 1 x 1 row over 100k 264 -> 175, 16 x 4 rows over 41k 985 -> 801 (x4 and x8 the target were worse
// than x2); the server's decode step at speculation 7 (three rounds, medians, the steps carrying every
// sequence) 8 x 41k 34.01 -> 32.48 ms, 16 x 25k 44.65 -> 43.19. At three waves (an 8-row verify) more
// workgroups only add contention: 4 x 8 rows over 100k +9 % at x2, so those keep 128. The split
// count already moves with the batch (8 sequences at 256 split like 4 at 128), so this adds no
// partition the merge did not already see.
static inline int r4d_decode_splits(const R4DArgs* a, int tile) {
if (a->splits > 0) return a->splits;
const int tiles = (a->max_ctx + tile - 1) / tile;
const int units = std::max(1, a->kv_heads * a->num_seqs);
int s = 128 / units;
const int gqa = a->kv_heads > 0 ? std::max(1, a->q_heads / a->kv_heads) : 1;
int s = (a->q_len * gqa <= 32 ? 256 : 128) / units;
const int cap = tiles / 2;
if (s > cap) s = cap;
if (s > tiles) s = tiles;
+58
View File
@@ -510,6 +510,64 @@ extern "C" int r4d_fuse_gemm_nt_q_gated(const RadParam* p, int n_p, uint64_t pre
}
}
/* ==========================================================================================
* gemm_nt_q_gated_mx -- the same fold over an OCP-MXFP4 weight.
* (row: gemm_mxfp4a8_gated_gemv; kernel: libr4d/r4d_gemm_mxfp4a8_gemv.hip, the gated form)
*
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] b_ref [5] q [6] scale [7] out_bf16
*
* The GEMM step is gemm_nt_q at dtype mxfp4a8 with `b_ref` in its last operand. `group` is the
* weight's 32 on the GEMM and the activation's 128 on the quantiser, so the quantiser's is set, not
* mirrored. At act gelu_tanh the chain is three steps, gelu_mul into a second temporary and
* quant_act_fp8 over it; that form refuses `out_bf16` (the shim), so operand 7 is not wired.
*/
extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const char* dt = r4d_pgets(p, n_p, "dtype");
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
if (pi(p, n_p, "group", 32) != 32) return RAD_E_UNSUPPORTED;
if (!dt || std::strcmp(dt, "mxfp4a8")) return RAD_E_UNSUPPORTED;
const bool gelu = act_is(p, n_p, "silu", "gelu_tanh");
if (!gelu && !act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
/* The GeGLU chain leaves its bf16 plane in a temporary, so a caller asking for out_bf16 there
* has no chain (the shim refuses the operand too). */
if (gelu && RAD_FUSE_HAS(present, 7)) return RAD_E_UNSUPPORTED;
if (step == 0) {
Step s(out, "gemm_nt_q");
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, 4 });
}
if (gelu) {
if (step == 1) {
Step s(out, "gelu_mul");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pstr("dtype", "bf16");
return s.wire({ RAD_FUSE_TMP(0), RAD_FUSE_TMP(1) }); /* gate_up, y */
}
if (step == 2) {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
.pstr("dtype", "bf16");
return s.wire({ RAD_FUSE_TMP(1), 5, 6 }); /* x, q, scale */
}
return RAD_E_NOTFOUND;
}
switch (step) {
case 1: {
Step s(out, "gated_quant_fp8");
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).pint("group", 128)
.pstr("dtype", "bf16").mirror(p, n_p, "act");
return s.wire({ RAD_FUSE_TMP(0), 5, 6, 7 }); /* gate_up, q, scale, out_bf16 */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue.
* (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libr4d/
+55 -5
View File
@@ -415,13 +415,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
unsigned int* const Lpk = (unsigned int*)loc_pack;
float* const Lsc = (float*)(loc_pack + loc_scale_off);
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
if constexpr (WIRE == 0) {
/* Push my rows into the peer's slot. `x` is a tight [M][n] of bf16 (the launcher refuses a
* pitched one), so a row range is a 16B-word range. */
const int wpr = (int)(n >> 3);
const int wend = r1 * wpr;
const int4* const in4 = (const int4*)x;
for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) ps[k] = in4[k];
for (int k = r0 * wpr + (int)tid; k < wend; k += (int)THR) {
const int4 v = in4[k];
ps[k] = v;
hck += r4d_archk_u4(v, 4u * (unsigned)k);
}
} else {
/* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks,
* so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is
@@ -449,8 +454,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
float sc = (a > 0.0f) ? bf2f(f2bf(a * (1.0f / (float)ARQ_QMAX))) : 1.0f;
if (!(sc > 0.0f)) sc = 1.0f;
if (lig == 0) {
p_sc[g] = (unsigned short)(__float_as_uint(sc) >> 16);
const unsigned short sc16 = (unsigned short)(__float_as_uint(sc) >> 16);
p_sc[g] = sc16;
Lsc[g] = sc;
hck += r4d_archk_mix(sc16, R4D_ARCHK_U16 + (unsigned)g);
}
const float inv = 1.0f / sc;
#pragma unroll
@@ -464,21 +471,33 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
}
/* Flush lane-contiguously, widest region first, so each is one coalesced store. */
char* const pb = p_pay + (size_t)c * ARQ_CBYTES;
const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); // the chunk's first dword
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4)
for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) {
*(uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16) =
make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]);
if constexpr (ARQ_NWORD % 4 >= 2)
hck += r4d_archk_u4(make_uint4(acc[w4], acc[w4 + 1], acc[w4 + 2], acc[w4 + 3]),
cd + (unsigned)(w4 * ARQ_WV) + lane * 4u);
}
if constexpr (ARQ_NWORD % 4 >= 2) {
*(uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8) =
make_uint2(acc[ARQ_NWORD & ~3], acc[(ARQ_NWORD & ~3) + 1]);
if constexpr (ARQ_NWORD % 2 == 1)
const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u;
hck += r4d_archk_mix(acc[ARQ_NWORD & ~3], e) +
r4d_archk_mix(acc[(ARQ_NWORD & ~3) + 1], e + 1u);
}
if constexpr (ARQ_NWORD % 2 == 1) {
*(unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4) =
acc[ARQ_NWORD - 1];
hck += r4d_archk_mix(acc[ARQ_NWORD - 1],
cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane);
}
#pragma unroll
for (int wi = 0; wi < ARQ_NWORD; ++wi)
Lpk[((size_t)c * ARQ_NWORD + wi) * ARQ_WV + lane] = acc[wi];
}
}
r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq);
/* The drain modes are r4d_ar_oneshot_2rank_exact's, selected by the same variant table. */
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
@@ -495,6 +514,37 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
}
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
if constexpr (WIRE == 0) {
const int wpr = (int)(n >> 3);
const int4* const m4 = (const int4*)ms;
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR)
h += r4d_archk_u4(m4[k], 4u * (unsigned)k);
} else {
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
const int c = c00 + ci;
const char* const pb = m_pay + (size_t)c * ARQ_CBYTES;
const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4);
#pragma unroll
for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4)
h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16),
cd + (unsigned)(w4 * ARQ_WV) + lane * 4u);
if constexpr (ARQ_NWORD % 4 >= 2) {
const uint2 u = *(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8);
const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u;
h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u);
}
if constexpr (ARQ_NWORD % 2 == 1)
h += r4d_archk_mix(*(const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4),
cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane);
#pragma unroll
for (int t = 0; t < ARQ_ITERS; ++t) {
const int g = c * ARQ_CG + t * ARQ_GPW + gw;
if (lig == 0) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g);
}
}
}
});
if constexpr (WIRE == 6) {
/* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate,
+288 -1
View File
@@ -30,19 +30,25 @@
// shuffles. TN only widens a block; the sum order of a column is fixed by KW, which is constant.
//
// The column's 2^(ref - 127) is applied once, as in the decode kernel's epilogue. No scratch and no
// counters: there is no split across blocks.
// counters: there is no split across blocks (the gated fold at the end of the file has both).
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include "r4d_q8.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <cstring>
#include <map>
#include <mutex>
#include <stdexcept>
#include <utility>
#define R4D_MXG_MAX_M 8
#define R4D_MXG_WMMA_MAX_M 64 // the WMMA form's bound: four 16-row tiles a wave
#define R4D_MXG_KW 8 // waves on a block's K, both forms; a constant, so the sum order is too
#define R4D_MXGG_MAX_GROUPS 1024 // the gated fold's counter block: a gated width up to 131072
typedef unsigned mxg_u4 __attribute__((ext_vector_type(4)));
typedef unsigned mxg_u2 __attribute__((ext_vector_type(2)));
@@ -346,3 +352,284 @@ extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) {
}
return RAD_OK;
}
// ============================================================== the gated form (gemm_nt_q_gated_mx)
//
// The gate_up GEMM with gated_quant_fp8's pass in its epilogue, so the [M, 2n] bf16 product is never
// written and the quantiser is not a launch of its own. A block is one 16-column tile of the gated
// output: sixteen waves, the WMMA form's eight K waves over the gate tile (weight rows 16 j ..) and
// eight over the up tile (rows n + 16 j ..), each tile's partials met in LDS in that form's order.
// The block forms silu(gate) * up in bf16 for its sixteen columns and each row's amax over them. The
// quantiser's scale is per 128 columns (one activation scale group of the down projection's input),
// so the eight blocks of a group leave their products and amaxes in the op's scratch, and the last
// to arrive (an agent-scope counter per group, keyed on the output as the decode row's) takes the
// group's amax and writes its codes and scales.
//
// Why a tile pair a block: one block a 128-column group, each wave running every K partial of one of
// its sixteen tiles, left the grid at n / 128 blocks, 68 at Qwen's per-rank gate_up on 32 WGPs, so a
// few WGPs ran a third block while the rest idled, and the fold (97..101 us) lost to the gemv row and
// gated_quant_fp8 it replaces (78 + 7 us). Splitting K across a group's blocks instead moved an fp32
// partial of the whole product per split through memory (4.4 MB at eight rows; 106 us). A tile pair
// a block is the gemv row's own grid and K order; what crosses blocks is the bf16 product and the
// amaxes, M * n * 2 bytes and n / 16 * M floats: Qwen 78..81 us, TranslateGemma 99 (as before), at
// TP1 148 against the pair's 152 (r4d_selftest --perfmx). End to end the gain is smaller, since a
// replayed step overlaps the old fold's idle WGPs with other work: Qwen without speculation x1 / x4 /
// x8 +1.4 / +1.8 / +1.5 % (three alternating rounds).
//
// Byte-identical to the WMMA form above followed by gated_quant_fp8. Wave v of a tile runs what wave
// v of that form runs (partial v sums chunks v, v + KW, .. in order), and the partials are added
// v = 0, 1, .. from zero, as that form's epilogue adds its waves' rows of sP. The scaled sum is
// rounded to bf16 by the same conversion, and from there the arithmetic is r4d_fused_quant_fp8.hip's
// gated_quant_fp8_kernel: silu(gate) * up rounded to bf16, the group's amax (a max, so the blocks'
// order does not matter), scale amax / 448, codes through q8_pack4. ACT 1 is the GeGLU form: gelu_mul's
// tanh GELU with its constants (r4d_model_bf16.hip), the product rounded to bf16 as gelu_mul stores
// it, then quant_act_fp8's quantiser, which is the same arithmetic as gated_quant_fp8's.
namespace {
__device__ __forceinline__ float mxg_bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
__device__ __forceinline__ uint16_t mxg_f2bf(float f) { // as r4d_fused_quant_fp8.hip's f2bf
const uint32_t u = __float_as_uint(f);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
} // namespace
template <bool ABLK, int ACT>
__global__ __launch_bounds__(2 * R4D_MXG_KW * 32)
void r4d_gemm_mxfp4a8_gated_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, uint8_t* __restrict__ Q, float* __restrict__ S,
uint16_t* __restrict__ Y, uint16_t* __restrict__ H, float* __restrict__ X,
unsigned* __restrict__ cnt, int M, int K, int n, int as_rs, int lda, int ldws, int q_ld,
int s_ld, int y_ld) {
constexpr int KW = R4D_MXG_KW;
__shared__ float sP[2][KW][R4D_MXG_MAX_M][16]; // gate (0) and up (1) partials, a K wave each
__shared__ unsigned s_last;
const int lane = threadIdx.x & 31;
const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5);
const int half = wave >> 3, kv = wave & 7; // gate or up, and this wave's K partial
const int j = blockIdx.x; // the gated output's 16-column tile
const int nt = half * (n >> 4) + j; // this wave's weight tile
const int col = lane & 15, khalf = lane >> 4;
const int row = col;
const bool live = row < M;
const int ksteps = K >> 4, chunks = K >> 7;
const unsigned* __restrict__ Wp = (const unsigned*)W;
const int ref = (int)Wref[nt * 16 + col];
mxg_v8f tot = (mxg_v8f)(0.f);
for (int ch = kv; ch < chunks; ch += KW) {
unsigned wv[8];
#pragma unroll
for (int s = 0; s < 8; ++s)
wv[s] = __builtin_nontemporal_load(&Wp[((size_t)nt * ksteps + ch * 8 + s) * 32 + lane]);
int e8[4];
#pragma unroll
for (int q = 0; q < 4; ++q) e8[q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + nt * 16 + col];
mxg_v2i af[8];
#pragma unroll
for (int s = 0; s < 8; ++s) {
if (live) {
const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8);
af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1];
} else {
af[s][0] = 0; af[s][1] = 0;
}
}
mxg_v8f acc = (mxg_v8f)(0.f);
#pragma unroll
for (int s = 0; s < 8; ++s) {
unsigned lo, hi;
r4d_mxfp4_unpack8(wv[s], r4d_mxfp4_fold_d(ref, e8[s >> 1]), &lo, &hi);
mxg_v2i wf;
wf[0] = (int)lo; wf[1] = (int)hi;
acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[s], acc);
}
const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f;
#pragma unroll
for (int e = 0; e < 8; ++e) tot[e] = fmaf(acc[e], sc, tot[e]);
}
// tot[e]: row (lane & 15), column khalf * 8 + e of the tile.
if (live) {
#pragma unroll
for (int e = 0; e < 8; ++e) sP[half][kv][row][khalf * 8 + e] = tot[e];
}
__syncthreads();
// The tile pair's product: a thread a (row, column), sixteen lanes a row, so a row's amax is a
// shuffle within its sixteen.
const int g = j >> 3; // the 128-column group
const int tid = threadIdx.x;
if (tid < M * 16) {
const int m = tid >> 4, c = tid & 15;
float sg = 0.f, su = 0.f;
#pragma unroll
for (int w = 0; w < KW; ++w) sg += sP[0][w][m][c];
#pragma unroll
for (int w = 0; w < KW; ++w) su += sP[1][w][m][c];
const int cg = j * 16 + c, cu = n + j * 16 + c;
const float rg = __int_as_float((int)Wref[cg] << 23), ru = __int_as_float((int)Wref[cu] << 23);
const float am = ABLK ? 1.f : As[(size_t)m * as_rs];
const __hip_bfloat16 hg = (__hip_bfloat16)(ABLK ? sg * rg : sg * rg * am);
const __hip_bfloat16 hu = (__hip_bfloat16)(ABLK ? su * ru : su * ru * am);
const float gv = mxg_bf2f(*(const uint16_t*)&hg);
const float a = ACT == 0 ? gv / (1.0f + expf(-gv))
: 0.5f * gv * (1.0f + tanhf(0.7978845608028654f * (gv + 0.044715f * gv * gv * gv)));
const uint16_t h = mxg_f2bf(a * mxg_bf2f(*(const uint16_t*)&hu));
if (Y) Y[(size_t)m * y_ld + cg] = h;
H[(size_t)m * n + cg] = h;
float mx = fabsf(mxg_bf2f(h));
#pragma unroll
for (int o = 8; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor(mx, o, 16));
if (c == 0) X[(size_t)j * M + m] = mx;
}
// Every thread's stores are ordered before the counter; then the group's last arriver quantises.
__threadfence();
__syncthreads();
if (tid == 0)
s_last = __hip_atomic_fetch_add(&cnt[g], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (s_last != 7u) return;
if (tid == 0) cnt[g] = 0u; // reset for the next launch
__threadfence(); // acquire, before reading the other blocks'
// gated_quant_fp8: one wave a row, a lane four consecutive columns of the group.
if (wave < M) {
const int m = wave, c0 = lane * 4;
const size_t gcol = (size_t)g * 128 + c0;
float mx = 0.f;
#pragma unroll
for (int t = 0; t < 8; ++t) mx = fmaxf(mx, X[(size_t)(g * 8 + t) * M + m]);
float vq[4];
#pragma unroll
for (int i = 0; i < 4; ++i) vq[i] = mxg_bf2f(H[(size_t)m * n + gcol + i]);
const float sc = mx > 0.0f ? mx * (1.0f / q8_top<false>()) : 1.0f;
if (lane == 0) S[(size_t)m * s_ld + g] = sc;
const float inv = 1.0f / sc;
*(uint32_t*)(Q + (size_t)m * q_ld + gcol) = q8_pack4<false>(vq[0], vq[1], vq[2], vq[3], inv);
}
}
namespace {
// The arrival counters, one block per output buffer, as the decode row's (mxd_out_ctr): not in the
// scratch, which other ops overwrite, since they must be zero at entry. One allocation per (device,
// output), kept zero by the reducer and never freed (a recorded pass replays the pointer).
unsigned* mxgg_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
unsigned* p = nullptr;
if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
// need not wait for, so wait here (as mxd_out_ctr and r4d_moe.hip's router counters do).
if (hipMemset(p, 0, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
}
// The scratch: the bf16 product [M, n], then each tile's per-row amax [n / 16][M] fp32.
long long mxgg_h_bytes(long long M, long long n) { return (M * n * 2 + 255) / 256 * 256; }
long long mxgg_scratch_bytes(long long M, long long n) {
return mxgg_h_bytes(M, n) + (n / 16) * M * (long long)sizeof(float);
}
void mxgg_launch(bool ablk, int act, const void* a, const void* as, const void* w, const void* ws,
const void* wr, void* q, void* s, void* y, void* scratch, unsigned* cnt, int M,
int K, int n, int as_rs, int lda, int ldws, int q_ld, int s_ld, int y_ld,
RadStream stream) {
const dim3 grid((uint32_t)(n / 16)), block(2 * R4D_MXG_KW * 32);
hipStream_t st = (hipStream_t)stream;
uint16_t* h = (uint16_t*)scratch;
float* x = (float*)((char*)scratch + mxgg_h_bytes(M, n));
#define MXGG_L(AB_, ACT_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gated_kernel<AB_, ACT_>), grid, block, 0, st, \
(const unsigned char*)a, (const float*)as, (const unsigned char*)w, \
(const unsigned char*)ws, (const unsigned char*)wr, (uint8_t*)q, (float*)s, \
(uint16_t*)y, h, x, cnt, M, K, n, as_rs, lda, ldws, q_ld, s_ld, y_ld)
if (act == 0) { if (ablk) MXGG_L(true, 0); else MXGG_L(false, 0); }
else { if (ablk) MXGG_L(true, 1); else MXGG_L(false, 1); }
#undef MXGG_L
}
} // namespace
/* The gated GEMM's shim. Operand indices are `gemm_nt_q_gated_mx`'s (oGemmNtQGatedMx in
* r4d_rows.cpp): gemm_nt_q_gated's with the per-row reference `b_ref` after `b_scale`. The weight
* is one [N, K] plane, gate rows then up rows, N = 2 * the gated width; no parts. */
enum { MXGG_A = 0, MXGG_AS = 1, MXGG_B = 2, MXGG_BS = 3, MXGG_BR = 4, MXGG_Q = 5, MXGG_S = 6,
MXGG_Y = 7 };
extern "C" int r4d_rad_gemm_mxfp4a8_gated(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, MXGG_A);
const RadTensor* xs = r4d_opt(a, MXGG_AS);
const RadTensor* w = r4d_opt(a, MXGG_B);
const RadTensor* ws = r4d_opt(a, MXGG_BS);
const RadTensor* wr = r4d_opt(a, MXGG_BR);
const RadTensor* q = r4d_opt(a, MXGG_Q);
const RadTensor* sc = r4d_opt(a, MXGG_S);
const RadTensor* y = r4d_opt(a, MXGG_Y);
if (!x || !xs || !w || !ws || !wr || !q || !sc) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_F8E4M3 || xs->dtype != RAD_F32 || q->dtype != RAD_F8E4M3 ||
sc->dtype != RAD_F32 || (y && y->dtype != RAD_BF16))
return R4D_NO(RAD_E_DTYPE);
if (q->rank != 2 || sc->rank != 2 || x->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE);
if (r4d_geti_or(a, "group", 32) != 32) return R4D_NO(RAD_E_SHAPE);
/* silu (the SwiGLU MLP) or gelu_tanh (GeGLU, gelu_mul's). The GeGLU chain's bf16 plane is
* gelu_mul's output, which the fold's replaces-hook cannot hand to the optional `out_bf16`, so
* that form writes none. */
const char* act = r4d_gets(a, "act");
const int actm = !act ? -1 : !std::strcmp(act, "silu") ? 0 : !std::strcmp(act, "gelu_tanh") ? 1 : -1;
if (actm < 0) return R4D_NO(RAD_E_UNSUPPORTED);
if (actm == 1 && y) return R4D_NO(RAD_E_UNSUPPORTED);
/* The gated width from `q`, the buffer written; N and K from the op's parameters, since the
* weight operands are packed bytes. */
const long long M = q->shape[0], nout = q->shape[1];
const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (M < 1 || M > R4D_MXG_MAX_M || nout < 128 || nout % 128 || nout / 128 > R4D_MXGG_MAX_GROUPS)
return R4D_NO(RAD_E_SHAPE);
if (N != 2 * nout || K < 128 || K % 128) return R4D_NO(RAD_E_SHAPE);
if (x->shape[0] != M || r4d_numel(x) != M * K) return R4D_NO(RAD_E_SHAPE);
if (sc->shape[0] != M || sc->shape[1] != nout / 128) return R4D_NO(RAD_E_SHAPE);
if (y && (y->shape[0] != M || y->shape[1] != nout)) return R4D_NO(RAD_E_SHAPE);
/* The activation scale grid as the gemm_nt_q rows read it (mx_ascale_grid), so the fold and the
* GEMM it replaces take every scale plane the same way. */
GemmOps go{};
go.ascale = xs; go.M = M; go.K = K;
int as_group = 0, as_rs_i = 1;
if (mx_ascale_grid(go, &as_group, &as_rs_i) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
const bool ablk = as_group == 128;
const long long as_rs = as_rs_i;
/* Row pitches; r4d_row_pitch is -1 for a tensor not contiguous past its leading axis. A is read
* a dword at a time. */
const long long lda = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc);
const long long yp = y ? r4d_row_pitch(y) : 0;
if (lda < K || lda % 4 || qp < nout || sp < nout / 128 || (y && yp < nout))
return R4D_NO(RAD_E_STRIDE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || !r4d_aligned(q->data, 4) ||
!r4d_aligned(ws->data, 4) || !r4d_aligned(wr->data, 4) || qp % 4)
return R4D_NO(RAD_E_ALIGN);
/* The cross-block product and amaxes are the op's scratch (sized by the hook below); a
* shorter one is refused. */
if (!a->scratch || a->scratch_bytes < mxgg_scratch_bytes(M, nout)) return R4D_NO(RAD_E_SCRATCH);
unsigned* cnt = mxgg_out_ctr(q->data);
if (!cnt) return R4D_NO(RAD_E_NOMEM);
R4D_TRY("gemm_mxfp4a8_gated",
mxgg_launch(ablk, actm, x->data, xs->data, w->data, ws->data, wr->data, q->data, sc->data,
y ? y->data : nullptr, a->scratch, cnt, (int)M, (int)K, (int)nout, (int)as_rs,
(int)lda, (int)N, (int)qp, (int)sp, (int)yp, s));
return RAD_OK;
}
/* The op's scratch: the product and amaxes at the band's widest M, from N (twice the gated
* width). */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
if (M < 1 || M > R4D_MXG_MAX_M || N < 256 || N % 256) return 0;
return (int64_t)mxgg_scratch_bytes(M, N / 2);
}
+23
View File
@@ -939,6 +939,29 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
return RAD_OK;
}
/* gemm_nt_q_gated_mx's weights are gemm_nt_q's mxfp4a8 planes in the same stored forms, but its
* `b_ref` is operand 4, where gemm_nt_q has `y`: mapped to gemm_nt_q's index, so both ops ask for
* the reference plane in one form and the loader stores it once. */
static int mx_gated_operand(int operand) {
return operand == Q_B || operand == Q_BSCALE ? operand : operand == 4 ? Q_BREF : -1;
}
extern "C" int r4d_rad_layout_mxfp4_gated(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
const int o = mx_gated_operand(operand);
return o < 0 ? RAD_E_UNSUPPORTED : r4d_rad_layout_mxfp4(p, n_p, o, enc, sel, pl, n, out);
}
extern "C" int r4d_rad_relayout_mxfp4_gated(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
const int o = mx_gated_operand(operand);
return o < 0 ? RAD_E_UNSUPPORTED
: r4d_rad_relayout_mxfp4(p, n_p, o, enc, sel, pl, n, dst, dst_bytes);
}
/* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is
* the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b
* low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same
+7
View File
@@ -459,6 +459,8 @@ int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_gated(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_gated_scratch(const RadArgs*);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
@@ -665,6 +667,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4_gated(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -917,6 +923,7 @@ int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFu
int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated_mx (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
+11 -1
View File
@@ -324,7 +324,13 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
/* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */
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) ps[k] = in4[k];
unsigned int hck = 0u; // the push check (r4d_ar_seq.h)
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) {
const int4 v = in4[k];
ps[k] = v;
hck += r4d_archk_u4(v, 4u * (unsigned)k);
}
r4d_archk_put(hck, peer_flags, nbw, s_slot, (unsigned)b, sq);
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
__syncthreads();
@@ -338,6 +344,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
}
__syncthreads();
if (acq) __threadfence_system();
r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) {
for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR)
h += r4d_archk_u4(ms[k], 4u * (unsigned)k);
});
const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */
const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f;
+50 -5
View File
@@ -1627,6 +1627,20 @@ static const RadOperandSpec oGemmNtQGated[] = {
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* The same fold over an OCP-MXFP4 gate_up weight, which gemm_nt_q reads with a per-row reference
* exponent (`b_ref`) beside its scale plane. A schema of its own rather than an optional operand on
* gemm_nt_q_gated: an op's operand count is part of its contract with the plugins already built
* against it. */
static const RadOperandSpec oGemmNtQGatedMx[] = {
{ "a", RAD_OPD_IN, 0 },
{ "a_scale", RAD_OPD_IN, 0 },
{ "b", RAD_OPD_WEIGHT, 0 },
{ "b_scale", RAD_OPD_WEIGHT, 0 },
{ "b_ref", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
};
/* The gate in a separate operand, as in a gated attention: the gate is a column slice of the
* [q|gate] projection and `x` the attention output, two buffers with different pitches. A row is a
@@ -3363,6 +3377,10 @@ static const RadOpSchema kSchemas[] = {
"columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. "
"Byte-identical to the two ops it replaces, which is what makes it substitutable "
"rather than a second numerical path."),
SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx,
"gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 "
"(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the "
"epilogue, byte-identical to the two ops it replaces."),
SCHEMA("gate_quant_fp8", pGateQuantFp8, oGateQuantFp8,
"the same, with the gate in its own operand rather than packed beside x."),
SCHEMA("quant_act_fp8", pQuantActFp8, oQuantActFp8,
@@ -4808,6 +4826,13 @@ static const RadConstraint cGemmNtQGatedFp8[] = {
C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048),
C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"),
};
/* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block
* per 16-column tile pair of the gated output; N/2 a multiple of 128, so each 128-column group's eight
* blocks meet at its last arriver, which quantises the group. */
static const RadConstraint cGemmNtQGatedMx[] = {
C_LE("M", 8), C_DIV("K", 128), C_DIV("N", 256), C_EQ("group", 32), C_IN("dtype", "mxfp4a8"),
C_IN("act", "silu gelu_tanh"),
};
static const RadConstraint cGateQuantFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
};
@@ -7742,6 +7767,26 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gemv, nullptr,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_gated_gemv", "gemm_nt_q_gated_mx", "gemm",
"the gemv row's WMMA form over a gate_up weight with gated_quant_fp8's pass in its epilogue: a "
"block per 16-column tile of the gated output, that form's eight K waves on the gate tile and "
"eight on the up tile, the block's bf16 product and row amaxes in the op's scratch and the last "
"of a 128-column group's blocks to arrive writing its codes and scales, so the [M, 2n] bf16 "
"product is never written",
"M <= 8; K a multiple of 128; N a multiple of 256 (the gated width a multiple of the 128-column "
"scale group); act silu, or gelu_tanh without out_bf16; the skinny kernel's fragment-order weight, [K/32][N] E8M0 "
"exponents and per-row reference exponent, gate rows then up rows",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K, and the "
"QUANTISER's outputs: E4M3 codes, an f32 scale per (row, 128 columns) and an optional bf16 "
"product. Byte-identical to gemm_mxfp4a8_gemv followed by gated_quant_fp8 (silu), or by gelu_mul "
"and quant_act_fp8 (gelu_tanh)",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGemmNtQGatedMx), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gated, r4d_rad_gemm_mxfp4a8_gated_scratch,
r4d_rad_layout_mxfp4_gated, r4d_rad_relayout_mxfp4_gated, nullptr, nullptr,
/* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */
r4d_fuse_gemm_nt_q_gated_mx },
{ "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver "
"reduction, the weight unpacked through LDS, streaming weight loads",
@@ -9704,11 +9749,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
* every collective the peer flags and exchange buffers the all-reduces own
*
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output;
* gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) split partial is the
* op's scratch and its arrival counters are keyed on the output alone;
* router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken at init, one
* per declared op and band). Concurrent launches never share these, so those four rows are
* concurrent. A new row with stream-ordered state belongs in the list above.
* gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) and
* gemm_mxfp4a8_gated_gemv's split partials are the op's scratch and their arrival counters are keyed
* on the output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance
* (taken at init, one per declared op and band). Concurrent launches never share these, so those
* five rows are concurrent. A new row with stream-ordered state belongs in the list above.
*
* lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they
* update and refills the pools they read between steps with its own copies,
+227
View File
@@ -5999,6 +5999,15 @@ static int launch_row(const RadKernelInfo* r, std::vector<RadTensor> ts,
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
if (r->scratch) {
const int64_t need = r->scratch(&a);
if (need < 0) return (int)need;
if (need > 0) {
a.scratch = dalloc((size_t)need);
a.scratch_bytes = need;
if (!a.scratch) return RAD_E_NOMEM;
}
}
const int rc = r->launch(&a, (RadStream)nullptr);
if (rc != RAD_OK) return rc;
return st_stream_sync(nullptr) == hipSuccess ? RAD_OK : RAD_E_STATE;
@@ -6073,6 +6082,162 @@ static void w4a8_multi_user_exact(const Plugin& pl) {
}
}
/* ---- the MXFP4 gated fold, against the pair it replaces -------------------------------------
*
* gemm_mxfp4a8_gated_gemv (gemm_nt_q_gated_mx) against gemm_mxfp4a8_gemv followed by
* gated_quant_fp8, on the same weight bytes (one relayout, through the gemv row's hooks, which the
* gated row shares) and activation. Codes, scales and the bf16 product must be identical, and the
* codes mostly non-zero (zeroed buffers compare equal). Run twice: with `out_bf16`, and without it,
* where the codes and scales must still match. */
static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K, bool ablk,
bool gelu = false) {
const char* row = "gemm_mxfp4a8_gated_gemv";
if (!sel(row)) return;
char nm[192];
std::snprintf(nm, sizeof nm, "%s byte-identical to gemv + %s, M=%lld N=%lld K=%lld%s", row,
gelu ? "gelu_mul + quant_act_fp8" : "gated_quant_fp8", (long long)M, (long long)N,
(long long)K, ablk ? " ascale=row x 128" : "");
const RadKernelInfo* rg = find(pl, row);
const RadKernelInfo* rv = find(pl, "gemm_mxfp4a8_gemv");
const RadKernelInfo* rq = find(pl, gelu ? "quant_act_fp8" : "gated_quant_fp8");
const RadKernelInfo* rm = find(pl, "gelu_mul_bf16");
if (!rg || !rv || !rq || (gelu && !rm) || !rg->layout || !rg->relayout) {
ok(nm, false, "row or hooks absent");
return;
}
Planes p;
p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale");
if (ic < 0 || is < 0) { ok(nm, false, "encoding has no codes/scale plane"); return; }
mxfp4_fill(p, ic, is, N, K, 0x51u, true);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
/* Stored through the gated row's own hooks (its `b_ref` is operand 4), so the gemv row reading
* the same bytes also checks that both ops store the planes in one form. */
if (stored(rg, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(rg, lp, 3, p, { "scale" }, &ws) != RAD_OK ||
stored(rg, lp, 4, p, { "scale" }, &wr) != RAD_OK) {
ok(nm, false, "relayout refused");
return;
}
/* The reference plane through the gemv row's own hook (its operand 6) must be the same bytes:
* a remap that handed the gated row's b_ref another form would otherwise pass, both kernels
* reading the same wrong plane. */
{
std::vector<uint8_t> wr_gemv;
if (stored(rv, lp, 6, p, { "scale" }, &wr_gemv) != RAD_OK || wr_gemv != wr) {
ok(nm, false, "b_ref stored differently by the gated and gemv rows");
return;
}
}
const int64_t nkb = K / 128, n = N / 2, gkb = n / 128;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> as((size_t)(M * (ablk ? nkb : 1)));
for (int64_t i = 0; i < M; ++i) {
if (ablk)
for (int64_t c = 0; c < nkb; ++c)
as[(size_t)(i * nkb + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * nkb + c)) % 97);
else
as[(size_t)i] = 0.0125f * (float)(1 + st_mix32((uint32_t)i ^ 0xa5u) % 5);
for (int64_t k = 0; k < K; ++k) rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, 0x3cu));
}
void* d_a = dalloc(ha.size());
void* d_s = dalloc(as.size() * 4);
void* d_w = dalloc(wq.size());
void* d_e = dalloc(ws.size());
void* d_r = dalloc(wr.size());
void* d_y = dalloc((size_t)(M * N * 2));
void* d_q[3] = { dalloc((size_t)(M * n)), dalloc((size_t)(M * n)), dalloc((size_t)(M * n)) };
void* d_z[3] = { dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)), dalloc((size_t)(M * gkb * 4)) };
void* d_b[2] = { dalloc((size_t)(M * n * 2)), dalloc((size_t)(M * n * 2)) };
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y || !d_q[2] || !d_z[2] || !d_b[1]) {
ok(nm, false, "hipMalloc failed");
return;
}
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
const RadTensor ta = T(d_a, RAD_F8E4M3, { M, K });
const RadTensor tas = ablk ? T(d_s, RAD_F32, { M, nkb }) : T(d_s, RAD_F32, { M });
const RadTensor tw = T(d_w, RAD_U8, { (int64_t)wq.size() }), te = T(d_e, RAD_U8, { (int64_t)ws.size() });
const RadTensor tr = T(d_r, RAD_U8, { (int64_t)wr.size() });
/* The pair. */
RadTensor none = T(nullptr, RAD_F32, { 1 });
absent(none);
int rc = launch_row(rv, { ta, tas, tw, te, T(d_y, RAD_BF16, { M, N }), none, tr },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") });
if (rc == RAD_OK && !gelu)
rc = launch_row(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q[0], RAD_F8E4M3, { M, n }),
T(d_z[0], RAD_F32, { M, gkb }), T(d_b[0], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") });
if (rc == RAD_OK && gelu) {
rc = launch_row(rm, { T(d_y, RAD_BF16, { M, N }), T(d_b[0], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_b[0], RAD_BF16, { M, n }), T(d_q[0], RAD_F8E4M3, { M, n }),
T(d_z[0], RAD_F32, { M, gkb }) },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16") });
}
if (rc != RAD_OK) { ok(nm, false, "the chain: rc=" + std::to_string(rc)); return; }
/* The fold, with and without the bf16 product (the GeGLU form refuses it, asserted). */
const std::vector<RadParam> gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8"), PS("act", gelu ? "gelu_tanh" : "silu") };
for (int v = 1; v <= 2; ++v) {
st_memset(d_q[v], 0, (size_t)(M * n));
st_memset(d_z[v], 0, (size_t)(M * gkb * 4));
}
st_memset(d_b[1], 0, (size_t)(M * n * 2));
rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }),
T(d_z[1], RAD_F32, { M, gkb }), T(d_b[1], RAD_BF16, { M, n }) }, gp);
if (gelu) {
if (rc == RAD_OK) { ok(nm, false, "the GeGLU fold served out_bf16"); return; }
rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[1], RAD_F8E4M3, { M, n }),
T(d_z[1], RAD_F32, { M, gkb }), none }, gp);
st_memcpy(d_b[1], d_b[0], (size_t)(M * n * 2), hipMemcpyDeviceToDevice);
}
/* Twice into one output, cleared between: the split's arrival counters are keyed on the output,
* so the second launch reduces only if the first left them zero. */
for (int rep = 0; rep < 2 && rc == RAD_OK; ++rep) {
st_memset(d_q[2], 0, (size_t)(M * n));
st_memset(d_z[2], 0, (size_t)(M * gkb * 4));
rc = launch_row(rg, { ta, tas, tw, te, tr, T(d_q[2], RAD_F8E4M3, { M, n }),
T(d_z[2], RAD_F32, { M, gkb }), none }, gp);
}
if (rc != RAD_OK) { ok(nm, false, "the fold: rc=" + std::to_string(rc)); return; }
std::vector<uint8_t> c[3];
std::vector<float> z[3];
for (int v = 0; v < 3; ++v) {
c[v].resize((size_t)(M * n));
z[v].resize((size_t)(M * gkb));
st_memcpy(c[v].data(), d_q[v], c[v].size(), hipMemcpyDeviceToHost);
st_memcpy(z[v].data(), d_z[v], z[v].size() * 4, hipMemcpyDeviceToHost);
}
std::vector<uint16_t> b0((size_t)(M * n)), b1((size_t)(M * n));
st_memcpy(b0.data(), d_b[0], b0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(b1.data(), d_b[1], b1.size() * 2, hipMemcpyDeviceToHost);
int nc = 0, nz = 0, nb = 0, nc2 = 0, nz2 = 0, live = 0;
for (size_t i = 0; i < c[0].size(); ++i) {
nc += c[0][i] != c[1][i];
nc2 += c[0][i] != c[2][i];
live += c[1][i] != 0;
}
for (size_t i = 0; i < z[0].size(); ++i) {
nz += std::memcmp(&z[0][i], &z[1][i], 4) != 0;
nz2 += std::memcmp(&z[0][i], &z[2][i], 4) != 0;
}
for (size_t i = 0; i < b0.size(); ++i) nb += b0[i] != b1[i];
ok(nm, nc == 0 && nz == 0 && nb == 0 && nc2 == 0 && nz2 == 0 && live > (int)c[1].size() / 2,
"codes differ " + std::to_string(nc) + "/" + std::to_string(nc2) + ", scales " +
std::to_string(nz) + "/" + std::to_string(nz2) + ", bf16 " + std::to_string(nb) +
", nonzero " + std::to_string(live) + " of " + std::to_string(c[1].size()));
}
/* ---- the audio generator's ops and their optional forms, against libref's arithmetic ----------
*
* Each case builds its operands on the host, runs the row, and compares with the host port of the
@@ -13140,6 +13305,31 @@ static void mx_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8") };
perf_row(pl, row, ts, ps, d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters);
/* At a gate_up shape the gemv row's GEMM is half of a pair: time the other half
* (gated_quant_fp8 over its output) and the fold that replaces both. */
if (!std::strcmp(row, "gemm_mxfp4a8_gemv") && N % 256 == 0 && K % 128 == 0) {
const int64_t n = N / 2;
void* d_q = dalloc((size_t)(M * n));
void* d_z = dalloc((size_t)(M * (n / 128) * 4));
if (!d_q || !d_z) { std::printf(" gated: hipMalloc failed\n"); continue; }
RadTensor nob = T(nullptr, RAD_BF16, { M, n });
absent(nob);
perf_row(pl, "gated_quant_fp8", { T(d_y, RAD_BF16, { M, N }), T(d_q, RAD_F8E4M3, { M, n }),
T(d_z, RAD_F32, { M, n / 128 }), nob },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") },
d_y, (size_t)(M * N * 2), 1, (double)(M * N * 2), iters, 0);
const RadKernelInfo* rg = find(pl, "gemm_mxfp4a8_gated_gemv");
std::vector<uint8_t> gr;
if (rg && stored(rg, lp, 4, p, { "scale" }, &gr) == RAD_OK && gr == wr)
perf_row(pl, "gemm_mxfp4a8_gated_gemv",
{ T(d_a, RAD_F8E4M3, { M, K }), T(d_s, RAD_F32, { M, nkb }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_r, RAD_U8, { (int64_t)wr.size() }), T(d_q, RAD_F8E4M3, { M, n }),
T(d_z, RAD_F32, { M, n / 128 }), nob },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"),
PS("act", "silu") },
d_w, wq.size(), copies, (double)(wq.size() + ws.size()), iters);
}
}
}
@@ -23517,6 +23707,32 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs, co
if (row->fini) { row->fini(a.inst); row->fini(b.inst); }
}
/* Every peer push landing after its flag (the kernel's test mode, R4D_AR_TEST_LATE_PUSH): a push
* over PCIe P2P sometimes lands a microsecond or more after the release flag that follows it, so a
* reader that trusted the flag would sum the slot's previous contents. The push check
* (r4d_ar_seq.h) makes the reader wait for the bytes; here every launch of the sweep needs it. */
static void ar_two_rank_late(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
setenv("R4D_AR_TEST_LATE_PUSH", "1", 1);
ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] };
std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b);
ta.join();
tb.join();
unsetenv("R4D_AR_TEST_LATE_PUSH");
ok("2-rank all-reduce init, pushes landing after their flags",
a.rc_init == RAD_OK && b.rc_init == RAD_OK,
"rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init));
if (a.rc_init != RAD_OK || b.rc_init != RAD_OK) return;
ok("2-rank all-reduce, every push landing ~20 us after its flag, 32 rounds, every sum exact on "
"both ranks",
a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && a.bad == 0 && b.bad == 0,
"rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + ", " +
std::to_string(a.bad + b.bad) + " elements wrong");
if (row->fini) { row->fini(a.inst); row->fini(b.inst); }
}
/* ------------------------------------------------------------------ the two-rank all-gather */
/* The payload is what the vocab-parallel sampler gathers: (u32 global token id, f32 logit) pairs.
* A token id's bit pattern read as f32 is a denormal, so an all-gather emulated by an all-reduce
@@ -27888,6 +28104,16 @@ static void device_phase(const Plugin& pl) {
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1088, 576, true);
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_gemv", 1056, 576, false);
mxfp4a8_m_invariant(pl, "gemm_mxfp4a8_decode", 5120, 5120, true);
/* The gated fold against the pair it replaces (gemv + gated_quant_fp8): Qwen's and
* TranslateGemma's per-rank gate_up at every M of the band, one group of 128 at the smallest
* K, and the per-row activation scale. */
for (const int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8 }) mxfp4a8_gated_case(pl, m, 17408, 5120, true);
mxfp4a8_gated_case(pl, 8, 21504, 5376, true);
mxfp4a8_gated_case(pl, 3, 256, 256, true);
mxfp4a8_gated_case(pl, 5, 1024, 640, false);
for (const int64_t m : { 1, 4, 8 }) mxfp4a8_gated_case(pl, m, 21504, 5376, true, true);
mxfp4a8_gated_case(pl, 3, 256, 256, true, true);
mxfp4a8_gated_case(pl, 2, 1024, 640, false, true);
/* Parts (ParoQuant): each weight part against its own activation copy, with bounds off any
* kernel's tile, two and three parts, at every band. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144);
@@ -29012,6 +29238,7 @@ static void device_phase(const Plugin& pl) {
if (!std::strcmp(base, "ar_oneshot_2rank_exact")) {
ar_two_rank(pl, devs, n.c_str());
ar_two_rank_sweep(pl, devs, n.c_str());
ar_two_rank_late(pl, devs, n.c_str());
} else {
gather_two_rank(pl, devs, n.c_str());
}