radiance 1.2.0

- MXFP4 weights: block-fp8 Qwen3.5/3.6/3.8 dense models serve OCP-MXFP4 linears (e2m1, an E8M0
  exponent per 32) at 4-bit weights against E4M3 activations. New libr4d rows: the decode GEMM
  (M <= 128, split-K with a fused last-arriver reduction) and the prefill GEMM on a fragment-tiled
  activation. Qwen3.8-27B MXFP4 (AMD Quark AWQ) is in the model table.
- Cards without peer-to-peer access serve: every collective has a host-memory twin; --p2p
  auto|on|off.
- Stop strings apply to the answer, not to the reasoning block a reply starts in.
- A prefix hit ends one drafter window before the prompt's end, so a windowed block drafter
  (DFlash2) drafts from the first token of a follow-up turn.
This commit is contained in:
Deadcode committed 2026-10-06 21:36:24 +02:00
1 parent 7001841e45
commit e95d397288
47 files changed
+2611 -219

No files matched your search

+2
View File
@@ -108,6 +108,8 @@ set(R4D_UNITS
"r4d_gemm_w4a8_tiled|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
"r4d_gemm_w4a8_prefill|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
"r4d_gemm_mxfp4a8_nt_m64|"
"r4d_gemm_mxfp4a8_tiled|"
"r4d_gemm_mxfp4a8_decode|"
# Block-scaled FP8 -- the format Qwen3.8-27B-FP8 ships in.
# No -D: the 128x128 block is a property of the checkpoint on disk and not a quantiser choice
# like RAD_W4_GROUP, so it is a constant in the source and the entry points reject a mismatch.
+2
View File
@@ -52,6 +52,8 @@ target architecture. They are reported by the `r4d_*_dims()` accessors in
| `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny |
| `gemm_w2a8_nt` | 2-bit weight against int8 activation — the fast draft head |
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
| `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_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 |
| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window — a block-diffusion drafter's geometry. Decode only; `attn_h128_gqa4_have_prefill()` reports 0 so a caller routes long queries to its own fallback |
| `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage |
| `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups |
+21 -1
View File
@@ -262,6 +262,11 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon
void r4d_ar_ipc_free(long p);
void r4d_ar_ipc_memzero(long p, long size);
void r4d_ar_ipc_enable_peer(long peer);
// Exchange buffers in pinned, fine-grained HOST memory, for cards that cannot reach each other's
// VRAM: every card reads and writes the same host pages over its own link. Zeroed, and the
// returned address is valid on every card and on the CPU alike. Startup-only.
long r4d_ar_host_alloc(long size);
void r4d_ar_host_free(long p);
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2).
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
@@ -547,10 +552,25 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i
// OCP-MXFP4 weight, fp8 activation. e2m1 elements with one E8M0 exponent per 32 K, folded
// against a per-row reference exponent so the inner loop has no rescale; fp8 WMMA.
// as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW, long stream);
int M, int K, int N, int WV, int SK, int MB, int NPW,
int as_group, int as_rs, long stream);
int r4d_gemm_mxfp4a8_nt_m64_max_m(void);
int r4d_gemm_mxfp4a8_nt_m64_group(void);
// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a
// FRAGMENT-ORDERED copy of the activation (`at`, written by r4d_mxfp4a8_tile_a, at least
// r4d_mxfp4a8_tile_a_bytes long) and unpacks the weight once per K slab. TN (2 or 4, 0 = by M) is
// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row,
// 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs, long stream);
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream);
long r4d_mxfp4a8_tile_a_bytes(int M, int K);
int r4d_gemm_mxfp4a8_tiled_group(void);
// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's
// scratch, which only the plugin ABI hands over.
int r4d_gemm_mxfp4a8_decode_max_m(void);
// ---- BLOCK-SCALED FP8: the format a checkpoint ships in ----------------------------------------
//
+69 -21
View File
@@ -120,6 +120,9 @@ struct ArInst {
* that buys nothing but round trips: at a 2048-token prefill chunk the capacity rule asks for
* 936 blocks and the tuning rule asks for 24. */
int nb_cap = 0;
/* Where the exchange buffers live: 0 in each rank's own VRAM, written by its peers over P2P;
* 1 in pinned host memory that every card reaches over its own link (build, below). */
int host = 0;
};
/* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one
@@ -150,13 +153,14 @@ long align16(long v) { return (v + 15) & ~15L; }
* residual that is 40 MiB a slot and 80 MiB for the pair. ONE set serves every op that resolved
* to the same (rank, world, dtype, bound) -- see the cache below, which is what keeps a 64-layer
* model from building 128 of these. */
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code) {
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int host) {
if (world < 2 || world > R4D_MAX_RANKS) return RAD_E_SHAPE;
if (rank < 0 || rank >= world) return RAD_E_INVAL;
if (max_numel <= 0) return RAD_E_INVAL;
in->rank = rank;
in->world = world;
in->host = host;
in->dtype = dtype_code;
in->esize = r4d_ar_esize(dtype_code);
in->max_numel = (long)max_numel;
@@ -196,12 +200,26 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
* invalidates. libr4d's driver falls back to coarse when fine fails; so does this, because a
* deterministic fallback stays symmetric across ranks (same environment, same hardware). */
int fine_sc = 1, fine_fl = 1, fine_sq = 1;
/* WITHOUT PEER ACCESS THE MAILBOX MOVES TO THE HOST, AND NOTHING ELSE CHANGES. Every kernel in
* the family touches another rank only through its scratch slots and its flag words -- its
* input, its output and its sequence counters are its own card's -- so with those two in
* pinned host memory no card ever addresses another card's VRAM, and the same kernels run on a
* machine whose PCIe topology or IOMMU forbids peer traffic. A push then lands in host memory
* over the writer's link and the reduce reads it back over the reader's, so a message crosses
* two links where P2P crosses one; that is the price, and it is paid only where P2P is absent
* (the rows that take this path require device.p2p == 0, r4d_rows.cpp). The sequence counters
* stay in VRAM: only their own rank reads them. */
R4D_TRY("ar_ipc_alloc",
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
if (host) {
sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes);
fl = r4d_ar_host_alloc(flag_words * 4);
} else {
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
}
sq = r4d_ar_ipc_alloc(2L * maxb * 4, 1, handle, &hlen);
if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(2L * maxb * 4, 0, handle, &hlen); });
if (!sc || !fl || !sq) return RAD_E_NOMEM;
@@ -258,7 +276,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
in->peer_scratch[j] = g_rv.scratch[r];
in->peer_flags[j] = g_rv.flags[r];
++j;
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
if (!host) R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
}
/* Second barrier: no rank may launch until every rank has enabled peer access, or the first
@@ -295,8 +313,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
struct CacheKey {
int rank, world, dtype;
long long numel;
int host;
bool operator==(const CacheKey& o) const {
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel;
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel &&
host == o.host;
}
};
@@ -320,7 +340,7 @@ int acquire(const CacheKey& k, ArInst** out) {
* and a rank-keyed entry means no two builders race for the same key. */
ArInst* in = new (std::nothrow) ArInst();
if (!in) return RAD_E_NOMEM;
int rc = build(in, k.rank, k.world, k.numel, k.dtype);
int rc = build(in, k.rank, k.world, k.numel, k.dtype, k.host);
if (rc != RAD_OK) { delete in; return rc; }
{
std::lock_guard<std::mutex> lk(g_cache_mu);
@@ -343,8 +363,13 @@ void release(ArInst* in) {
}
/* Only this rank's own allocations. A peer pointer is the peer's to free, and freeing it here
* would be a double free the moment two ranks tear down in either order. */
r4d_ar_ipc_free(in->my_scratch);
r4d_ar_ipc_free(in->my_flags);
if (in->host) {
r4d_ar_host_free(in->my_scratch);
r4d_ar_host_free(in->my_flags);
} else {
r4d_ar_ipc_free(in->my_scratch);
r4d_ar_ipc_free(in->my_flags);
}
r4d_ar_ipc_free(in->my_seq);
r4d_ar_ipc_free(in->locpack);
delete in;
@@ -354,8 +379,7 @@ void release(ArInst* in) {
/* ------------------------------------------------------------------ init / fini */
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -373,28 +397,35 @@ extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
if (numel <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, dt, numel }, &in);
int rc = acquire(CacheKey{ rank, world, dt, numel, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
}
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_init(p, n_p, rank, world, 0, out);
}
extern "C" int r4d_rad_ar_host_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_init(p, n_p, rank, world, 1, out);
}
/* The fused all-reduce + norm declares `M`(range) and `n` rather than `numel`: its message is the
* post-projection activation. Same world, same buffers, different arithmetic to get the bound. */
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, void** out) {
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, int host,
void** out) {
const long long M = pgeti_hi(p, n_p, "M", 0);
const long long K = pgeti_hi(p, n_p, "n", 0);
if (M <= 0 || K <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K }, &in);
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
}
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_ln_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -402,7 +433,15 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
if (ws_param != world) return RAD_E_SHAPE;
if (world != 2) return RAD_E_SHAPE; /* the handshake is one peer flag per block */
return ar_mn_acquire(p, n_p, rank, world, out);
return ar_mn_acquire(p, n_p, rank, world, host, out);
}
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_ln_init(p, n_p, rank, world, 0, out);
}
extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_ln_init(p, n_p, rank, world, 1, out);
}
/* The four-rank ar_hc_write and ar_gather_hc_write. The key is the family's -- {rank, 4, bf16,
@@ -413,8 +452,8 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
* (r4d_ar_wide.h), so ops sharing an instance interleave in any order every rank issues them in,
* and ops on separate instances touch nothing of each other's. Exact wire only: the rows constrain
* `wire` to 0, and a `wire` 6 that reaches this init anyway is refused. */
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host,
void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -423,7 +462,16 @@ extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int
if (world != 4) return RAD_E_SHAPE; /* the peer bundle is compiled for four */
if (pgeti_hi(p, n_p, "wire", 0) != 0) return RAD_E_UNSUPPORTED;
return ar_mn_acquire(p, n_p, rank, world, out);
return ar_mn_acquire(p, n_p, rank, world, host, out);
}
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_hc_wide_init(p, n_p, rank, world, 0, out);
}
extern "C" int r4d_rad_ar_hc_wide_host_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_hc_wide_init(p, n_p, rank, world, 1, out);
}
extern "C" void r4d_rad_ar_fini(void* instance) {
+23
View File
@@ -489,6 +489,29 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
void r4d_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); }
void r4d_ar_ipc_memzero(long p, long size) { if (p) HIPOK(hipMemset((void*)p, 0, size)); }
// THE HOST MAILBOX. Coherent so a peer's stores are not held in a CPU cache line this card reads
// around, mapped so the cards address it, portable so every card does and not only the one
// current at allocation. A card reaches it through the same fine-grained path a peer's VRAM
// scratch is reached by, so the kernels' fences mean what they mean there. The address a card
// uses must be the CPU's own, because one pointer is published to every rank: a mapping that put
// the pages elsewhere on some card would have each rank write where no other rank reads.
long r4d_ar_host_alloc(long size) {
void* p = nullptr;
HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped |
hipHostMallocPortable));
std::memset(p, 0, (size_t)size);
void* d = nullptr;
const hipError_t e = hipHostGetDevicePointer(&d, p, 0);
if (e != hipSuccess || d != p) {
(void)hipHostFree(p);
throw std::runtime_error(e != hipSuccess
? std::string("host mailbox: no card address: ") + hipGetErrorString(e)
: std::string("host mailbox: the card address differs from the CPU address"));
}
return (long)p;
}
void r4d_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); }
// Enable direct peer access. radiance runs one process with a thread per rank sharing an address
// space, so a peer pointer is valid here once this has run and no IPC handle exchange is needed;
// see the header of r4d_ar_entry.hip.
+12
View File
@@ -334,6 +334,16 @@ struct R4dGemmCfg { int wv, sk, mb, npw, nt; };
* not compute the GEMM and then pick it. */
struct R4dTileCfg { int variant; int bm; int bn; };
/* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block,
* TN=4 a 256 x 128 one. Its crossover is a function of M (r4d_gemm_mxfp4a8_tiled.hip carries the
* measurement), so 0 -- the default -- decides at issue and a fixed value is for a tuner. */
struct R4dMxTileCfg { int tn; };
/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in
* r4d_gemm_mxfp4a8_decode.hip (it needs M and the shape, which exist only at issue); `nt` 1 streams
* the weight past L2/MALL, 2 loads it plainly. */
struct R4dMxDecCfg { int ks; int bk; int nt; };
/* Split-KV segment count for the paged decode kernels. 0 is libr4d's own split law, which is
* measured (r4d_attn_paged_h256_gqa6.hip carries the table) and reads num_seqs and max_ctx that
* only exist at issue -- so it stays the default and the fixed counts are there for a tuner that
@@ -375,6 +385,8 @@ extern "C" {
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
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*);
void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*);
+24
View File
@@ -321,6 +321,30 @@ struct GemmOps {
long long M, N, K;
};
/* THE MXFP4 GEMMS' ACTIVATION SCALE GRID, read off the operand rather than assumed. One f32 a row
* (`[M]` or `[M][1]`: a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`:
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
* at the wrong width is an answer that is merely wrong. */
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
const RadTensor* s = g.ascale;
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
long long cols = 1, rstride = 1;
if (s->rank >= 2) {
cols = s->shape[s->rank - 1];
rstride = s->stride[s->rank - 2];
if (s->shape[s->rank - 2] < g.M) return R4D_NO(RAD_E_SHAPE);
} else if (s->rank == 1) {
if (s->shape[0] < g.M) return R4D_NO(RAD_E_SHAPE);
cols = s->shape[0] / g.M;
rstride = cols;
}
const long long kb = (g.K + 127) / 128;
if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; }
return R4D_NO(RAD_E_SHAPE);
}
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
* checked here beyond being present, which is deliberate: the byte count that matters is the one
+617
View File
@@ -0,0 +1,617 @@
// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the DECODE
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T over the same operands, weight
// layout and fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled.
//
// WHY A THIRD MXFP4 KERNEL. At decode the GEMM is a weight stream: a speculative verify step is
// a handful of rows against the whole 4-bit trunk, and the only number that matters is how close
// the stream runs to the card's DRAM bandwidth. The skinny kernel splits K inside one workgroup
// and reads the weight straight into registers, which leaves the narrow projections well short of
// it. This one splits K ACROSS workgroups with a fused last-arriver reduction, unpacks the weight
// through LDS, gives each block one 16-row A fragment per M tile, and streams the weight with
// non-temporal loads.
//
// THE TILE. A block is DWN = 8 waves over BND = 128 output columns, one 16-column fragment a wave,
// and DTM 16-row M fragments -- the SMALLEST that covers M, because a wider tile computes rows
// nobody asked for. A K slab of DBK bytes is staged: A (16*DTM rows) and the weight's 128 rows,
// unpacked to e4m3 with the block exponent folded in through r4d_mxfp4.h, as the other two MXFP4
// kernels fold it.
//
// SPLIT-K IS NOT OPTIONAL. With one 16-row M fragment the independent N fragments number N/16, so
// N=5120 is 320 waves -- 2.5 a SIMD however the N tile is chosen. DKS blocks split the K slabs;
// each writes an fp32 partial [DKS][M][N] and the LAST to arrive (an agent-scope counter per column
// block) sums them in place, so there is no second launch.
//
// THE SPLIT, SLAB AND LOAD HINT are a rule measured cell by cell on this kernel -- every split x
// slab x hint against the 27B's per-rank shapes at M = 8..128, DRAM-fed -- because no single
// fill target fits: the split is the smallest power of two whose grid reaches 48 blocks at M <= 16,
// 56 at M <= 96 and 40 above (an unsplit 40-block grid already streams a short-K weight at the
// card's rate there, and a split's partial traffic grows with M); a deep K (8192 or more, down at
// K=8704) keeps doubling while a split still has 24 or more 128-wide slabs, since 40-odd blocks
// do not keep its long slab loop fed; and no split goes past ks*M = 512, where the partials
// outweigh what the split buys. The slab is 128 except where LDS per block, (16*DTM + 128) *
// (DBK+8) bytes, would cost a wide or deeply split grid its resident blocks (see mxd_plan); a K
// that is not a multiple of 128 takes 64 (and a 2-way split widens to 4). Weight loads are non-temporal for weights of 4 MiB or more,
// plain below, where the weight is too small to evict anything the split partials need. All three
// are tunables (`ks`, `bk`, `nt`) whose 0 is this rule.
//
// NO STATE IS KEYED ON THE STREAM. The split partial is the op's own scratch -- the core sizes it
// from the scratch hook and treats it as read+write, so two ops that could overlap get disjoint
// slices -- and the arrival counters are a small block keyed on the OUTPUT buffer (mxd_out_ctr),
// zero at entry and left zero by the reducer. A recorded pass is replayed with its recorded
// arguments, possibly on another stream than it was recorded on, so a pointer that depended on the
// stream would make the replay differ from its recording. Two launches writing the same output are
// ordered by that dependency; two that can overlap write different outputs. The row is therefore
// concurrent (rad_kernel_concurrent), as gemm_fp8a8_nt_m16 is. A scratch shorter than the split
// needs is refused: the hook sizes it for every M of the band, so a short one is a caller's error.
//
// Every thread fences its partial stores before the counter: a fence on thread 0 alone orders
// only thread 0's stores, and the reducer would then read whatever happened to drain.
//
// TWO ACTIVATION SCALE GRIDS, as in the tiled kernel: one f32 a row, or one a (row, 128 of K). The
// per-block form carries each row's accumulator in the current block's scale and rescales it by
// s_prev / s_next at each 128 boundary, the ratio computed once a row into LDS from scales loaded a
// boundary early; with the accumulator transposed a lane reads one ratio for each of its rows. A split's partial is brought back
// to absolute units before it is written, because the splits end in different blocks.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <map>
#include <mutex>
#include <stdexcept>
#define R4D_MXD_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
#define R4D_MXD_MTILE 16
#define R4D_MXD_MAX_TM 8 // M <= 128
#define R4D_MXD_PAD 8
#define R4D_MXD_MAX_KS 16
#define R4D_MXD_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
typedef int mxd_v2i __attribute__((ext_vector_type(2)));
typedef unsigned mxd_u2 __attribute__((ext_vector_type(2)));
typedef unsigned mxd_u4 __attribute__((ext_vector_type(4)));
typedef float mxd_f4 __attribute__((ext_vector_type(4)));
template <bool NT, typename T>
static __device__ __forceinline__ T mxd_ld(const T* p) {
if constexpr (NT) return __builtin_nontemporal_load(p);
else return *p;
}
// ---- what both kernels share: the scale grid at a 128 boundary, and the epilogue.
//
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
// activation fragment as its B operand -- the two fragments have the same register layout, so
// this is only an argument order -- and computes C^T: a lane's accumulator for M fragment i holds
// ONE row, m = 16i + col, and the eight consecutive columns n0 + 16*wave + kb8 + e. So a row's
// activation scale is one value a lane, not eight: the (row, 128) grid's boundary rescale reads
// DTM scales instead of 8*DTM, and the epilogue writes each lane's eight outputs as one 16-byte
// store (one 32-byte store of partials) instead of eight 2-byte ones.
// THE (ROW, 128) SCALE GRID, computed once a row: thread t < ROWS owns row t. It loads the next
// 128 boundary's two scales -- the block that starts there and the one before it -- a boundary
// early, writes the row's ratio s_prev / s_next to LDS at the boundary (published by the staging
// barrier), and a lane then reads ONE ratio for each of its rows. A zero block keeps the carried
// scale; a zero block before this one sends the carried scale back to the grid, which only an
// all-zero activation block ever does.
static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row,
int kb) {
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
}
template <int DTM>
static __device__ __forceinline__ void mxd_rescale(v8f (&acc)[DTM], const float* sR, int col) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const float r = sR[i * 16 + col];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
}
}
// The split's result: written straight to C when the accumulator holds the whole K range, else as
// an fp32 partial that the last block to arrive on this column block sums. `kb_end` is the block
// the split's last slab ends in (ABLK: the scale the accumulators are carried in).
template <int DTM, int DKS, bool ABLK>
static __device__ __forceinline__ void mxd_epilogue(
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks,
int kb_end, unsigned* s_last, float* sR) {
constexpr int NTHR = R4D_MXD_DWN * 32, BND = R4D_MXD_DWN * 16;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
const int tid = threadIdx.x;
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
// Each row's final scale, once a row: the scale the split's accumulators end in (ABLK), or the
// row's own. The K loop's closing barrier retired the last ratio reads.
if (tid < ROWS) {
const int m = tid < M ? tid : M - 1;
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
}
__syncthreads();
float sc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
if constexpr (DKS == 1) {
if (nb < N) {
const mxd_u2 rb = *(const mxd_u2*)(Wref + nb);
float rf[8];
#pragma unroll
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
union { __hip_bfloat16 h[8]; mxd_u4 v; } o;
#pragma unroll
for (int e = 0; e < 8; ++e)
o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]);
*(mxd_u4*)(C + (size_t)m * N + nb) = o.v;
}
}
}
return;
}
if (nb < N) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
mxd_f4 lo, hi;
#pragma unroll
for (int e = 0; e < 4; ++e) {
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
}
mxd_f4* dst = (mxd_f4*)(P + ((size_t)ks * M + m) * N + nb);
dst[0] = lo;
dst[1] = hi;
}
}
}
// EVERY thread's partial stores are ordered before the counter, then the last arriver reduces.
__threadfence();
__syncthreads();
if (tid == 0)
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (*s_last != (unsigned)(DKS - 1)) return;
if (tid == 0) cnt[blockIdx.x] = 0u; // left clean for the next launch on this stream
__threadfence(); // acquire, before reading the other partials
const int nhi = min(n0 + BND, N);
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
const float rf = __int_as_float((int)Wref[nn] << 23);
for (int m = 0; m < M; ++m) {
float sum = 0.f;
#pragma unroll
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
C[(size_t)m * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
}
}
}
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_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, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
// a split that starts mid-block meets its first boundary one slab in
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
}
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
#pragma unroll
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
const int idx = off + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
{
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
const int kstep0 = k0 / 16;
#pragma unroll
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
const int sl = off + tid * 2;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
const int gn = n0 + r;
// gn is even and N % 16 == 0: clamping to the last even row keeps the 8 B read aligned and
// gc + 1 in bounds; the slot address is recomputed from the clamped row.
const int gc = gn < N - 2 ? gn : N - 2;
const int lanec = (lane_ & 16) | (gc & 15);
const mxd_u2 wv =
mxd_ld<NT>((const mxd_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
lanec]);
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < 2; ++q) {
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * N + gc + q]);
unsigned int lo, hi;
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
}
}
}
__syncthreads();
if constexpr (ABLK) {
if (bnd) mxd_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
mxd_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
// THE ONE-FRAGMENT FORM (M <= 16), which is every single-sequence verify step. The same tile, fold
// and split as above, with two changes that pay only when one M fragment leaves the block waiting
// on memory: the NEXT slab's A, codes and exponents are loaded into registers while this slab
// computes, so a block keeps its loads in flight across the WMMA phase instead of draining at every
// barrier; and a thread takes four adjacent slots, one 16 B load instead of two 8 B ones. Each
// row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at
// every split: the K order, the fold and the reduction are unchanged.
template <int DBK, int DKS, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_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, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
constexpr int DTM = 1, VEC = 4;
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
// per-thread slot geometry, fixed across slabs
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT];
int s_ref[W_IT][VEC];
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const int sl = it * NTHR * VEC + tid * VEC;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15);
const int gn = n0 + r;
const int gc = gn < N - VEC ? gn : N - VEC;
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
#pragma unroll
for (int q = 0; q < VEC; ++q) s_ref[it][q] = (int)Wref[gc + q];
}
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
wv_t rw[W_IT];
int rd[W_IT][VEC];
mxd_u4 ra[A_IT];
auto load = [&](int s) {
const int k0 = s * DBK;
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1;
ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
}
}
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const size_t slot =
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
rw[it] = mxd_ld<NT>((const wv_t*)&Wp[slot]);
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * N + s_gc[it] + q];
}
};
auto store = [&]() {
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
*(mxd_u4*)(&sA[r * STR + c]) = ra[j];
}
}
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
#pragma unroll
for (int q = 0; q < VEC; ++q) {
unsigned int lo, hi;
r4d_mxfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]), &lo, &hi);
*(mxd_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = mxd_u2{lo, hi};
}
}
};
if (s_lo < s_hi) load(s_lo);
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
}
store();
__syncthreads();
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
if constexpr (ABLK) {
if (bnd) mxd_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
mxd_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
namespace {
// THE ARRIVAL COUNTERS, one block an output buffer -- see the header. The counters cannot live in
// the scratch: other ops write the arena between two of ours, and the counters must be zero at
// entry. So they are a small device allocation of their own, taken once per (device, output) and
// kept zero by the reducer, as gemm_fp8a8_nt_m16 keys its split_ctr.
unsigned* mxd_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;
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess) { (void)hipFree(p); return nullptr; }
blocks.emplace(key, p);
return p;
}
// THE SPLIT, SLAB AND LOAD HINT A LAUNCH RUNS, from M, the shape and the tunables (0 = the rule).
// One function for the launch and the scratch hook, so the partial the hook sizes is the one
// written. See the header for the rule and what it was measured on.
struct MxdPlan { int ks, bk; bool nt; };
MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
MxdPlan p;
int ks = 1;
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
p.ks = KS > 0 ? KS : ks;
// 64-wide slabs where LDS per block, (16*DTM + 128)*(DBK+8) bytes, costs a wide or deeply split
// grid its resident blocks: DTM 4 unsplit on 110+ column blocks, and DTM 8 on those or at a 4-way
// split.
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
if (K % p.bk) { // a slab may not run past K
p.bk = 64;
if (p.ks == 2) p.ks = 4;
}
return p;
}
long mxd_partial_bytes(int M, int N, int ks) {
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
}
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
long scratch_bytes) {
if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128");
if (N < 16 || N % 16 || N > R4D_MXD_MAX_N)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: N must be a multiple of 16 up to 36864");
if (K < 64 || K % 64)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: K must be a multiple of 64");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the activation scale is per row or per "
"128 of K");
const MxdPlan pl = mxd_plan(M, K, N, KS, BK, NT);
const int ks = pl.ks, bk = pl.bk;
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
if (bk != 64 && bk != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: BK must be 64 or 128");
if (scratch_bytes < mxd_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the op's scratch is shorter than the split "
"partial; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = mxd_out_ctr((const void*)c);
if (!cnt) throw std::runtime_error("r4d gemm_mxfp4a8_decode: split counter alloc failed");
const bool ablk = as_group == 128, nt = pl.nt;
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
hipStream_t st = (hipStream_t)stream;
dim3 grid(nblk, 1, ks), block(R4D_MXD_DWN * 32);
auto Ap = (const unsigned char*)a;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
#define MXD_L(BK_, KS_, TM_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
#define MXD_L1(BK_, KS_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
#define MXD_AB(BK_, KS_, TM_, NT_) \
{ if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); }
#define MXD_NT(BK_, KS_, TM_) \
{ if (nt) MXD_AB(BK_, KS_, TM_, true) else MXD_AB(BK_, KS_, TM_, false) }
#define MXD_AB1(BK_, KS_, NT_) \
{ if (ablk) MXD_L1(BK_, KS_, NT_, true); else MXD_L1(BK_, KS_, NT_, false); }
#define MXD_NT1(BK_, KS_) { if (nt) MXD_AB1(BK_, KS_, true) else MXD_AB1(BK_, KS_, false) }
#define MXD_TM(BK_, KS_) \
{ switch (tm) { case 1: MXD_NT1(BK_, KS_) break; case 2: MXD_NT(BK_, KS_, 2) break; \
case 3: MXD_NT(BK_, KS_, 3) break; case 4: MXD_NT(BK_, KS_, 4) break; \
case 5: MXD_NT(BK_, KS_, 5) break; case 6: MXD_NT(BK_, KS_, 6) break; \
case 7: MXD_NT(BK_, KS_, 7) break; default: MXD_NT(BK_, KS_, 8) break; } }
#define MXD_KS(BK_) \
{ switch (ks) { case 1: MXD_TM(BK_, 1) break; case 2: MXD_TM(BK_, 2) break; \
case 4: MXD_TM(BK_, 4) break; case 8: MXD_TM(BK_, 8) break; \
default: MXD_TM(BK_, 16) break; } }
if (bk == 64) MXD_KS(64) else MXD_KS(128)
#undef MXD_KS
#undef MXD_TM
#undef MXD_NT1
#undef MXD_AB1
#undef MXD_NT
#undef MXD_AB
#undef MXD_L1
#undef MXD_L
}
} // namespace
extern "C" int r4d_gemm_mxfp4a8_decode_max_m(void) { return R4D_MXD_MTILE * R4D_MXD_MAX_TM; }
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > r4d_gemm_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
R4D_TRY("gemm_mxfp4a8_decode",
mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes));
return RAD_OK;
}
/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
* band times its widest M -- an upper bound on every launch the band can make. */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
const long long K = r4d_geti_or(a, "K", 0);
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_mxfp4a8_decode_max_m()) return 0;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
return (int64_t)mxd_partial_bytes((int)M, (int)N, ks);
}
+69 -40
View File
@@ -68,6 +68,14 @@
// The E8M0 scales are left in [K/32][N] order -- a half-wave reads sixteen consecutive bytes of
// those already.
//
// TWO ACTIVATION SCALE GRIDS, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false), or
// one per (row, 128 of K) (ABLK=true, the block-scaled fp8 family's grid). With ABLK each wave
// carries its partial sums in units of the current 128-block's scale and rescales them by
// s_prev / s_next at each block boundary inside its split-K segment. The segments end in
// DIFFERENT blocks, so each partial is brought back to absolute units -- multiplied by its own
// last scale -- before the LDS reduction adds them, and the epilogue applies only the weight's
// reference factor.
//
// TRAP FOR ANYONE MEASURING THIS KERNEL: a weight of tens of megabytes streamed in a loop is
// Infinity-Cache resident on this part, so a bandwidth figure taken that way can read above the
// DRAM roofline. It ranks kernels reading the same bytes; it is not achieved DRAM bandwidth.
@@ -78,56 +86,36 @@
// the last valid row and the store discards it -- which keeps the inner loop branch-free.
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
#define R4D_GEMM_MXFP4_MAX_M 64
#define R4D_GEMM_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
#define R4D_GEMM_MXFP4_GROUP R4D_MXFP4_GROUP
#define WAVE32 32
typedef int v2i __attribute__((ext_vector_type(2)));
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
// Folded magnitudes: kMag[d] is the eight e2m1 magnitudes scaled by 2^-d, as packed e4m3 bytes,
// low table then high table, indexed by the 3-bit magnitude through v_perm_b32.
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and
// a rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the
// same exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter
// little (such an element is 2.9e-3 of its row's reference) but the table is generated, not
// hand-rounded, so it should agree with the hardware's own conversion.
__device__ __constant__ unsigned int kMag[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
};
// Eight e2m1 codes (four packed bytes) -> eight e4m3 bytes in k order, with the block's exponent
// difference already folded in.
__device__ __forceinline__ v2i r4d_mxfp4_unpack8(unsigned int wv, int dsh) {
const unsigned int t0 = kMag[dsh][0], t1 = kMag[dsh][1];
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
// Eight e2m1 codes (four packed bytes) -> the B fragment, eight e4m3 bytes in k order with the
// block's exponent difference folded in (r4d_mxfp4.h, shared with the other two MXFP4 kernels).
__device__ __forceinline__ v2i r4d_mxfp4_frag8(unsigned int wv, int d) {
unsigned int lo, hi;
r4d_mxfp4_unpack8(wv, d, &lo, &hi);
v2i out;
out[0] = (int)__builtin_amdgcn_perm(bo, be, 0x05010400u); // elements 0..3
out[1] = (int)__builtin_amdgcn_perm(bo, be, 0x07030602u); // elements 4..7
out[0] = (int)lo;
out[1] = (int)hi;
return out;
}
template <int MT, int NPW>
template <int MT, int NPW, bool ABLK>
__global__ void r4d_gemm_mxfp4a8_nt_m64_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, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int WV, int SK) {
int M, int K, int N, int WV, int SK, int as_rs) {
extern __shared__ float red[];
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
const int col_local = wave / SK, ksplit = wave % SK;
@@ -161,8 +149,39 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps = K / 16;
// ABLK: the scale each accumulator row of this lane is carried in -- row (mt0+i)*16 + mhalf + e.
float scur[ABLK ? MT : 1][8];
if constexpr (ABLK) {
#pragma unroll
for (int i = 0; i < MT; i++)
#pragma unroll
for (int e = 0; e < 8; e++) {
int r = (mt0 + i) * 16 + mhalf + e;
r = r < M - 1 ? r : M - 1;
const float s = As[(size_t)r * as_rs + (kbase >> 7)];
scur[i][e] = s > 0.f ? s : 1.f;
}
}
for (int k = 0; k < Ks; k += 16) {
const int kg = kbase + k; // fragment base, both lane halves
if constexpr (ABLK) {
if (k && (kg & 127) == 0) { // a new 128-wide activation block
#pragma unroll
for (int i = 0; i < MT; i++)
#pragma unroll
for (int e = 0; e < 8; e++) {
int r = (mt0 + i) * 16 + mhalf + e;
r = r < M - 1 ? r : M - 1;
float s = As[(size_t)r * as_rs + (kg >> 7)];
s = s > 0.f ? s : scur[i][e];
const float q = scur[i][e] / s;
scur[i][e] = s;
#pragma unroll
for (int j = 0; j < NPW; j++) acc[j][i][e] *= q;
}
}
}
const int kstep = kg / 16;
const int blk = kg / R4D_GEMM_MXFP4_GROUP; // one E8M0 block covers this whole step
v2i af[MT];
@@ -181,9 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
// apart -- a fully strided read on the operand that dominates traffic.
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
int dsh = (int)wref[j] - (int)Ws[(size_t)blk * N + n];
dsh = dsh < 0 ? 0 : (dsh > 15 ? 15 : dsh);
const v2i wf = r4d_mxfp4_unpack8(wv, dsh);
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n]));
#pragma unroll
for (int i = 0; i < MT; i++)
acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]);
@@ -199,7 +216,8 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
for (int j = 0; j < NPW; j++) {
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
#pragma unroll
for (int e = 0; e < 8; e++) red[slot + lane * 8 + e] = acc[j][i][e];
for (int e = 0; e < 8; e++)
red[slot + lane * 8 + e] = ABLK ? acc[j][i][e] * scur[i][e] : acc[j][i][e];
}
__syncthreads();
// One pass over the block's 256-element tiles; every thread takes a stride.
@@ -215,7 +233,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
float v = 0.f;
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
C[(size_t)m * N + n] =
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * As[m]);
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m]));
}
}
}
@@ -225,7 +243,7 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP
extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW,
long stream) {
int as_group, int as_rs, long stream) {
if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
@@ -236,6 +254,9 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: MB must be 1..4");
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: NPW must be 1, 2, 4 or 8");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
const int ntiles = N / 16, mtiles = (M + 15) / 16;
const int ncols = WV * NPW;
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
@@ -249,8 +270,13 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define LAUNCH(MTv, NPv) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv>), grid, \
block, smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK)
#define LAUNCH(MTv, NPv) \
do { \
if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
} while (0)
#define LAUNCH_MB(NPv) switch (MB) { \
case 1: LAUNCH(1, NPv); break; \
case 2: LAUNCH(2, NPv); break; \
@@ -284,6 +310,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
const int group = r4d_gemm_mxfp4a8_nt_m64_group();
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
Cfg c;
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
if (rc != RAD_OK) return rc;
@@ -291,7 +320,7 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
(long)(uintptr_t)s));
as_group, as_rs, (long)(uintptr_t)s));
return RAD_OK;
}
+398
View File
@@ -0,0 +1,398 @@
// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for PREFILL row
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the same operands, the same weight
// layout and the same fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode -- the band
// above theirs.
//
// WHY A SEPARATE KERNEL. The decode kernels give a block at most 128 rows, so at prefill they
// would re-read the whole weight ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each
// weight byte is unpacked once per K slab into LDS, where all four row-waves of the block read it.
//
// A COMES STRAIGHT FROM GLOBAL INTO REGISTERS, NOT THROUGH LDS. Staging A through LDS costs a
// write, a barrier and a second read of the operand the block uses most, and a WMMA A fragment --
// lane l holds row l%16, k-bytes 8*(l/16)..+8 of a 16 x 16 tile -- is 16 rows apart in a row-major
// plane, so it cannot be loaded straight from one either. So A is re-tiled first, into the op's
// scratch, in FRAGMENT ORDER:
//
// AT[((m/16) * (K/16) + k/16) * 256 + ((m%16) + 16 * ((k/8)%2)) * 8 + k%8] = A[m][k]
//
// One 16 x 16 fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so
// every A fragment a wave needs for a slab issues as one clause of global loads off a wave-uniform
// base (SGPR, the SADDR form) and is consumed at the WMMAs. The re-tile is one read and one write
// of A -- tens of microseconds at a 2048-row chunk against the hundreds the A-direct loop saves on
// every large projection -- and it is the op's own, so no producer has to know about the layout.
// Rows past M in the last fragment are written as zeros; they only reach accumulators the
// epilogue drops.
//
// THE WEIGHT AND THE FOLD ARE THE SKINNY KERNEL'S. It reads the fragment-order weight that
// r4d_rad_layout_mxfp4 stores and folds each block's exponent into the e4m3 value through the
// table in r4d_mxfp4.h, so all three MXFP4 kernels produce the same e4m3 byte for every element.
// The table is copied to LDS once per block: read from global it would be a dependent load issued
// behind the A fragments, and the in-order load counter would make the fold wait for all of them.
// 2^(Wref[n]-127) is applied once in the epilogue next to the activation's scale; see
// r4d_gemm_mxfp4a8_nt_m64.hip for the fold and its error analysis.
//
// THE TILE. 8 waves as 4 (M) x 2 (N); a wave owns TM=4 x TN accumulator fragments, so the block
// covers BMF = 4*4*16 = 256 rows and BNF = 2*TN*16 columns. The tall tile is for reuse: every
// weight byte staged is multiplied against 256 rows. TN is the axis that depends on M. Widening
// N halves the column-block count while BMF still masks most of a short M, so TN=4 wins only on
// long prompts; on a 17408x5120 weight the two cross near M=2048. Hence tn=0, the default, picks
// TN=4 from M >= 2048 and TN=2 below. The K slab is 128 at TN=2 and 64 at TN=4 (and 64 at TN=2
// when K is not a multiple of 128): TN=4 holds twice the accumulators, and a 128 slab's A
// fragments on top of them would cost occupancy.
//
// BARRIERS FENCE LDS ONLY. __syncthreads() is a workgroup acquire/release over every address
// space, which drains the global load counter at each barrier. Nothing in global memory is
// shared between the block's waves, so the barrier is scoped to LDS and the next slab's A loads
// stay in flight across it.
//
// STAGING IS CLAMPED, NEVER PREDICATED. A bounds-predicated load lands in its own exec-mask
// region and the compiler then cannot carry a counted s_wait_loadcnt across the merge. Clamped
// (a tile past M reads the last real tile, a weight row past N the last aligned group), a slab's
// loads issue back to back; the epilogue drops what they computed.
//
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
// activation fragment as its B operand -- the two have the same register layout, so this is only
// an argument order -- and computes C^T: a lane's accumulator for (M fragment i, N fragment j)
// holds ONE row and eight consecutive columns. So a row's activation scale is one value a lane
// for each of its TM rows, and the epilogue writes each (i, j) as one 16-byte store.
//
// TWO ACTIVATION SCALE GRIDS. `a_scale` is either one f32 per row (ABLK=false) or one per (row,
// 128 of K) (ABLK=true: the block-scaled fp8 family's grid, which every fused producer in
// arch/common writes). Per-block scales vary along K and so cannot wait for the epilogue. The
// accumulator is carried IN UNITS OF THE CURRENT BLOCK'S SCALE: at each 128 boundary every row's
// partial sum is multiplied by s_prev / s_next, and the epilogue applies the last block's scale --
// one multiply per accumulator element per 128 of K, ~K/128 fp32 ulps of extra rounding. The
// ratio is computed once a row: thread t owns row t of the block, loads the next boundary's two
// scales a boundary early (no slab waits on a scale load) and writes the ratio to LDS, and a lane
// reads one ratio for each of its TM rows.
//
// TRAP FOR ANYONE MEASURING THIS KERNEL: the same as the skinny kernel's. A weight of tens of
// megabytes streamed in a loop is Infinity-Cache resident on this part, so a bandwidth figure
// taken that way reads above the DRAM roofline.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
#define R4D_MXT_TM 4 // 16-row fragments per wave
#define R4D_MXT_WM 4 // waves along M
#define R4D_MXT_WN 2 // waves along N
#define R4D_MXT_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
#define R4D_MXT_NTHR (R4D_MXT_WM * R4D_MXT_WN * 32)
#define R4D_MXT_BMF (R4D_MXT_WM * R4D_MXT_TM * 16)
#define R4D_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
#define R4D_MXT_TN4_MIN_M 2048 // tn=0's crossover, see above
typedef int mxt_v2i __attribute__((ext_vector_type(2)));
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
typedef unsigned mxt_u4 __attribute__((ext_vector_type(4)));
static __device__ __forceinline__ void mxt_lds_barrier() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
__builtin_amdgcn_s_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
}
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane, so the writes are
// contiguous and each lane reads one 8-byte group of one row.
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
long long slots) {
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
if (o >= slots) return;
const int ks = K / 16;
const int lane = (int)(o & 31);
const long long f = o >> 5;
const int mt = (int)(f / ks), kst = (int)(f % ks);
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
mxt_u2 v = { 0u, 0u };
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k);
*(mxt_u2*)(AT + o * 8) = v;
}
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs) {
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[32];
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int wm = wave / WN, wn = wave % WN;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
const int ksteps = K / 16, Mt = (M + 15) >> 4;
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
// One A base per M fragment: wave-uniform, so readfirstlane keeps it in an SGPR and every load
// takes the SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
const unsigned char* abase[TM];
#pragma unroll
for (int i = 0; i < TM; ++i) {
int mt = (m0 >> 4) + wm * TM + i;
mt = mt < Mt - 1 ? mt : Mt - 1;
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
}
const unsigned int aoff = (unsigned int)lane * 8;
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned.
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW];
unsigned int wref[NW];
#pragma unroll
for (int it = 0; it < NW; ++it) {
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % NS, ntl = rest / NS;
wrow[it] = ntl * 16 + (lane_ & 15);
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
const int gn = n0 + wrow[it];
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
wkst[it] = kst;
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
: Wref[wrc[it]];
}
v8f acc[TM][TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
// ABLK, once a row: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two
// scales -- the block that starts there and the one before it -- a boundary early.
const int trow = m0 + tid < M ? m0 + tid : M - 1;
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
float ns = 0.f, np = 0.f;
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
mxt_lds_barrier(); // sMag
for (int k0 = 0; k0 < K; k0 += LBK) {
// ABLK: a new 128-wide activation block starts with this slab; each row's ratio goes to LDS,
// published by the staging barrier below (sR's previous readers were behind the last slab's
// closing barrier). A zero block keeps the carried scale; a zero block before this one sends
// the carried scale back to the grid, which only an all-zero activation block ever does.
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd)
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
}
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
mxt_v2i af[TM][NS];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int st = 0; st < NS; ++st)
af[i][st] = *(const mxt_v2i*)(abase[i] +
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
// W slab -> LDS, folded to e4m3.
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
unsigned int wq[WSLOTS], wsw;
if constexpr (WSLOTS == 4) {
const mxt_u4 v = *(const mxt_u4*)src;
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
wsw = *(const unsigned int*)(Ws + (size_t)blk * N + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const mxt_u2 v = *(const mxt_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * N + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
(int)((wsw >> (8 * q)) & 0xFF));
unsigned int lo, hi;
r4d_mxfp4_unpack8_t(wq[q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
}
}
mxt_lds_barrier();
if constexpr (ABLK) {
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
if (bnd) {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const float r = sR[wm * TM * 16 + i * 16 + col];
#pragma unroll
for (int j = 0; j < TN; ++j)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
}
}
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
if ((k0 & 127) == 0 && k0 + 128 < K) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < NS; ++step) {
const int kk = step * 16 + kb8;
mxt_v2i wf[TN];
#pragma unroll
for (int j = 0; j < TN; ++j) {
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
}
// One step's W fragments live at a time: without the fence the compiler hoists every
// step's loads above the first WMMA and holds them all.
__builtin_amdgcn_sched_barrier(0);
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j)
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
acc[i][j]);
}
mxt_lds_barrier();
}
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns of N fragment
// j, so each (i, j) is one 16-byte store. 2^(Wref[n]-127) is exactly the float whose exponent
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside N or all outside it.
float sc[TM];
if constexpr (ABLK) {
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
mxt_lds_barrier();
#pragma unroll
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
} else {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
}
}
#pragma unroll
for (int j = 0; j < TN; ++j) {
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
if (nb >= N) continue;
const mxt_u2 rb = *(const mxt_u2*)(Wref + nb);
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
if (m >= M) continue;
union { __hip_bfloat16 h[8]; mxt_u4 v; } o;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]);
}
*(mxt_u4*)(C + (size_t)m * N + nb) = o.v;
}
}
}
extern "C" int r4d_gemm_mxfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
}
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) {
if (M < 1) throw std::runtime_error("r4d mxfp4a8_tile_a: M must be >= 1");
if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16");
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0,
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots);
}
extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs,
long stream) {
if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: K must be a multiple of 64");
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves the grid short of 128
// blocks (a narrow N): there the TN=2 grid's extra blocks win.
if (TN == 0)
TN = M >= R4D_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_MXT_BMF - 1) / R4D_MXT_BMF) >= 128
? 4 : 2;
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: TN must be 2 or 4");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
if (ablk && as_rs < (K + 127) / 128)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
const bool wide_slab = TN == 2 && K % 128 == 0;
const int bnf = R4D_MXT_WN * TN * 16;
dim3 grid((N + bnf - 1) / bnf, (M + R4D_MXT_BMF - 1) / R4D_MXT_BMF), block(R4D_MXT_NTHR);
auto Ap = (const unsigned char*)at;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define MXT_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Rp, Cp, M, K, N, as_rs)
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
#undef MXT_LAUNCH
}
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K))
return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long at = (long)(uintptr_t)a->scratch;
R4D_TRY("gemm_mxfp4a8_tiled",
r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s);
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
t.tn, as_group, as_rs, (long)(uintptr_t)s));
return RAD_OK;
}
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
* the activation, whole 16-row fragments. */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K);
}
+74
View File
@@ -0,0 +1,74 @@
// Shared device-side machinery for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode):
// the folded-magnitude table and the eight-element unpack that reads it. One definition, because
// the three kernels must fold every weight element to the same e4m3 byte -- a model whose step
// crosses from one row's band into another's must not change what the weight is.
//
// r4d_gemm_mxfp4a8_nt_m64.hip explains the fold: d = Wref[n] - E8M0[n][blk] is pushed into the
// e4m3 value through this table, and 2^(Wref[n]-127) is applied once in the epilogue.
#pragma once
#include <hip/hip_runtime.h>
#define R4D_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
// kMxfp4Mag[d] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d, as packed
// e4m3 bytes, low word then high word, indexed by the 3-bit magnitude through v_perm_b32.
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and a
// rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the same
// exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter little
// (such an element is 2.9e-3 of its row's reference), but the table is generated, not hand-rounded,
// so it agrees with the hardware's own conversion. d >= 13 is zero: below the row's range.
//
// Static: each kernel's code object carries its own copy, and no two define the same symbol.
static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
};
// The exponent difference a block is folded at, clamped to the table: a block above its row's
// reference cannot occur (the reference is the row's maximum), and one 15 or more below is zero.
static __device__ __forceinline__ int r4d_mxfp4_fold_d(int ref, int e8) {
const int d = ref - e8;
return d < 0 ? 0 : (d > 15 ? 15 : d);
}
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
// in k order, word 0 holding elements 0..3 and word 1 elements 4..7, with the block's exponent
// difference `d` already folded in. Splitting the nibbles gives the even and odd elements; each is
// mapped through the table by a v_perm_b32 indexed with the 3-bit magnitude, the sign rides along
// as bit 3 shifted into the e4m3 sign position, and two more v_perm_b32 interleave the halves.
//
// `_t` takes the table row (t0, t1) the caller already holds -- a kernel that copies the table to
// LDS reads it there, off the global load counter its weight and activation loads wait on.
static __device__ __forceinline__ void r4d_mxfp4_unpack8_t(unsigned int wv, unsigned int t0,
unsigned int t1, unsigned int* lo,
unsigned int* hi) {
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
}
static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
}
// THE ACTIVATION SCALE A ROW'S ACCUMULATOR IS CARRIED IN, for the per-(row, 128 of K) grid: the
// last non-zero entry of row `row` at or before block `kb`, or 1 when there is none. A block whose
// scale is zero has zero codes and adds nothing whichever scale the sum is carried in, so it keeps
// the previous one rather than dividing by zero.
static __device__ __forceinline__ float r4d_mxfp4_carried(const float* __restrict__ row, int kb) {
for (int j = kb; j >= 0; --j) {
const float s = row[j];
if (s > 0.f) return s;
}
return 1.f;
}
+11
View File
@@ -42,6 +42,8 @@ enum {
* asks with M=64 to exclude m16. */
R4D_PRIO_GEMM_M16 = 60,
R4D_PRIO_GEMM_SKINNY = 50,
/* The MXFP4 decode row outranks the MXFP4 skinny row, whose band it shares up to N = 36864. */
R4D_PRIO_GEMM_MXDEC = 55,
/* The skinny m64 row has no upper bound on M, so the tiled bf16 row -- M > 64 only -- has to
* outrank it to be reached, and stays below m16 whose band it never enters. */
R4D_PRIO_GEMM_BF16_TILED = 55,
@@ -167,6 +169,11 @@ int r4d_rad_hc_write_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, in
/* -- all-reduce (r4d_ar_entry.hip) -- */
int r4d_rad_ar_init(const RadParam*, int, int rank, int world, void** out);
void r4d_rad_ar_fini(void*);
/* The same three inits with every rank's exchange buffers in pinned host memory: the host twins
* of the collective rows (r4d_rows.cpp) take them, and every launch and the fini are shared. */
int r4d_rad_ar_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_ln_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_hc_wide_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_oneshot_2rank_exact(const RadArgs*, RadStream);
int r4d_rad_ar_gather_2rank (const RadArgs*, RadStream);
/* The gather at a wide group's handshake (r4d_ar_gather_Nrank.hip launches it). */
@@ -207,6 +214,10 @@ int r4d_rad_gemm_w8a8_m64 (const RadArgs*, RadStream);
int r4d_rad_gemm_w8a8_tiled (const RadArgs*, RadStream);
int r4d_rad_gemm_w2a8 (const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_m64(const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
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_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int r4d_rad_rowtopk_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
+157 -8
View File
@@ -34,6 +34,8 @@
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0])))
@@ -2923,6 +2925,18 @@ static const RadConstraint cGemmNtW8A8[] = {
static const RadConstraint cGemmW4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8 w4a8_asym"),
};
/* r4d_gemm_mxfp4a8_decode. Entry point: M <= 128, N % 16, K % 64, and N up to its counter block's
* 36864. Above the skinny row by priority, so it takes the decode band; the skinny row keeps the
* wider N up to M = 64, the tiled row everything else. */
static const RadConstraint cGemmMxfp4A8Decode[] = {
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_mxfp4a8_tiled. Entry point: N % 16 (the fragment-order weight), K % 64 (its narrowest
* K slab), M >= 1. The decode and skinny rows outrank it in their bands by priority, so the band
* starts at 1 rather than at a hand-picked crossover. */
static const RadConstraint cGemmMxfp4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_w8a8_tiled. The same kernel at radix 8; the asym arm exists in the .hip but is NOT
* declared in r4d.h, so this plugin cannot reach it and `w8a8_asym` is deliberately absent from
* the dtype set. */
@@ -3042,6 +3056,25 @@ static const RadTunable tGemmPrefill[] = {
"compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" },
};
/* The MXFP4 tiled GEMM's one axis. Both values are compiled arms of one template; 0 is the M
* crossover (TN=4 from M >= 2048), which needs M and so cannot be a constant. */
static const int64_t kMxTn[] = { 0, 2, 4 };
static const RadTunable tGemmMxfp4Tiled[] = {
{ "tn", kMxTn, NELEM(kMxTn), 0,
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
};
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
* `nt` 1 streams the weight past the caches, 2 loads it plainly. */
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
static const int64_t kMxDecBk[] = { 0, 64, 128 };
static const int64_t kMxDecNt[] = { 0, 1, 2 };
static const RadTunable tGemmMxfp4Decode[] = {
{ "ks", kMxDecKs, NELEM(kMxDecKs), 0, "split-K workgroups a column block. 0 = the fill rule" },
{ "bk", kMxDecBk, NELEM(kMxDecBk), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
{ "nt", kMxDecNt, NELEM(kMxDecNt), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
};
/* ------------------------------------------------------------------------ split-KV attention
* 0 is libr4d's measured split law (r4d_attn_paged_h256_gqa6.hip carries the table), which reads
* num_seqs and max_ctx -- values that exist only at issue -- so it cannot be a constant and stays
@@ -4319,6 +4352,32 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_m64, nullptr, r4d_rad_layout_mxfp4,
r4d_rad_relayout_mxfp4 },
{ "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",
"M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent; the split partial in the op's scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC,
ROW(cGemmMxfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_decode, r4d_rad_gemm_mxfp4a8_decode_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_tiled", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM tiled for PREFILL row counts: the activation re-tiled into fragment order in "
"the op's scratch, its fragments read straight into registers, the weight unpacked once per K "
"slab into LDS for a 256-row block",
"any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent; the re-tiled activation in the op's "
"scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED,
ROW(cGemmMxfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */
{ "gemm_w4a8_prefill", "gemm_nt_q", "gemm",
"the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is "
@@ -5067,8 +5126,9 @@ static const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL,
"libr4d",
"0.5.0",
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, P2P "
"all-reduce, skinny and tiled quantised GEMM, and the rotate-and-quantise fusions",
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, "
"all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, and the "
"rotate-and-quantise fusions",
"gfx1201",
};
@@ -5082,12 +5142,91 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) {
if (i < 0 || i >= rad_kernel_schema_count()) return nullptr;
return &kSchemas[i];
}
/* ================================================================================ the host twins
*
* A MACHINE WITHOUT PEER ACCESS RUNS THE SAME COLLECTIVES WITH THEIR MAILBOX IN HOST MEMORY. Every
* row that takes one of the three all-reduce inits has a twin: the same op, kernel, launch, fini,
* priority and tuning axes, `_host` appended to its name, its device.p2p == 1 turned into
* device.p2p == 0, and the init that puts every rank's exchange buffers in pinned host memory
* (r4d_ar_entry.hip, build). Exactly one of a pair matches any machine, so neither outranks the
* other, and a band report names which transport the step runs.
*
* DERIVED, NOT WRITTEN OUT, so a collective row added to the table above has its twin by being
* added and the two cannot drift: the transport is the only thing they differ in. A collective row
* that does not require device.p2p == 1 gets no twin, and r4d_selftest fails it for the missing
* constraint. */
namespace {
struct HostTwin {
RadKernelInfo info;
std::string name, computes, shape;
std::vector<RadConstraint> c;
};
RadInitFn host_init_for(RadInitFn f) {
if (f == r4d_rad_ar_init) return r4d_rad_ar_host_init;
if (f == r4d_rad_ar_ln_init) return r4d_rad_ar_ln_host_init;
if (f == r4d_rad_ar_hc_wide_init) return r4d_rad_ar_hc_wide_host_init;
return nullptr;
}
std::string replaced(std::string s, const char* from, const char* to) {
const size_t at = s.find(from);
if (at != std::string::npos) s.replace(at, std::strlen(from), to);
return s;
}
const std::vector<HostTwin>& host_twins() {
static const std::vector<HostTwin> v = [] {
std::vector<HostTwin> t;
for (const RadKernelInfo& k : kKernels) {
const RadInitFn init = host_init_for(k.init);
if (!init) continue;
HostTwin h;
h.c.assign(k.constraints, k.constraints + k.n_constraints);
int p2p = 0;
for (RadConstraint& c : h.c)
if (!std::strcmp(c.key, RAD_FACT_P2P) && c.op == RAD_C_EQ && c.ival == 1) {
c.ival = 0;
++p2p;
}
if (p2p != 1) continue;
h.info = k;
h.info.init = init;
h.name = std::string(k.name) + "_host";
h.computes = k.computes;
if (h.computes.find("over P2P IPC scratch") != std::string::npos)
h.computes = replaced(h.computes, "over P2P IPC scratch",
"through a pinned host-memory mailbox");
else
h.computes += ", exchanged through a pinned host-memory mailbox";
h.shape = replaced(replaced(k.shape, "all peer-accessible", "no peer access needed"),
"peer-accessible", "no peer access needed");
t.push_back(std::move(h));
}
/* The strings are pointed into only once the vector has stopped growing. */
for (HostTwin& h : t) {
h.info.name = h.name.c_str();
h.info.computes = h.computes.c_str();
h.info.shape = h.shape.c_str();
h.info.constraints = h.c.data();
h.info.n_constraints = (int)h.c.size();
}
return t;
}();
return v;
}
} /* namespace */
extern "C" int rad_kernel_count(void) {
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
return (int)(sizeof(kKernels) / sizeof(kKernels[0])) + (int)host_twins().size();
}
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
const int base = (int)(sizeof(kKernels) / sizeof(kKernels[0]));
if (i < 0 || i >= rad_kernel_count()) return nullptr;
return &kKernels[i];
if (i < base) return &kKernels[i];
return &host_twins()[(size_t)(i - base)].info;
}
/* WHICH ROWS TOUCH NOTHING BUT THEIR OPERANDS AND SCRATCH (rad_abi.h). Nothing on an R4D launch
@@ -5100,11 +5239,13 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
* gemm_w8a8_tiled
* 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, and
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output;
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
* output alone, so no argument depends on the stream a pass is recorded or replayed on; and
* router_gemm_topk_scatter_bf16's arrival counter is its op instance's (taken at init, one a
* declared op and band), so two launches that could run at once never share them, and both rows
* are concurrent. A row added with state of its own that the stream's order protects belongs in
* this list. */
* declared op and band). Two launches that could run at once never share any of them, so all three
* rows are concurrent. A row added with state of its own that the stream's order protects belongs
* in this list. */
extern "C" int rad_kernel_concurrent(int i) {
const RadKernelInfo* k = rad_kernel_at(i);
if (!k) return 0;
@@ -5179,6 +5320,14 @@ extern "C" void r4d_cfg_tiled(const RadArgs* a, R4dTileCfg* out) {
extern "C" void r4d_cfg_prefill(const RadArgs* a, R4dTileCfg* out) {
tile_bmbn(TUNE(a, tGemmPrefill, "tile"), 1, out);
}
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
out->ks = TUNE(a, tGemmMxfp4Decode, "ks");
out->bk = TUNE(a, tGemmMxfp4Decode, "bk");
out->nt = TUNE(a, tGemmMxfp4Decode, "nt");
}
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
out->tn = TUNE(a, tGemmMxfp4Tiled, "tn");
}
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
out->splits = TUNE(a, tAttnSplit, "splits");
}
+497 -78
View File
@@ -353,17 +353,20 @@ static void cross_check(const Plugin& pl) {
"' which op '" + r->op + "' does not declare; ";
}
}
/* EVERY MULTI-CARD ROW NEEDS PEER ACCESS. Each kernel in this library that runs only at
* two or more ranks reads or writes the other cards' memory directly, so without
* device.p2p a machine whose cards cannot reach each other resolves it and the launch
* faults or hangs instead of being refused by name at selection. */
/* EVERY MULTI-CARD ROW STATES THE TRANSPORT IT NEEDS. A kernel in this library that runs
* only at two or more ranks either reads and writes the other cards' memory directly and
* requires device.p2p == 1, or is a host twin whose mailbox is pinned host memory and
* requires device.p2p == 0. Without the key, a machine whose cards cannot reach each other
* resolves a P2P kernel and the launch faults or hangs instead of being refused by name at
* selection; and a host twin without it would compete with its original where P2P works. */
bool multi = false, p2p = false;
for (int c = 0; c < r->n_constraints; ++c) {
const RadConstraint& rc = r->constraints[c];
if (!std::strcmp(rc.key, "world_size") &&
(rc.op == RAD_C_EQ || rc.op == RAD_C_GE) && rc.ival >= 2)
multi = true;
if (!std::strcmp(rc.key, RAD_FACT_P2P) && rc.op == RAD_C_EQ && rc.ival == 1)
if (!std::strcmp(rc.key, RAD_FACT_P2P) && rc.op == RAD_C_EQ &&
(rc.ival == 1 || rc.ival == 0))
p2p = true;
}
if (multi && !p2p) {
@@ -379,7 +382,8 @@ static void cross_check(const Plugin& pl) {
ok("no row declares the same axis key twice", dup_axis == 0, axisdetail);
ok("every row's op has a schema", no_schema == 0, keydetail);
ok("every constraint key is a declared parameter of its op", bad_key == 0, keydetail);
ok("every row that needs two or more ranks requires device.p2p", no_p2p == 0, p2pdetail);
ok("every row that needs two or more ranks requires device.p2p 1 or 0", no_p2p == 0,
p2pdetail);
/* The libr4d orderings the integer priority has to preserve. */
int p_ts = -1, p_os = -1, p_dec = -1, p_pre = -1, p_m16 = -1, p_m64 = -1, p_bt = -1;
@@ -3308,6 +3312,351 @@ static void w8a16_numeric(const Plugin& pl, const char* row, int64_t M, int64_t
}
/* An OCP-MXFP4 weight's planes, drawn through st_mix32 of each coordinate and `seed`: codes over
* all sixteen e2m1 values, and an exponent per (row, 32 of K) within three binades of 127. With
* `deep`, about one block in eleven sits 6..12 binades lower still -- the folded table's subnormal
* tail. */
static void mxfp4_fill(Planes& p, int ic, int is, int64_t N, int64_t K, uint32_t seed, bool deep) {
const int64_t nblk = K / 32;
for (int64_t n = 0; n < N; ++n)
for (int64_t k = 0; k < K; k += 2) {
const uint32_t h = st_mix32((uint32_t)(n * K + k) ^ (seed * 0x9e3779b9u));
p.data[(size_t)ic][(size_t)((n * K + k) / 2)] =
(uint8_t)((h & 15) | (((h >> 8) & 15) << 4));
}
for (int64_t n = 0; n < N; ++n)
for (int64_t b = 0; b < nblk; ++b) {
const uint32_t h = st_mix32((uint32_t)(n * nblk + b) ^ (seed * 0x85ebca6bu) ^ 0x2545u);
int e = 127 + (int)(h % 7) - 3;
if (deep && (h >> 8) % 11 == 0) e -= 6 + (int)((h >> 16) % 7);
p.data[(size_t)is][(size_t)(n * nblk + b)] = (uint8_t)e;
}
}
/* An E4M3-representable activation value in [-4, 4], drawn the same way. */
static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) {
const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ (seed * 0xc2b2ae35u));
return (float)((int)(h % 401) - 200) * 0.02f;
}
/* THE MXFP4 GEMMS AGAINST WHAT THE PLANES MEAN. The weight is an OCP-MXFP4 plane pair -- e2m1
* codes and an E8M0 exponent per 32 K -- stored through the row's own hooks, so the fragment
* order, the [K/32][N] exponents and the per-row reference all come from r4d_layout.cpp and the
* kernel is checked on what the loader would hand it. The reference decodes the planes on the host
* with no fold at all, so a misread arrangement shows as a column that disagrees.
*
* Codes, exponents and activations are drawn through st_mix32 of their coordinates, so a misread
* pitch or lane map reads unrelated numbers rather than a shifted copy of the right ones. The
* exponents are spread so a row's blocks sit up to 12 binades under its reference: d <= 8 is exact
* in the folded e4m3 table and d = 9..12 rounds, which is the subnormal tail every MXFP4 row
* shares. M and N are chosen ragged against the tiled row's 256-row block and 64/128-column tile,
* so the clamped staging and the guarded epilogue both run. `tn` pins the tiled row's column
* width; 0 leaves it to the row's own M rule (and is ignored by the skinny row).
*
* `ablk` hands the activation scale as the block-scaled fp8 family's grid, one f32 per (row, 128
* of K), instead of one per row -- what an architecture's fused quantisers write. The scales are
* spread over two decades and every eleventh block's is ZERO with zero codes behind it (an
* all-zero activation block), which is the case the kernels carry their previous scale through. */
static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int tn, bool ablk = false, std::vector<RadParam> extra = {}) {
if (!sel(row)) return;
char nm[160];
std::string ex;
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
const RadKernelInfo* r = find(pl, row);
if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; }
const int64_t nblk = K / 32;
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;
const int rw = stored(r, lp, 2, p, { "codes" }, &wq);
const int rs = stored(r, lp, 3, p, { "scale" }, &ws);
const int rr = stored(r, lp, 6, p, { "scale" }, &wr);
if (rw != RAD_OK || rs != RAD_OK || rr != RAD_OK) {
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs) + "/" +
std::to_string(rr));
return;
}
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> av((size_t)(M * K)), as((size_t)(M * asc));
for (int64_t i = 0; i < M; ++i) {
for (int64_t c = 0; c < asc; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * asc + c) ^ 0xa5u);
as[(size_t)(i * asc + c)] =
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
: 0.0125f * (float)(1 + h % 5);
}
for (int64_t k = 0; k < K; ++k) {
const bool zero = ablk && as[(size_t)(i * asc + k / 128)] == 0.0f;
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, v);
av[(size_t)(i * K + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * K + k);
}
}
std::vector<uint16_t> hy((size_t)(M * N), 0);
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(hy.size() * 2);
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y) { 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);
std::vector<RadTensor> ts = {
T(d_a, RAD_F8E4M3, { M, K }),
ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }),
};
absent(ts[5]);
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8") };
if (tn) ps.push_back(PI("tn", tn));
for (const RadParam& p : extra) ps.push_back(p);
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
/* A row with a scratch hook (the decode row's split partial) gets what it asks for, as the
* core would hand it; the decode row refuses a split with too little. */
if (r->scratch) {
const int64_t sb = r->scratch(&a);
if (sb > 0) {
a.scratch = dalloc((size_t)sb);
a.scratch_bytes = sb;
if (!a.scratch) { ok(nm, false, "hipMalloc failed"); return; }
}
}
const int rc = r->launch(&a, (RadStream) nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
ok(nm, false, "rc=" + std::to_string(rc));
return;
}
st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost);
/* Every column for small N, a stride otherwise -- always including the last column, which is
* the clamped tail of the tiled row's weight staging. */
const int64_t nstep = N > 96 ? N / 96 : 1;
double num = 0, den = 0, worst = 0;
for (int64_t i = 0; i < M; ++i)
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
double acc = 0;
for (int64_t k = 0; k < K; ++k) {
const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
acc += (double)av[(size_t)(i * K + k)] * w *
(ablk ? (double)as[(size_t)(i * asc + k / 128)] : 1.0);
}
if (!ablk) acc *= (double)as[(size_t)i];
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
num += d * d;
den += acc * acc;
worst = std::max(worst, std::fabs(d) / (std::fabs(acc) + 1e-3));
}
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
char d[96];
std::snprintf(d, sizeof d, "rel_l2 %.3e, worst %.3e", rel, worst);
ok(nm, rel < 1e-2, d);
}
/* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial
* is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own
* weights, activations and output and a DISJOINT slice of one scratch allocation, with a split
* (ks > 1) so the partial and the counters are live. The reference is each launched alone, then the
* pair is launched on two non-blocking streams with nothing ordering them -- repeated, so the
* launches overlap in different phases -- and every output must be BYTE-identical to the serial one
* (the reducer sums the splits in a fixed order, so a lost or shared counter / partial shows as a
* different byte or a hang). A last serial launch after the loop checks that the counters were
* left at zero. */
struct MxdOverlapGemm {
int64_t M, N, K;
int ks;
std::vector<RadTensor> ts;
std::vector<RadParam> ps;
void* y = nullptr;
int64_t scratch = 0;
bool ready = false;
};
static bool mxd_overlap_build(const RadKernelInfo* r, MxdOverlapGemm& g, int seed) {
const int64_t M = g.M, N = g.N, K = g.K, nkb = K / 128;
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) return false;
mxfp4_fill(p, ic, is, N, K, (uint32_t)seed, false);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
if (stored(r, lp, 2, p, { "codes" }, &wq) != RAD_OK ||
stored(r, lp, 3, p, { "scale" }, &ws) != RAD_OK ||
stored(r, lp, 6, p, { "scale" }, &wr) != RAD_OK)
return false;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> as((size_t)(M * nkb));
for (int64_t i = 0; i < M; ++i) {
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) ^ (uint32_t)seed) % 97);
for (int64_t k = 0; k < K; ++k)
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, (uint32_t)seed));
}
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());
g.y = dalloc((size_t)(M * N) * 2);
if (!d_a || !d_s || !d_w || !d_e || !d_r || !g.y) return false;
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);
g.ts = { 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(g.y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }),
T(d_r, RAD_U8, { (int64_t)wr.size() }) };
absent(g.ts[5]);
g.ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"),
PI("ks", g.ks), PI("bk", 128), PI("nt", 1) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = g.ts.data(); a.n_t = (int)g.ts.size();
a.p = g.ps.data(); a.n_p = (int)g.ps.size();
a.world_size = 1;
g.scratch = r->scratch ? r->scratch(&a) : 0;
g.ready = g.scratch >= (int64_t)g.ks * M * N * 4;
return g.ready;
}
static int mxd_overlap_launch(const RadKernelInfo* r, MxdOverlapGemm& g, void* scratch,
hipStream_t st, int64_t scratch_bytes = -1) {
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = g.ts.data(); a.n_t = (int)g.ts.size();
a.p = g.ps.data(); a.n_p = (int)g.ps.size();
a.world_size = 1;
a.scratch = scratch;
a.scratch_bytes = scratch_bytes < 0 ? g.scratch : scratch_bytes;
return r->launch(&a, (RadStream)st);
}
static void mxd_overlap_case(const Plugin& pl) {
if (!sel("gemm_mxfp4a8_decode_overlap") && !sel("gemm_mxfp4a8_decode")) return;
const char* nm = "gemm_mxfp4a8_decode: two split GEMMs on two streams, disjoint scratch, "
"byte-identical to serial";
const RadKernelInfo* r = find(pl, "gemm_mxfp4a8_decode");
if (!r || !r->layout || !r->relayout || !r->scratch) { ok(nm, false, "row or hooks absent"); return; }
MxdOverlapGemm g[3];
g[0] = MxdOverlapGemm{}; g[0].M = 8; g[0].N = 400; g[0].K = 2560; g[0].ks = 4;
g[1] = MxdOverlapGemm{}; g[1].M = 8; g[1].N = 272; g[1].K = 2560; g[1].ks = 2;
g[2] = MxdOverlapGemm{}; g[2].M = 24; g[2].N = 1040; g[2].K = 1152; g[2].ks = 4;
for (int i = 0; i < 3; ++i)
if (!mxd_overlap_build(r, g[i], 1 + 2 * i)) {
ok(nm, false, "operands or scratch hook (ks > 1 needs a split partial)");
return;
}
/* One allocation, a slice each, 256-byte aligned: the core's disjoint scratch slices. */
int64_t off[3], tot = 0;
for (int i = 0; i < 3; ++i) { off[i] = tot; tot += (g[i].scratch + 255) & ~int64_t(255); }
char* base = (char*)dalloc((size_t)tot);
if (!base) { ok(nm, false, "hipMalloc failed"); return; }
/* The serial reference gets its own scratch, so the two runs share nothing but the kernel. */
std::vector<std::vector<uint16_t>> want(3);
for (int i = 0; i < 3; ++i) {
void* sc = dalloc((size_t)g[i].scratch);
if (!sc) { ok(nm, false, "hipMalloc failed"); return; }
const int rc = mxd_overlap_launch(r, g[i], sc, nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
ok(nm, false, "serial rc=" + std::to_string(rc));
return;
}
want[(size_t)i].assign((size_t)(g[i].M * g[i].N), 0);
st_memcpy(want[(size_t)i].data(), g[i].y, want[(size_t)i].size() * 2, hipMemcpyDeviceToHost);
}
hipStream_t s1 = nullptr, s2 = nullptr;
if (hipStreamCreateWithFlags(&s1, hipStreamNonBlocking) != hipSuccess ||
hipStreamCreateWithFlags(&s2, hipStreamNonBlocking) != hipSuccess) {
ok(nm, false, "hipStreamCreate failed");
return;
}
int bad = 0, iters = 0;
std::string why;
for (int it = 0; it < 200 && !bad; ++it) {
const int a = it % 3, b = (it + 1 + (it / 3) % 2) % 3; /* every ordered pair of distinct GEMMs */
for (int i : { a, b }) st_memset(g[i].y, 0, (size_t)(g[i].M * g[i].N) * 2);
/* The streams are non-blocking, so nothing orders them after the legacy-stream memset. */
(void)hipDeviceSynchronize();
const int ra = mxd_overlap_launch(r, g[a], base + off[a], s1);
const int rb = mxd_overlap_launch(r, g[b], base + off[b], s2);
const bool sa = st_stream_sync(s1) == hipSuccess, sb = st_stream_sync(s2) == hipSuccess;
if (ra != RAD_OK || rb != RAD_OK || !sa || !sb) {
bad = 1;
why = "launch rc " + std::to_string(ra) + "/" + std::to_string(rb);
break;
}
for (int i : { a, b }) {
std::vector<uint16_t> got((size_t)(g[i].M * g[i].N));
st_memcpy(got.data(), g[i].y, got.size() * 2, hipMemcpyDeviceToHost);
if (std::memcmp(got.data(), want[(size_t)i].data(), got.size() * 2) != 0) {
bad = 1;
size_t nd = 0, first = got.size(), nz = 0;
for (size_t j = 0; j < got.size(); ++j) {
if (got[j] != want[(size_t)i][j]) { ++nd; if (first == got.size()) first = j; }
if (got[j] == 0) ++nz;
}
why = "iter " + std::to_string(it) + ": GEMM " + std::to_string(i) + " (ks=" +
std::to_string(g[i].ks) + ") differs from serial: " + std::to_string(nd) +
"/" + std::to_string(got.size()) + " elements, first at " +
std::to_string(first) + " (m=" + std::to_string(first / (size_t)g[i].N) +
" n=" + std::to_string(first % (size_t)g[i].N) + "), " +
std::to_string(nz) + " zero, partner GEMM " + std::to_string(i == a ? b : a);
}
}
++iters;
}
(void)hipStreamDestroy(s1);
(void)hipStreamDestroy(s2);
ok(nm, !bad, bad ? why : std::to_string(iters) + " overlapped pairs identical");
/* The counters must be zero again: a serial launch after the storm is still byte-identical. */
bool again = true;
for (int i = 0; i < 3 && again; ++i) {
st_memset(g[i].y, 0, (size_t)(g[i].M * g[i].N) * 2);
const int rc = mxd_overlap_launch(r, g[i], base + off[i], nullptr);
std::vector<uint16_t> got((size_t)(g[i].M * g[i].N));
again = rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess;
if (again) {
st_memcpy(got.data(), g[i].y, got.size() * 2, hipMemcpyDeviceToHost);
again = std::memcmp(got.data(), want[(size_t)i].data(), got.size() * 2) == 0;
}
}
ok("gemm_mxfp4a8_decode: serial after the overlap storm is still identical (counters left at "
"zero)", again);
/* A split given less scratch than its partial is refused, not run unsplit: the hook sized it
* for the whole band, so a short one is a caller's error and must surface as one. */
const int rc = mxd_overlap_launch(r, g[0], base + off[0], nullptr, g[0].scratch / 2);
(void)st_stream_sync(nullptr);
ok("gemm_mxfp4a8_decode: a split with half its scratch is refused", rc != RAD_OK,
"rc=" + std::to_string(rc));
}
/* THE INT8 TRUNK CHAIN: quant_act_i8g on a bf16 activation, then one of the i8a8 GEMMs on what it
* wrote, against the planes' meaning. The weight is i8 with a bf16 scale per row per 128 K (what
* libquant writes for `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's own
@@ -9200,10 +9549,10 @@ static void ar_worker(ArThread* t) {
st_free(out);
}
static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_2rank_exact");
if (!row) { ok("ar_oneshot_2rank_exact", false, "row absent"); return; }
if (devs.size() < 2) { skip("ar_oneshot_2rank_exact (2 ranks)", "fewer than two gfx1201 cards"); return; }
static void ar_two_rank(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; }
/* 8192 fp32 elements: a whole number of 16-byte pushes and small enough that the handshake,
* not the link, is what is being exercised. */
@@ -9243,6 +9592,11 @@ static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs) {
* a hang. The sizes give 11, 4 and 7 blocks under the default block rule. */
static const int64_t kArSweepNumel[] = { 65536, 8192, 40000, 65536, 12000, 24576, 65536, 8192 };
constexpr int kArSweepN = (int)(sizeof(kArSweepNumel) / sizeof(kArSweepNumel[0]));
/* The sweep again and again with new values each round, so every slot is reused many times over.
* A reader that is served a slot's previous contents -- a cached line of host memory or of a
* peer's, a flag seen before the bytes behind it -- folds the value of an earlier launch, and every
* launch's value is distinct, so that is a wrong sum and not a lucky one. */
constexpr int kArSweepRounds = 32;
struct ArSweep {
const RadKernelInfo* row;
@@ -9262,7 +9616,7 @@ static void ar_sweep_worker(ArSweep* t) {
};
t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst);
if (t->rc_init != RAD_OK) return;
/* Rank r contributes (r + 1) * (j + 1), so launch j sums to (1 + 2 + .. + world) * (j + 1). */
/* Rank r contributes (r + 1) * v, so a launch with value v sums to (1 + 2 + .. + world) * v. */
const float tri = (float)(t->world * (t->world + 1) / 2);
void* in[kArSweepN] = {};
@@ -9273,40 +9627,45 @@ static void ar_sweep_worker(ArSweep* t) {
t->rc_launch = RAD_E_NOMEM;
return;
}
/* Rank r contributes (r + 1) * (j + 1), so launch j sums to 3 * (j + 1) exactly. */
std::vector<float> h((size_t)kArSweepNumel[j], (float)((t->rank + 1) * (j + 1)));
st_memcpy(in[j], h.data(), bytes, hipMemcpyHostToDevice);
st_memset(out[j], 0, bytes);
}
for (int j = 0; j < kArSweepN && t->rc_launch == RAD_OK; ++j) {
RadTensor ts[2] = { T(in[j], RAD_F32, { kArSweepNumel[j] }),
T(out[j], RAD_F32, { kArSweepNumel[j] }) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts; a.n_t = 2;
a.p = ps.data(); a.n_p = (int)ps.size();
a.instance = t->inst;
a.rank = t->rank;
a.world_size = t->world;
t->rc_launch = t->row->launch(&a, nullptr);
for (int round = 0; round < kArSweepRounds && t->rc_launch == RAD_OK; ++round) {
for (int j = 0; j < kArSweepN; ++j) {
const size_t bytes = (size_t)kArSweepNumel[j] * 4;
const float v = (float)(round * kArSweepN + j + 1);
std::vector<float> h((size_t)kArSweepNumel[j], (float)(t->rank + 1) * v);
st_memcpy(in[j], h.data(), bytes, hipMemcpyHostToDevice);
st_memset(out[j], 0, bytes);
}
for (int j = 0; j < kArSweepN && t->rc_launch == RAD_OK; ++j) {
RadTensor ts[2] = { T(in[j], RAD_F32, { kArSweepNumel[j] }),
T(out[j], RAD_F32, { kArSweepNumel[j] }) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts; a.n_t = 2;
a.p = ps.data(); a.n_p = (int)ps.size();
a.instance = t->inst;
a.rank = t->rank;
a.world_size = t->world;
t->rc_launch = t->row->launch(&a, nullptr);
}
st_stream_sync(nullptr);
for (int j = 0; j < kArSweepN; ++j) {
const float v = (float)(round * kArSweepN + j + 1);
std::vector<float> h((size_t)kArSweepNumel[j]);
st_memcpy(h.data(), out[j], h.size() * 4, hipMemcpyDeviceToHost);
for (float x : h) if (x != tri * v) ++t->bad;
}
}
st_stream_sync(nullptr);
for (int j = 0; j < kArSweepN; ++j) {
std::vector<float> h((size_t)kArSweepNumel[j]);
st_memcpy(h.data(), out[j], h.size() * 4, hipMemcpyDeviceToHost);
for (float v : h) if (v != tri * (float)(j + 1)) ++t->bad;
st_free(in[j]);
st_free(out[j]);
}
}
static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_2rank_exact");
if (!row) { ok("ar_oneshot_2rank_exact", false, "row absent"); return; }
if (devs.size() < 2) {
skip("ar_oneshot_2rank_exact (block counts)", "fewer than two gfx1201 cards");
return;
}
static void ar_two_rank_sweep(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; }
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();
@@ -9315,8 +9674,8 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs) {
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, launches back to back at changing block counts, every sum exact on "
"both ranks",
ok("2-rank all-reduce, 32 rounds of launches back to back at changing block counts, 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");
@@ -9369,10 +9728,10 @@ static void gather_worker(ArThread* t) {
st_free(out);
}
static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_gather_2rank");
if (!row) { ok("ar_gather_2rank", false, "row absent"); return; }
if (devs.size() < 2) { skip("ar_gather_2rank (2 ranks)", "fewer than two gfx1201 cards"); return; }
static void gather_two_rank(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; }
const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */
ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel };
@@ -9459,10 +9818,10 @@ static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs) {
* the instantiation, the dispatch rows and the entry points agree: a rendezvous of three, a sum of
* 1 + 2 + 3 on every rank bit for bit, the slot parity surviving a block-count sweep, and the
* gather placing three slices in both of its layouts. Skipped, not failed, on fewer cards. */
static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_3rank_exact");
if (!row) { ok("ar_oneshot_3rank_exact", false, "row absent"); return; }
if (devs.size() < 3) { skip("ar_oneshot_3rank_exact (3 ranks)", "fewer than three gfx1201 cards"); return; }
static void ar_three_rank(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() < 3) { skip(name, "fewer than three gfx1201 cards"); return; }
const int64_t numel = 8192;
ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel }, c{ row, 2, devs[2], numel };
a.world = b.world = c.world = 3;
@@ -9501,7 +9860,7 @@ static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
tz.join();
const bool up = x.rc_init == RAD_OK && y.rc_init == RAD_OK && z.rc_init == RAD_OK &&
x.rc_launch == RAD_OK && y.rc_launch == RAD_OK && z.rc_launch == RAD_OK;
ok("3-rank all-reduce, eight launches at changing block counts on one instance",
ok("3-rank all-reduce, 32 rounds of eight launches at changing block counts on one instance",
up && x.bad == 0 && y.bad == 0 && z.bad == 0,
up ? std::to_string(x.bad + y.bad + z.bad) + " elements wrong"
: "rc " + std::to_string(x.rc_init) + "/" + std::to_string(y.rc_init) + "/" +
@@ -9514,10 +9873,10 @@ static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
}
}
static void gather_three_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_gather_3rank");
if (!row) { ok("ar_gather_3rank", false, "row absent"); return; }
if (devs.size() < 3) { skip("ar_gather_3rank (3 ranks)", "fewer than three gfx1201 cards"); return; }
static void gather_three_rank(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() < 3) { skip(name, "fewer than three gfx1201 cards"); return; }
const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */
const int W = 3;
/* What each rank sent, rebuilt here rather than read back off the device (gather_two_rank). */
@@ -10347,6 +10706,61 @@ static void device_phase(const Plugin& pl) {
gemm_case(pl, "gemm_w8a8_nt_m64", "w8a8", M, N, K, RAD_I8, 1, 0, 0, N*K, N*(K/128)*2);
gemm_case(pl, "gemm_w2a8_nt", "w2a8", M, N, K, RAD_I8, 1, 1, 0, N*K/4, N*(K/128)*4);
gemm_case(pl, "gemm_mxfp4a8_nt_m64", "mxfp4a8", M, N, K, RAD_F8E4M3, 1, 0, 1, N*K/2, (K/32)*N);
gemm_case(pl, "gemm_mxfp4a8_tiled", "mxfp4a8", 256, 256, K, RAD_F8E4M3, 1, 0, 1, 256*K/2, (K/32)*256);
/* The skinny row is known-good, so it checks the check; the tiled row at both widths, ragged
* in M and N, then at the size where tn=0 crosses over to TN=4. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 40, 272, 640, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0);
/* ...and against the fp8 family's (row, 128) activation grid, which is what an architecture
* feeds them. K = 640 is five blocks and 2560 twenty, so every split-K segment of the
* skinny row and every slab pair of the tiled one crosses block boundaries. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 512, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true);
/* K not a multiple of 128: the TN=2 kernel takes the 64-wide slab. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2, true);
/* The decode row over its whole band: the split rule's own choice, then every split and
* slab forced, at both activation grids; N past a 128-column block, K a multiple of 64
* but not 128 (the slab falls back to 64), and DTM 1..4. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, false);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 400, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true);
mxd_overlap_case(pl);
/* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or
* fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K
* on both sides of M=80, and the plain case; then every split and slab forced. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 14336, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 128, 6144, 1152, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 100, 1024, 576, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 72, 5120, 6144, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 120, 5120, 6144, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 112, 5120, 2560, 0, false);
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", 1) });
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 24, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", ks == 2 ? 2 : 1) });
/* ...and the one-fragment form (DTM = 1: the register prefetch and 16 B loads) at every
* split, slab and load hint, on both activation grids, N past a column block. */
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
for (int nt : { 1, 2 }) {
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", nt) });
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 13, 272, 1152, 0, false,
{ PI("ks", ks), PI("bk", bk), PI("nt", nt) });
}
gemm_case(pl, "gemm_w4a8_tiled", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
gemm_case(pl, "gemm_w8a8_tiled", "w8a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K, 256*(K/128)*2);
gemm_case(pl, "gemm_w4a8_prefill", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
@@ -10842,44 +11256,49 @@ static void device_phase(const Plugin& pl) {
bf16_gemm_numeric(pl, "gemm_bf16_nt_tiled", 300, 1040, 2560);
}
if (sel("ar_oneshot_2rank_exact")) {
if (!g_case) std::printf("\ncross-rank\n");
ar_two_rank(pl, devs);
ar_two_rank_sweep(pl, devs);
}
if (sel("ar_gather_2rank")) {
if (!g_case) std::printf("\ncross-rank\n");
gather_two_rank(pl, devs);
}
/* The wide family at three. Its own rows, so the sweep names them (a row the sweep never
* mentions is reported as a coverage hole) and so `--case ar_oneshot_3rank_exact` reproduces
* one of them alone. */
if (sel("ar_oneshot_3rank_exact")) {
if (!g_case) std::printf("\ncross-rank, three\n");
ar_three_rank(pl, devs);
}
if (sel("ar_gather_3rank")) {
if (!g_case) std::printf("\ncross-rank, three\n");
gather_three_rank(pl, devs);
/* Every collective has a host twin (r4d_rows.cpp): the same kernel with its mailbox in pinned
* host memory. A case is the pair's, so the twin is held to exactly the original's checks. */
for (const char* base : { "ar_oneshot_2rank_exact", "ar_gather_2rank", "ar_oneshot_3rank_exact",
"ar_gather_3rank" }) {
for (const std::string& n : { std::string(base), std::string(base) + "_host" }) {
if (!sel(n.c_str())) continue;
const bool three = std::strstr(base, "3rank") != nullptr;
if (!g_case) std::printf(three ? "\ncross-rank, three\n" : "\ncross-rank\n");
std::printf(" %s\n", n.c_str());
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());
} else if (!std::strcmp(base, "ar_gather_2rank")) {
gather_two_rank(pl, devs, n.c_str());
/* The wide family at three. Its own rows, so the sweep names them (a row the sweep
* never mentions is reported as a coverage hole) and so `--case
* ar_oneshot_3rank_exact` reproduces one of them alone. */
} else if (three && std::strstr(base, "gather")) {
gather_three_rank(pl, devs, n.c_str());
} else {
ar_three_rank(pl, devs, n.c_str());
}
}
}
/* The 4- and 8-rank rows cannot be exercised on a two-card box. Reported as skipped rather
* than quietly passing: a row that has never been launched is not a row that works. */
auto skip_pair = [](const char* base, const char* why) {
for (const std::string& n : { std::string(base), std::string(base) + "_host" })
if (sel(n.c_str())) skip(n.c_str(), why);
};
for (const char* n : { "ar_oneshot_4rank_exact", "ar_oneshot_8rank_exact",
"ar_twoshot_4rank_exact", "ar_twoshot_8rank_exact",
"ar_twoshot_4rank_ti8" })
if (sel(n)) skip(n, "needs 4 or 8 peer-accessible cards");
if (sel("ar_oneshot_2rank_wht6"))
skip("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test");
if (sel("ar_ln_had_quant_i8"))
skip("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire");
skip_pair(n, "needs 4 or 8 cards");
skip_pair("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test");
skip_pair("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire");
/* Same reason, and one more: the norm half of it is rmsnorm_quant_fp8's, called through the
* same device function, so what a single-rank harness could check here is already checked
* there. What it cannot check without a peer -- the handshake and the reduced sum -- is what
* the two-rank harness is for. The engine covers it end to end: a decode step issues this op
* at every one of the 128 sites, and the generated text is compared byte for byte against a
* build that issues the pair instead. */
if (sel("ar_rmsnorm_quant_fp8"))
skip("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank");
skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank");
dfree_all();
}