radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+10 -6
View File
@@ -281,11 +281,13 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla
long stream, long nblocks, long nthreads, long drain, long acq);
// The exact all-reduce of `y` [M][n] bf16 with hc_write as its epilogue: h[r][c*n + i] +=
// inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and
// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight.
// `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate`
// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed); `gate_ctr`
// is the instance's block counter for it. The gather form below takes the same pair.
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream, long nblocks, long nthreads,
long drain, long acq);
long drain, long acq, long gate, long gate_ctr);
// The same with the MoE gather as its prologue: y is not read but produced -- the routed experts'
// rows `ye` [M*top_k][ye_ld] summed back to token order by the weights `ew` [M][ew_ld] and the
// sorted list `sorted` [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded
@@ -298,19 +300,21 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
long n, long hc, long irow, long hrow, long ye, long ew, long sorted,
long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld,
long top_k, long sig, long stream, long nblocks, long nthreads,
long drain, long acq, long inv);
long drain, long acq, long inv, long gate, long gate_ctr);
// r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's
// format and arithmetic, its loc_pack and scratch split): byte-identical to all_reduce on that wire
// then hc_write, and with `ye` non-zero to moe_gather, then those two. The gather's operands are
// r4d_ar_gather_hc_write's; its slot table is built in LDS, and the grid is widened until a
// block's table fits. M*n must be a multiple of 64. Returns 0, or a negative code for a shape it
// does not serve.
// block's table fits. M*n must be a multiple of 64. A non-zero `gate` is the engine's link word,
// ended by the launch once the peer's bytes have landed (r4d_ar_link_landed); `gate_ctr` is the
// instance's block counter for it. Returns 0, or a negative code for a shape it does not serve.
int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long loc_pack, long slot_stride_bytes,
long scale_off_bytes, long y, long inj, long h, long M, long n, long hc,
long irow, long hrow, long ye, long ew, long sorted, long sh, long sg,
long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig,
long stream, long nblocks, long nthreads, long drain, long acq);
long stream, long nblocks, long nthreads, long drain, long acq,
long gate, long gate_ctr);
int r4d_ar_max_blocks(void); // the two 2-rank kernels
void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit payload only
+35 -10
View File
@@ -123,6 +123,7 @@ struct ArInst {
/* 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;
long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */
};
/* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one
@@ -139,6 +140,10 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) {
long align16(long v) { return (v + 15) & ~15L; }
/* The sequence counters' allocation in words: 2 * nbw (r4d_ar_seq.h) and, after them, the block
* counter r4d_ar_link_landed keeps, padded to a cache line. */
long kSeqWords(long nbw) { return 2L * nbw + 32; }
/* Build the world. `max_numel` is the largest message any launch on this instance will carry.
*
* ONE SIZING RULE FOR THE WHOLE FAMILY, which is also what libr4d's own driver did ("one set
@@ -220,8 +225,8 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
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); });
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen);
if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen); });
if (!sc || !fl || !sq) return RAD_E_NOMEM;
/* SAY IT, because the fallback above changes what the KERNEL's fence settings mean. The
@@ -254,6 +259,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
in->my_flags = fl;
in->my_seq = sq;
in->locpack = lp;
in->gate_ctr = sq + 2L * maxb * 4; /* the word after the sequence counters (r4d_ar_seq.h) */
{
std::lock_guard<std::mutex> lk(g_rv.m);
@@ -482,6 +488,15 @@ extern "C" void r4d_rad_ar_fini(void* instance) {
/* ------------------------------------------------------------------ launch helpers */
/* THE ENGINE'S LINK WORD, where it handed one (rad_abi.h, `link_gate`). Over P2P the fused kernels
* end the hold as the peer's push lands, on either wire, and say so (RAD_LINK_ENDED); through the
* host mailbox it is the reduce that reads those bytes across the link, so those launches return
* RAD_OK and leave the hold to the engine. */
static long link_gate(const RadArgs* a) {
long long g = 0;
return rad_args_geti(a, "link_gate", &g) ? (long)g : 0L;
}
enum { AR_X = 0, AR_Y };
struct ArCall {
@@ -1350,26 +1365,32 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) {
if (!in->locpack) return RAD_E_STATE;
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, R4D_AR_WHT6_NB_CAP);
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
const long gate = link_gate(a), early = in->host ? 0L : gate;
const int rc = r4d_ar_hc_write_wht6(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj),
r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, r4d_addr(ye),
r4d_addr(ew), r4d_addr(so), sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L,
(long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig,
(long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq);
return rc == 0 ? RAD_OK : RAD_E_SHAPE;
(long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq,
early, early ? in->gate_ctr : 0L);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap);
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
const long gate = link_gate(a), early = in->host ? 0L : gate;
const int rc = r4d_ar_gather_hc_write(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc,
(long)irow, (long)hrow, r4d_addr(ye), r4d_addr(ew), r4d_addr(so),
sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld,
(long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads,
cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L);
return rc == 0 ? RAD_OK : RAD_E_SHAPE;
cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early,
early ? in->gate_ctr : 0L);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* AT FOUR RANKS, EXACT WIRE ONLY: r4d_rad_ar_hc_write_4rank with the gather in front, on an
@@ -1477,23 +1498,27 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) {
if (!in->locpack) return RAD_E_STATE;
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, R4D_AR_WHT6_NB_CAP);
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
const long gate = link_gate(a), early = in->host ? 0L : gate;
const int rc = r4d_ar_hc_write_wht6(
in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq,
in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj),
r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS,
cfgv.drain, cfgv.acq);
return rc == 0 ? RAD_OK : RAD_E_SHAPE;
cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L);
if (rc != 0) return RAD_E_SHAPE;
return early ? RAD_LINK_ENDED : RAD_OK;
}
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(words16, in->nb_cap);
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
const long gate = link_gate(a), early = in->host ? 0L : gate;
R4D_TRY("ar_hc_write",
r4d_ar_hc_write(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags,
in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h),
(long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s,
nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq));
return RAD_OK;
nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early,
early ? in->gate_ctr : 0L));
return early ? RAD_LINK_ENDED : RAD_OK;
}
/* AT FOUR RANKS, EXACT WIRE ONLY: the wide one-shot with the write as its epilogue. The four-rank
+13 -7
View File
@@ -142,9 +142,11 @@ __global__ void r4d_ar_hc_write_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw) {
int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate,
unsigned int* gate_ctr) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const int slot = (int)s_slot;
@@ -175,6 +177,7 @@ __global__ void r4d_ar_hc_write_kernel(
}
}
__syncthreads();
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (acq) __threadfence_system();
const int wpr = n >> 3; // 16B words a row
@@ -225,12 +228,13 @@ __global__ void r4d_ar_gather_hc_write_kernel(
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G,
const int* __restrict__ inv) {
const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
__shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS];
__shared__ float s_w[R4D_ARG_ROWS * R4D_ARG_SLOTS];
__shared__ float s_g[R4D_ARG_ROWS];
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const int slot = (int)s_slot;
@@ -286,6 +290,7 @@ __global__ void r4d_ar_gather_hc_write_kernel(
}
}
__syncthreads();
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (acq) __threadfence_system();
for (int k = start + tid; k < end; k += nt) {
@@ -398,7 +403,7 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads,
long drain, long acq) {
long drain, long acq, long gate, long gate_ctr) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8");
if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words");
@@ -415,7 +420,8 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
r4d_ar_hc_write_kernel<<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw);
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw,
(long long*)gate, (unsigned int*)gate_ctr);
}
int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
@@ -423,7 +429,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
long n, long hc, long irow, long hrow, long ye, long ew, long sorted,
long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld,
long top_k, long sig, long stream_i, long nblocks, long nthreads,
long drain, long acq, long inv) {
long drain, long acq, long inv, long gate, long gate_ctr) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2;
@@ -466,13 +472,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
(const int*)inv);
(const int*)inv, (long long*)gate, (unsigned int*)gate_ctr);
} else {
r4d_ar_gather_hc_write_kernel<false><<<nb, nt, 0, st>>>(
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h,
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G,
nullptr);
nullptr, (long long*)gate, (unsigned int*)gate_ctr);
}
return (int)hipGetLastError();
}
+8 -3
View File
@@ -77,12 +77,14 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs,
const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n, int hc,
long irow, long hrow, int n_groups, int n_chunks, long slot_stride_bytes,
long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max) {
long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max,
long long* gate, unsigned int* gate_ctr) {
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE;
const int lig = lane & (LPG - 1), gw = lane / LPG;
__shared__ unsigned int s_seq, s_slot;
extern __shared__ int s_tab[]; // slots, weights: [rows_max * top_k]; gates: [rows_max]
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe (cudagraph)
const unsigned int s = s_seq;
const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot,
@@ -145,6 +147,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel(
wht6_push_chunk<CG>(ld, c, n_groups, lane, lig, gw, w.p_pay, w.p_sc, w.l_pay, w.l_sc);
wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq);
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
for (int c = c0 + wid; c < c1; c += nwarp)
wht6_reduce_chunk<CG>(st, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, w.l_pay, w.l_sc);
@@ -155,7 +158,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
long scale_off_bytes, long y, long inj, long h, long M, long n, long hc,
long irow, long hrow, long ye, long ew, long sorted, long sh, long sg,
long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig,
long stream_i, long nblocks, long nthreads, long drain, long acq) {
long stream_i, long nblocks, long nthreads, long drain, long acq,
long gate, long gate_ctr) {
hipStream_t st = (hipStream_t)stream_i;
if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1;
if ((M * n) % GROUP) return -1;
@@ -197,7 +201,8 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo
(unsigned short*)y, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, \
(unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, \
(unsigned short*)h, (int)n, (int)hc, irow, hrow, n_groups, n_chunks, slot_stride_bytes, \
scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max)
scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max, \
(long long*)gate, (unsigned int*)gate_ctr)
if (gather) LF(true, kWht6FusedCG);
else LF(false, kWht6FusedCG);
#undef LF
+33 -1
View File
@@ -5,7 +5,7 @@
// instance's buffers has to take the step identically or the two ranks stop agreeing.
//
// THE COUNTER ALLOCATION IS 2 * nbw WORDS, zeroed once, where nbw is the block capacity the flag
// array was sized for:
// array was sized for, and the landed counter after them (r4d_ar_link_landed):
//
// [0, nbw) HANDSHAKE counters, one a block. Block b advances word b once per launch it
// runs in, publishes the new value to the peer and waits for the peer's. Kept per
@@ -19,6 +19,9 @@
// of them always equal the number of launches, and each block reads the slot
// parity off its own word without talking to any other block.
//
// [2*nbw] the LANDED counter: the blocks of the running launch that have seen their
// peer's push land, back at zero when the launch ends.
//
// WHY THE SLOT CANNOT COME OFF THE HANDSHAKE COUNTER. The double-buffered scratch is safe only if
// consecutive launches on one instance use opposite slots: launch k+1 may push while the peer is
// still reducing launch k, and it must not land in the bytes being read. Block counts differ from
@@ -56,6 +59,35 @@ __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs,
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
}
// THE ENGINE'S HOLD ON THE LINK, ENDED BY THE LAUNCH (rad_abi.h, rad_kernel_collective answering
// 2). The word is odd exactly while the engine holds the link for this launch, and nothing else
// writes it while the launch runs, so its value is read once, at the start, by each block's first
// thread (r4d_ar_link_word): the read crosses to host memory, and at the start it overlaps the push
// where at the end it would hold up the reduce.
//
// r4d_ar_link_landed is called by every block once its handshake has seen the peer's push to it
// land. The last block to get there knows every byte the peer sends this card has arrived, so the
// link is free for the rest of the kernel's run -- the reduce and whatever it writes -- and takes
// one off the word if it was odd, with an atomic so it commutes with any barrier counting the same
// word down. `ctr` counts the blocks and is back at zero when the launch ends, ready for the next
// one on the stream. The word is in memory the DMA engine polls past every cache, so it is read and
// written at system scope.
__device__ __forceinline__ long long r4d_ar_link_word(const long long* gate, unsigned int tid) {
return gate && tid == 0 ? __hip_atomic_load(gate, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)
: 0;
}
__device__ __forceinline__ void r4d_ar_link_landed(long long* gate, long long word,
unsigned int* ctr, unsigned int nb,
unsigned int tid) {
if (!gate || tid != 0) return;
const unsigned int prev = __hip_atomic_fetch_add(ctr, 1u, __ATOMIC_RELAXED,
__HIP_MEMORY_SCOPE_AGENT);
if (prev + 1u != nb) return;
__hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
if (word & 1) __hip_atomic_fetch_add(gate, -1LL, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
// True while `flag` has not yet reached `want`. The counters are u32 and wrap, so the comparison is
// on the signed difference: a peer at or past `want` -- it may already be a launch ahead -- reads
// as arrived on either side of the wrap, where a plain `flag < want` stops waiting altogether once
+38 -5
View File
@@ -17,6 +17,7 @@
#include "r4d_common.h"
#include "r4d_dt16.h"
#include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2)
#include <type_traits>
#define O_F16 1
#define O_MSKIP 2
@@ -58,6 +59,19 @@
// conversion is exact, so the fragments, and every byte after them, match the f16 tile's. With more
// waves a workgroup each would convert the whole tile, so the launcher sets it at one.
#define O_V8 8388608
// O_KRAW: with K read straight from the paged cache (KLDS0, CONTIG), an m-tile's K is loaded in ONE
// round -- all HEAD_DIM/16 fragment loads, issued as soon as the row address is known -- and each
// fragment is converted from its registers just before its WMMA.
//
// The prefetch depth (PF) and the scheduling barrier between a group's loads and its WMMAs say
// what may overlap, and a compiler is free to honour them literally: LLVM 24 does, and with PF 2 a
// tile's K then arrives in HEAD_DIM/32 round trips, one after another, which cost the head_dim-128
// drafter leg 16-19% on a bf16 cache. LLVM 22 lifted the loads over the barriers and issued them in
// one round. This bit asks for that round explicitly. What is held is the cache's own bytes -- 8 a
// fragment from fp8, 16 from bf16 -- not the converted fragment, so a full round costs 2 or 4 x
// HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold every converted fragment at once and cost the
// waves a SIMD. The fragments, and every byte after them, are unchanged.
#define O_KRAW 16777216
// `__builtin_nontemporal_load` will not take `uint4`/`uint2` -- they are HIP_vector_type class
// templates, not native vectors -- so the hinted loads go through these and bit-cast the WHOLE
// value back (never a subscript of it, which miscompiles).
@@ -107,6 +121,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
constexpr int KNT = (OPT & O_KNT) ? 1 : 0;
constexpr int V8 = ((OPT & O_V8) && !KVP) ? 1 : 0;
static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout");
constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0;
static_assert(!KRAW || (OPT & O_CONTIG), "the raw K round reads the contiguous layout");
typedef DT16<F16> D;
typedef typename D::frag frag16;
@@ -339,6 +355,14 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM))
* (KVP ? 2 : 1);
}
// A fragment's K bytes: 8 elements at 1 byte (fp8) or 2 (bf16), as the branches below read.
typedef typename std::conditional<KVP != 0, uint4, uint2>::type kraw_t;
kraw_t kraw[KRAW ? NKS : 1];
if constexpr (KRAW) {
#pragma unroll
for (int t = 0; t < NKS; ++t)
kraw[t] = *(const kraw_t*)(grow + (16 * t + 8 * h) * (KVP ? 2 : 1));
}
v8f s = (v8f){0,0,0,0,0,0,0,0};
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
@@ -357,17 +381,26 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits)
}
} else if (KVP) {
const uint16_t* kp = (const uint16_t*)grow + 16 * t;
const uint2 l0 = *(const uint2*)(kp + (CTG ? 8 * h : 4 * h));
const uint2 h0 = *(const uint2*)(kp + (CTG ? 8 * h + 4 : 8 + 4 * h));
uint2 l0, h0;
if constexpr (KRAW && KVP != 0) {
const uint4 u = kraw[t];
l0 = make_uint2(u.x, u.y);
h0 = make_uint2(u.z, u.w);
} else {
l0 = *(const uint2*)(kp + (CTG ? 8 * h : 4 * h));
h0 = *(const uint2*)(kp + (CTG ? 8 * h + 4 : 8 + 4 * h));
}
kb[j] = D::mk(make_uint2(D::from_bf16w(l0.x), D::from_bf16w(l0.y)),
make_uint2(D::from_bf16w(h0.x), D::from_bf16w(h0.y)));
} else {
const uint8_t* kp = grow + 16 * t;
uint32_t w4[4];
// CONTIG makes this ONE 8-byte load where the split map needs two 4-byte.
const uint2 raw = CTG ? *(const uint2*)(kp + 8 * h)
: make_uint2(*(const uint32_t*)(kp + 4 * h),
*(const uint32_t*)(kp + 8 + 4 * h));
uint2 raw;
if constexpr (KRAW && KVP == 0) raw = kraw[t];
else raw = CTG ? *(const uint2*)(kp + 8 * h)
: make_uint2(*(const uint32_t*)(kp + 4 * h),
*(const uint32_t*)(kp + 8 + 4 * h));
fp8x8_to_16x4w<D>(raw, w4);
kb[j] = D::mk(make_uint2(w4[0], w4[1]), make_uint2(w4[2], w4[3]));
}
+34 -8
View File
@@ -13,13 +13,14 @@
// bound is the constraint value the selector bands on, so it is stated in the row and nowhere
// else. A prefill block carries `NWARPS * 16 / gqa` query positions, 48 here against 64 there.
//
// WHAT CHANGES WITH HEAD_DIM IS ONE OPTION BIT. `O_KWIDE` fetches 16 K elements a thread and its
// WHAT CHANGES WITH HEAD_DIM IS HOW K IS FETCHED. `O_KWIDE` fetches 16 K elements a thread and its
// thread-to-(key, channel) map is written for 16 channels of 16 -- which is head_dim 256 exactly.
// At 128 it would stage past the tile, so the h128 prefill runs the same option set without it
// (3430923 against 3955211) and pays one more pass over a tile that is half the size. Everything
// else -- the lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k
// fragments, the SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and
// each bit is defined and justified in r4d_attn_prefill_h256_gqa6.hip.
// At 128 it would stage past the tile, so the h128 prefill runs without it and pays one more pass
// over a tile that is half the size; and its fragments are half as many registers, so it keeps a
// K prefetch of 4 where head_dim 256 takes 2 (3430923 against 3954187). Everything else -- the
// lazy reference-max softmax, f16 operands, the folded query scale, contiguous-k fragments, the
// SGPR block table, the V prefetch, the LDS-scoped barrier -- is unchanged, and each bit is
// defined and justified in r4d_attn_prefill_h256_gqa6.hip.
//
// NO `r4d_attn_dims` HERE. That entry point and the `check_dims_once` assertion built on it are
// the h256/gqa6 unit's statement about ITSELF, and a second definition would not link. A geometry
@@ -55,6 +56,14 @@ using std::max;
#define R4D_ATTN_GQA 8
#define R4D_ATTN_H128 1 /* this ratio also serves head_dim 128 -- MiniCPM5-2B is 16 over 2 */
#endif
/* A head_dim 64 PREFILL leg, off unless the including unit asks for it: LFM2 is 32 query heads
* over 8 at head_dim 64 (r4d_attn_paged_h256_gqa4.hip). It runs the h128 prefill option set --
* O_KWIDE's 16-channel staging is written for 256. There is no decode leg: the split-KV kernel
* holds a lane's columns as one or two dwords of codes, which is head_dim 128 or 256, so the
* query-tiled kernel serves every query length at this width. */
#ifndef R4D_ATTN_H64
#define R4D_ATTN_H64 0
#endif
#define GQ_JOIN_(a, b, c) a##b##c
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
#define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf)
@@ -73,8 +82,11 @@ using std::max;
#define G8_P_NWARPS 24
#define G8_P_TILE 48
#define G8_P_OPT_256 3955211
#define G8_P_OPT_128 3430923 // the same set without O_KWIDE; see the header
// K prefetch 2, as the h256/gqa6 prefill and for the same reason (see P_OPT there): 4 spills the
// m-tile loop. The head_dim-128 set keeps its prefetch of 4, which fits.
#define G8_P_OPT_256 3954187
#define G8_P_OPT_128 3430923 // without O_KWIDE, at prefetch 4; see the header
#define G8_P_OPT_64 G8_P_OPT_128
#define G8_D_TILE 16
#define G8_D_OPT 3429947
#define G8_D_JPB 2
@@ -230,6 +242,20 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h128_gqa, _bf16)(const RadArgs* a, Ra
return g8_prefill_launch<128, G8_P_OPT_128, 1>(&r, (hipStream_t)s);
}
#endif
#if R4D_ATTN_H64
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _fp8)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 64);
if (rc != RAD_OK) return rc;
return g8_prefill_launch<64, G8_P_OPT_64, 0>(&r, (hipStream_t)s);
}
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, RadStream s) {
R4DArgs r;
const int rc = fill_paged(a, &r, 64);
if (rc != RAD_OK) return rc;
return g8_prefill_launch<64, G8_P_OPT_64, 1>(&r, (hipStream_t)s);
}
#endif
/* The split-KV partial buffer, sized at declare from the band's upper bound. IT IS CALLED WITH
* PARAMETERS AND NO TENSORS -- that is what declare is -- so the parameters are the primary source
+4 -2
View File
@@ -37,8 +37,10 @@ using std::max;
// The same option set the h256 decode kernel ships, K prefetch of 2 included. This geometry does
// not need it -- head_dim 128 halves both the accumulator and the query, so it sits at 162-179
// VGPRs and does not spill at 4 -- but 2 is still 0.3-1.3% faster at every concurrency and window,
// for bit-identical output, so the two legs stay on one number.
#define B_OPT 3429947
// for bit-identical output, so the two legs stay on one number -- plus O_KRAW, which loads an
// m-tile's K codes in one round (see r4d_attn_decode_h256_gqa6.hip): at head_dim 128 that round is
// 16 VGPRs and leaves the residency where it was.
#define B_OPT 20207163
#ifndef B_JPB
#define B_JPB 2
#endif
+3
View File
@@ -11,8 +11,11 @@
//
// NO head_dim 128 LEG. gqa 4 at 128 is the DFlash2 drafter's windowed geometry, which
// r4d_attn_paged_h128_gqa4.hip serves; R4D_ATTN_H128 leaves those entry points out of this unit.
// A head_dim 64 PREFILL leg, for LFM2 (32 query heads over 8, d1-3B among them), which serves
// every query length: the split-KV decode kernel has no 64-wide form.
// The page is the body's default 16.
#define R4D_ATTN_GQA 4
#define R4D_ATTN_H128 0
#define R4D_ATTN_H64 1
#include "r4d_attn_paged_gqa8.hip"
+6 -3
View File
@@ -10,8 +10,8 @@
// the production configuration).
//
// `opt` is a bitmask of the optimisation steps, all of them on:
// prefill 3955211 = f16 operands | mask skip | folded query scale | contiguous-k fragments
// | prefetch 4 + scheduling barrier | dot2 row sum | block table in SGPRs
// prefill 3954187 = f16 operands | mask skip | folded query scale | contiguous-k fragments
// | prefetch 2 + scheduling barrier | dot2 row sum | block table in SGPRs
// | wide K fetch | V prefetch across the m-tile loop | LDS-scoped barrier
// decode 3429947 = the same, minus the wide K fetch (its K never reaches LDS), with the K
// prefetch at 2 rather than 4, plus reading K straight from the paged cache
@@ -50,7 +50,10 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max
// would need 68096 B > 65536, so the geometry stops at 48.
#define P_NWARPS 24
#define P_TILE 48
#define P_OPT 3955211
// K PREFETCH 2, NOT 4. Four fragments in flight hold more than the m-tile loop has to give at six
// waves a SIMD, and the loop then spills: LLVM 22 to 36 bytes a lane and LLVM 24 to 48, which cost
// LLVM 24 4% of the prefill. At 2 both compilers spill the same 20 bytes, outside the WMMA groups.
#define P_OPT 3954187
// KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below.
template <int KVP>
+66
View File
@@ -39,10 +39,27 @@ __device__ __forceinline__ int r4d_q_seq(const int* cu_q, int num_seqs, int q_le
return lo;
}
// ---- the occupancy a kernel is built for ---------------------------------------------------------
// R4D_WAVES(n) fixes the waves a SIMD the compiler schedules a kernel for. Left to itself the
// scheduler picks that target, trading registers for occupancy or the reverse, and the choice
// moves between compiler releases: LLVM 24 serialises a GEMM's loads to win one more wave a SIMD,
// paying a load round trip per WMMA, and elsewhere hoists more loads and gives a wave up. A kernel
// whose speed rests on a register budget states the budget with this, so the source and not the
// compiler version decides it. `n` may depend on template arguments.
#define R4D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n))))
typedef short v8s __attribute__((ext_vector_type(8)));
typedef float v8f __attribute__((ext_vector_type(8)));
typedef float v2f __attribute__((ext_vector_type(2))); // what cvt_pk_f32_fp8 actually returns
/* A 16-BYTE STAGING REGISTER AS A NATIVE VECTOR. HIP's uint4 is a class template wrapping a union,
* and an array of them that a K loop carries -- the next tile's chunks, loaded while this tile is
* computed -- is not promoted to registers: LLVM 22 and LLVM 24 both keep it in scratch, so every
* staged chunk goes global load, scratch store, scratch load, LDS store. The same array of an
* ext_vector_type is promoted. Loaded and stored whole only; r4d_dflash_conv_body.h declares the
* same type for a source that is also compiled without this header. */
typedef unsigned int r4d_u32x4 __attribute__((ext_vector_type(4)));
// exp2 with the hardware transcendental.
__device__ __forceinline__ float ex2(float x) {
@@ -65,6 +82,55 @@ __device__ __forceinline__ float bf16_to_f32(uint16_t h) {
return __builtin_bit_cast(float, (uint32_t)h << 16);
}
// ---- 16-bit values held in whole registers -------------------------------------------------------
// LLVM 24 gives gfx12 real 16-bit registers: a value of a 16-bit type lives in one HALF of a VGPR.
// Two bf16 assembled into a word then cost a shift and a half move each pair where LLVM 22 used one
// v_perm_b32, a bf16 widened to a float costs a half move and a shift, and a 16-bit load goes into a
// half (global_load_d16_b16), so it depends on the register's earlier contents and the waitcnt pass
// waits for them. The helpers below keep bf16 data in whole 32-bit registers from load to store,
// which compiles to the same code under both compilers. The bits are the same as the 16-bit forms.
// f32 -> bf16 rounded to nearest even, as the HIGH half of a word whose low half is not zero:
// f32_to_bf16 before its final shift. A NaN can round to infinity here, as there.
__device__ __forceinline__ uint32_t bf16_hi_rne(float f) {
const uint32_t u = __float_as_uint(f);
return u + 0x7fffu + ((u >> 16) & 1u);
}
// The same as (__hip_bfloat16)f computes it (LLVM's own expansion of the conversion): a NaN stays
// a NaN, made quiet, and everything else rounds to nearest even. Both results are formed before
// the choice so it compiles to one v_cndmask: written as `nan ? u | 0x400000 : u + ...`, the
// rounding is too long to speculate and each element becomes an exec-masked branch.
__device__ __forceinline__ uint32_t bf16_hi_rne_nan(float f) {
const uint32_t u = __float_as_uint(f);
const uint32_t r = u + 0x7fffu + ((u >> 16) & 1u), q = u | 0x400000u;
return f != f ? q : r;
}
// Two such words as one bf16 pair, `lo`'s high half in the low half: one byte permute.
__device__ __forceinline__ uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) {
return __builtin_amdgcn_perm(hi, lo, 0x07060302u);
}
// Two floats as a bf16 pair (`lo` in the low half), rounded as f32_to_bf16 rounds.
__device__ __forceinline__ uint32_t bf16x2_rne(float lo, float hi) {
return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi));
}
// Two floats as a bf16 pair, rounded as (__hip_bfloat16) rounds.
__device__ __forceinline__ uint32_t bf16x2_rne_nan(float lo, float hi) {
return bf16_pack_hi(bf16_hi_rne_nan(lo), bf16_hi_rne_nan(hi));
}
// A bf16 pair word's two values as floats: a shift and a mask, no conversion.
__device__ __forceinline__ float bf16w_lo(uint32_t w) { return __uint_as_float(w << 16); }
__device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w & 0xffff0000u); }
// One 16-bit element of global memory, zero-extended into a whole register (global_load_u16).
// Read as a uint16_t and widened afterwards, it is loaded into a register half instead
// (global_load_d16_b16, or d16_hi_b16 straight into the bf16's float position), which waits for
// the register's other half; through a generic pointer it is a flat load as well. The pointer
// must address global memory.
typedef __attribute__((address_space(1))) const uint16_t* r4d_gu16;
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r4d_gu16)p; }
// The same element as a bf16 widened to float.
__device__ __forceinline__ float ldg_bf16(const uint16_t* p) { return bf16w_lo(ldg_u16(p)); }
// `lane ^ N` WITHOUT THE LDS PIPE. `__shfl_xor` lowers to `ds_bpermute_b32` plus an
// `s_wait_dscnt` -- an LDS round trip, and when the exchange sits on a dependency chain (a dot
// product closed inside a token loop, say) that latency is the loop. gfx10 and up carry ROW_XMASK
+36 -15
View File
@@ -72,14 +72,29 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
// candidate, so it is computed once per step and read K times out of LDS.
__shared__ float sa[DSL_MAX_R];
__shared__ float ssc[DSL_MAX_K];
__shared__ int schosen; // the previous step's INDEX into its candidate list
__shared__ int spid; // the token the previous step chose: this step's predecessor
// THE CANDIDATES A WAVE SCORES, at most this many: c = wave, wave + DSL_WAVES, ...
constexpr int CPW = (DSL_MAX_K + DSL_WAVES - 1) / DSL_WAVES;
for (int l = 0; l < steps; ++l) {
const long row = (long)s * steps + l;
// THE STEP'S OWN READS GO FIRST. The candidates' ids and unary scores do not depend on the
// predecessor, so they are in flight with its codebook row instead of behind the barrier, each
// a round trip of its own in a walk that is nothing but round trips. A wave past K re-reads
// the last candidate and scores nothing.
int cid[CPW];
float un[CPW];
#pragma unroll
for (int i = 0; i < CPW; ++i) {
const int c = wave + i * DSL_WAVES;
const long at = row * cand_ld + (c < K ? c : K - 1);
cid[i] = cand[at];
un[i] = unary[at];
}
// Step 0's predecessor is the committed anchor; every later step's is the token this walk
// picked last time round, which is why the read has to happen after the barrier below.
const int pid = (l == 0) ? anchor[(long)s * anchor_stride]
: cand[(row - 1) * cand_ld + schosen];
// picked last time round, which thread 0 left in LDS before the barrier that ended that step.
const int pid = (l == 0) ? anchor[(long)s * anchor_stride] : spid;
const bool pid_ok = pid >= 0 && pid < V;
const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R;
@@ -99,16 +114,21 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
__syncthreads();
// One wave a candidate. R is a multiple of the wave, so the strided loop is balanced and the
// reduction is five xor-butterfly steps with no barrier inside it.
for (int c = wave; c < K; c += DSL_WAVES) {
const int cid = cand[row * cand_ld + c];
float acc = 0.0f;
if (cid >= 0 && cid < V) {
const r4d_u16* __restrict__ srow = succ + (long)cid * R;
// reduction is five xor-butterfly steps with no barrier inside it. A candidate out of range
// reads codebook row 0 and drops the sum, so the row's loads are never in a branch of their
// own; its score is its unary term alone either way.
#pragma unroll
for (int i = 0; i < CPW; ++i) {
const int c = wave + i * DSL_WAVES;
if (c < K) {
const bool ok = cid[i] >= 0 && cid[i] < V;
const r4d_u16* __restrict__ srow = succ + (long)(ok ? cid[i] : 0) * R;
float acc = 0.0f;
#pragma unroll 8
for (int r = lane; r < R; r += DSL_WAVE) acc += sa[r] * r4d_bf2f(srow[r]);
acc = r4d_wave_sum(ok ? acc : 0.0f);
if (lane == 0) ssc[c] = acc + un[i];
}
acc = r4d_wave_sum(acc);
if (lane == 0) ssc[c] = acc + unary[row * cand_ld + c];
}
__syncthreads();
@@ -120,10 +140,11 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel(
float bv = -INFINITY;
for (int c = 0; c < K; ++c)
if (ssc[c] > bv) { bv = ssc[c]; best = c; }
schosen = best;
out[(long)s * out_ld + l] = cand[row * cand_ld + best];
const int tok = cand[row * cand_ld + best];
spid = tok;
out[(long)s * out_ld + l] = tok;
}
// Both directions: the next step reads `schosen` and overwrites `sa`, and every other thread
// Both directions: the next step reads `spid` and overwrites `sa`, and every other thread
// is still reading this step's.
__syncthreads();
}
+5
View File
@@ -161,6 +161,11 @@ __device__ __forceinline__ v2f e4m3_pk(uint32_t q) {
__device__ __forceinline__ float bscale(uint16_t s) {
return __uint_as_float((uint32_t)s << 16);
}
/* The same scale held zero-extended in a whole register: the form a 16-bit value should stay in
* from its load on (see u16_load_w in r4d_moe.hip). The upper sixteen bits must be zero. */
__device__ __forceinline__ float bscale(uint32_t s) {
return __uint_as_float(s << 16);
}
// ---- LDS staging, shared by both fp8a8 instantiations -------------------------------------------
//
@@ -332,6 +332,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
__shared__ unsigned short cvq[CV ? RU_CVT * RU_K : 1], cvk[CV ? RU_CVT * RU_K : 1];
__shared__ unsigned short cvv[CV ? RU_CVT * RU_V : 1];
__shared__ int cvlast;
/* THE KEY HEAD'S HISTORY FOR THE REWRITE AT THE END, parked here once its taps are computed: the
* two newest history entries and this step's inputs, one channel a thread. Held in registers they
* stay live across the whole token loop, ten values a thread that the loop's h, q and k leave no
* room for -- they went to scratch, and other values with them. */
__shared__ unsigned short cvh[CV ? (CS - 1 + RU_CVT) * THR : 1];
/* THE TOKEN LOOP'S OWN GLOBAL READS, STAGED THE SAME WAY. Per token the loop reads `a` and `b`
* (the decay and beta inputs, one scalar each) and the output gate's row, and at decode there
* is well under a wave a SIMD to hide a load behind -- read in the loop, each is a full global
@@ -494,7 +499,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
// A NEGATIVE slot is the pad and ZERO IS A REAL SLOT -- see the same rule in
// r4d_gdn_conv_w4_h128_bf16.hip. A `<= 0` test here loses the first sequence's state entirely.
if (si < 0) return;
const int grp = row >> 5; // fixed 32-row group, see RU_FSTR
/* Fixed 32-row group, see RU_FSTR. One per WAVE: a wave's 32 threads are 16 consecutive rows from
* a multiple of 16, inside one group whatever VS is (a workgroup's first row is a multiple of
* NR >= 32). Said so to the compiler, the factor addresses it scales are scalar; as a lane value
* they were 64-bit VGPR offsets live across the token loop and reloaded from scratch there. */
const int grp = __builtin_amdgcn_readfirstlane(row >> 5);
float h[RU_HK];
{
@@ -571,6 +580,11 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
}
};
conv(cwa, cba, cha, cxa, (tid < RU_K ? cvq : cvk) + (tid & (RU_K - 1)));
#pragma unroll
for (int i = 1; i < CS; ++i) cvh[(i - 1) * THR + tid] = cha[i];
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
if (t < T) cvh[(CS - 1 + t) * THR + tid] = cxa[t];
if (tid < RU_V) {
conv(cwb, cbb, chb, cxb, cvv + tid);
ru_conv_rewrite(spb, chb, cxb, T, cv.cs_tok);
@@ -808,7 +822,14 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
__syncthreads();
if (!cvlast) return;
}
ru_conv_rewrite(spa, cha, cxa, T, cv.cs_tok);
unsigned short rh[CS], rx[RU_CVT];
rh[0] = 0; /* never read: the oldest entry is shifted out */
#pragma unroll
for (int i = 1; i < CS; ++i) rh[i] = cvh[(i - 1) * THR + tid];
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
rx[t] = t < T ? cvh[(CS - 1 + t) * THR + tid] : (unsigned short)0;
ru_conv_rewrite(spa, rh, rx, T, cv.cs_tok);
}
}
+14 -7
View File
@@ -29,6 +29,7 @@
// last valid row, computes a result nobody stores, and never touches memory it does not own.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include <hip/hip_bf16.h>
#include <cstdint>
@@ -95,27 +96,27 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
for (int j = 0; j < TN; ++j) tot[i][j] = (v8f)(0.f);
}
uint4 ra[AL], rw[WL];
r4d_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch
#pragma unroll
for (int i = 0; i < AL; ++i) ra[i] = *(const uint4*)(A + aoff[i]);
for (int i = 0; i < AL; ++i) ra[i] = *(const r4d_u32x4*)(A + aoff[i]);
#pragma unroll
for (int i = 0; i < WL; ++i) rw[i] = *(const uint4*)(W + woff[i]);
for (int i = 0; i < WL; ++i) rw[i] = *(const r4d_u32x4*)(W + woff[i]);
const int nk = K / BT_BK;
int left = spk; // k steps to the end of this split slice
for (int kt = 0; kt < nk; ++kt) {
__syncthreads(); // the previous tile's fragments are all read
#pragma unroll
for (int i = 0; i < AL; ++i) *(uint4*)adst[i] = ra[i];
for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i];
#pragma unroll
for (int i = 0; i < WL; ++i) *(uint4*)wdst[i] = rw[i];
for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i];
__syncthreads();
if (kt + 1 < nk) {
const unsigned k1 = (unsigned)(kt + 1) * BT_BK;
#pragma unroll
for (int i = 0; i < AL; ++i) ra[i] = *(const uint4*)(A + aoff[i] + k1);
for (int i = 0; i < AL; ++i) ra[i] = *(const r4d_u32x4*)(A + aoff[i] + k1);
#pragma unroll
for (int i = 0; i < WL; ++i) rw[i] = *(const uint4*)(W + woff[i] + k1);
for (int i = 0; i < WL; ++i) rw[i] = *(const r4d_u32x4*)(W + woff[i] + k1);
}
#pragma unroll
for (int s = 0; s < BT_BK / 16; ++s) {
@@ -128,6 +129,12 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = mma(af[i], bf[j], acc[i][j]);
/* A K STEP'S FRAGMENT READS, THEN ITS PRODUCTS, as the scheduler's groups. Left to itself,
* gfx12's compiler spreads each step's LDS reads among the previous step's WMMAs and waits on
* them early; grouped, the 128 x 128 tile measured 6 to 9% faster than LLVM 22's schedule at
* Flash-Next's shapes (M 384 to 2048, K 2560, N 2560 and 10240). */
__builtin_amdgcn_sched_group_barrier(0x100, TM + TN, 0); /* DS reads */
__builtin_amdgcn_sched_group_barrier(0x008, TM * TN, 0); /* WMMA */
if constexpr (SPLIT) {
if (--left == 0) {
left = spk;
+150 -19
View File
@@ -319,12 +319,52 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
#pragma unroll
for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = 0.0f;
/* AT MT <= 2 EACH PASS'S WEIGHT CHUNK, SCALE AND ACTIVATION ARE LOADED ONE PASS AHEAD (kPre),
* so a pass's loads run under the previous pass's arithmetic. Loaded in the pass that uses
* them, LLVM 24 issues them and then waits for the first three before it converts anything,
* and at M = 2 the head ran 0.65% behind LLVM 22's build; loaded ahead it is level, and M = 1
* is unchanged. Held a pass, the activation is eight registers a row, which the wider tiles do
* not have: at MT = 32 it spills a thousand slots, so they load in the pass. The last pass
* reloads its own chunk rather than reading past the row. */
constexpr bool kPre = MT <= 2u;
[[maybe_unused]] uint4 wn[RB];
[[maybe_unused]] uint32_t sn[RB];
[[maybe_unused]] uint4 xn[kPre ? MT : 1][2];
auto load = [&](uint32_t c) {
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) {
wn[r] = *(const uint4*)(w[r] + c);
sn[r] = srow[r][c / kBlock];
}
if constexpr (kPre) {
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) {
const uint4* xm = (const uint4*)(X + (size_t)xrow(m) * a_ld + c);
xn[m][0] = xm[0];
xn[m][1] = xm[1];
}
}
};
if constexpr (kPre)
if ((uint32_t)lane * 16u < full) load((uint32_t)lane * 16u);
for (uint32_t c = (uint32_t)lane * 16u; c < full; c += stride) {
float wf[RB][16];
float sc[RB];
[[maybe_unused]] uint4 wc[kPre ? RB : 1];
[[maybe_unused]] uint32_t scr[kPre ? RB : 1];
[[maybe_unused]] uint4 xc[kPre ? MT : 1][2];
if constexpr (kPre) {
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) { wc[r] = wn[r]; scr[r] = sn[r]; }
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) { xc[m][0] = xn[m][0]; xc[m][1] = xn[m][1]; }
load(c + stride < full ? c + stride : c);
}
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) {
const uint4 packed = *(const uint4*)(w[r] + c);
uint4 packed;
if constexpr (kPre) packed = wc[r];
else packed = *(const uint4*)(w[r] + c);
const uint32_t* pw = (const uint32_t*)&packed;
#pragma unroll
for (int k = 0; k < 4; ++k) {
@@ -335,14 +375,31 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
wf[r][k * 4 + 2] = e23.x;
wf[r][k * 4 + 3] = e23.y;
}
sc[r] = bscale(srow[r][c / kBlock]);
if constexpr (kPre) sc[r] = bscale(scr[r]);
else sc[r] = bscale(srow[r][c / kBlock]);
}
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) {
const uint16_t* xm = X + (size_t)xrow(m) * a_ld + c;
/* THE SIXTEEN bf16 AS EIGHT DWORDS, each widened by a shift (the even element) and a
* mask (the odd one): the same floats. Read a uint16_t at a time, LLVM 24 moves each
* into a 16-bit register half before shifting it -- two instructions an element where
* LLVM 22 took one. */
uint4 x0, x1;
if constexpr (kPre) {
x0 = xc[m][0];
x1 = xc[m][1];
} else {
const uint4* xm = (const uint4*)(X + (size_t)xrow(m) * a_ld + c);
x0 = xm[0];
x1 = xm[1];
}
const uint32_t xw[8] = { x0.x, x0.y, x0.z, x0.w, x1.x, x1.y, x1.z, x1.w };
float xv[16];
#pragma unroll
for (int k = 0; k < 16; ++k) xv[k] = __uint_as_float((uint32_t)xm[k] << 16);
for (int k = 0; k < 8; ++k) {
xv[2 * k] = __uint_as_float(xw[k] << 16);
xv[2 * k + 1] = __uint_as_float(xw[k] & 0xffff0000u);
}
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) {
float a0 = 0.0f, a1 = 0.0f;
@@ -488,17 +545,34 @@ uint32_t rb_default(uint32_t rows, uint32_t cols) {
// rather than sixteen. That is what makes the scale a scalar multiply in the epilogue of each
// block instead of a per-element gather.
typedef short lm_s8v __attribute__((ext_vector_type(8)));
typedef unsigned lm_u4v __attribute__((ext_vector_type(4)));
/* TWO DECODED CODES AS ONE bf16 PAIR: the high halves of both floats, by one byte permute. A code
* decodes to a float whose low sixteen bits are zero (E4M3's three mantissa bits, an int8's seven),
* so its bf16 is exactly those high bits -- f32_to_bf16's rounding adds less than one to the low
* half and carries nothing out of it -- and packed here it is one v_perm_b32 a pair, the rounding
* adds gone too. Built from f32_to_bf16 and the vector's lanes instead, LLVM 24's 16-bit register
* halves turn each pair into two half moves and a shift where LLVM 22 had the permute: 24 more
* instructions a K step of the M = 32 tile. The same bits either way. The floats are read with
* __float_as_uint, by value: __builtin_bit_cast of a vector's element miscompiles (see the
* nontemporal load in r4d_fp8_wmma.h), and here it fed the WMMA garbage.
*
* Every tile takes it: against the f32_to_bf16 form it is 0.3 to 0.7% faster at M = 4 to 16
* (MT 1, K 2048 to 5120), 0.8% at M = 32 (MT 2) and 7.7% at M = 64 (MT 4). */
__device__ __forceinline__ uint32_t lm_bf16_pair(v2f p) {
return __builtin_amdgcn_perm(__float_as_uint(p.y), __float_as_uint(p.x), 0x07060302u);
}
template <bool I8 = false>
__device__ __forceinline__ lm_s8v e4m3x8_to_bf16(uint32_t lo, uint32_t hi) {
const v2f a01 = code_pk<I8, false>(lo), a23 = code_pk<I8, true>(lo);
const v2f b01 = code_pk<I8, false>(hi), b23 = code_pk<I8, true>(hi);
lm_s8v r;
r[0] = (short)f32_to_bf16(a01.x); r[1] = (short)f32_to_bf16(a01.y);
r[2] = (short)f32_to_bf16(a23.x); r[3] = (short)f32_to_bf16(a23.y);
r[4] = (short)f32_to_bf16(b01.x); r[5] = (short)f32_to_bf16(b01.y);
r[6] = (short)f32_to_bf16(b23.x); r[7] = (short)f32_to_bf16(b23.y);
return r;
lm_u4v r;
r.x = lm_bf16_pair(a01);
r.y = lm_bf16_pair(a23);
r.z = lm_bf16_pair(b01);
r.w = lm_bf16_pair(b23);
return __builtin_bit_cast(lm_s8v, r);
}
// MT is ceil(M / 16): how many 16-row activation tiles ride the one weight read.
@@ -620,8 +694,21 @@ __device__ __forceinline__ lm_s8v e4m3x8_to_bf16(uint32_t lo, uint32_t hi) {
// The band is five things it is not: not the register file, not staging latency, not the straddle,
// not the activation loads, not the activation re-read. It needs a new hypothesis, not another
// pass over these.
//
// ---- THE WAVES A SIMD EACH TILE RUNS AT (R4D_WAVES) --------------------------------------------
//
// Two staged blocks a round (FKB = 2) hold 33 KB of LDS, which caps a SIMD at six waves whatever
// the registers, so six is the target there. One block a round at MT >= 3 is a register budget:
// seven waves at MT = 3 and six at MT = 4, where two K steps in flight are worth more than a
// seventh wave (above). MT <= 2 at one block is reachable only through R4D_LM_FKB and keeps the
// budget it was measured at. Without the target the scheduler is free to trade the activation
// loads' overlap for occupancy, and at MT = 4 that trade cost 40%.
constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u;
}
template <uint32_t MT, uint32_t FKB, bool I8 = false>
__global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel(
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
float* __restrict__ C, uint32_t c_ld,
uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) {
@@ -629,6 +716,7 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel(
constexpr uint32_t kRows = kDenseWaves * 16u; /* weight rows a workgroup covers */
constexpr uint32_t kPitch = lds_pitch<kFK>(); /* BYTES a staged weight row */
constexpr uint32_t kWUnits = kRows * (kFK / 16u); /* 16-byte staging units, weight */
constexpr bool kPre = MT <= 3u; /* activation a K step ahead, below */
__shared__ uint8_t s_w[kRows * kPitch];
@@ -650,8 +738,37 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel(
for (uint32_t t = 0; t < MT; ++t) acc[t] = (f8v)(0.0f);
for (uint32_t kt = 0; kt < cols; kt += kFK) {
/* Before the store, because the previous tile's fragment reads are still in flight. */
__syncthreads();
/* THE ACTIVATION FRAGMENTS ARE LOADED ONE K STEP AHEAD at MT <= 3 (kPre): each step
* takes the fragments the step before it loaded and issues the next step's, so their
* round trip runs under a step's WMMAs; the tile's first step is issued here, while the
* tile stages. Loaded in the step that uses them, LLVM 24 waits for them right after
* issuing them, every step -- LLVM 22's schedule had moved the loads a step early
* itself. Against LLVM 22's build: M = 4 from +0.44% to level, M = 32 to -1.4%. At
* MT = 4 the held fragments take the tile to 238 VGPRs and it runs 3.4% slower, so it
* loads in place there. The last step reloads its own fragments rather than reading
* past the tile. */
[[maybe_unused]] lm_s8v an[kPre ? MT : 1];
auto aload = [&](uint32_t kf) {
#pragma unroll
for (uint32_t t = 0; t < MT; ++t) {
const uint32_t m = t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u);
an[t] = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u);
}
};
if constexpr (kPre) aload(0u);
/* THE TILE'S BLOCK SCALES ARE READ HERE, ahead of the staging barrier, so they land
* while the tile stages and computes. Read where they are used, after a block's
* WMMAs, each is a global round trip the wave waits out with nothing else in flight,
* and a compiler is free to put the load there: LLVM 24 does for the second block of
* an FKB = 2 tile. Read here, M = 4 to 64 run 0.2 to 0.6% faster. */
uint16_t sraw[FKB];
#pragma unroll
for (uint32_t sb = 0; sb < FKB; ++sb) sraw[sb] = scl[(kt + sb * kBlock) / kBlock];
/* Before the store, because the previous tile's fragment reads are still in flight.
* Both barriers order LDS only: no thread reads global memory another one writes, and
* __syncthreads() is a fence over every address space, which on gfx12 waits for every
* load in flight -- the scale read above and the prefetched fragments with it. */
lds_barrier();
/* HOW MANY STAGING LOADS ARE IN FLIGHT, and it is a REGISTER decision, not a memory one. A round
* is kFK/32 units a thread -- eight at FKB = 2 -- and unrolling it whole holds eight uint4 results
* live across the stores, 32 VGPRs on top of MT accumulators and MT partials. At MT >= 3 unrolling
@@ -664,7 +781,7 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel(
const uint8_t* src = W + (size_t)((g < rows) ? g : (rows - 1u)) * w_ld + kt + off;
*(uint4*)(s_w + (size_t)r * kPitch + off) = *(const uint4*)src;
}
__syncthreads();
lds_barrier();
/* One scale block at a time INSIDE the staged tile, so the partial that the block
* scale multiplies is exactly the one a one-block round forms. FK is a staging width and
@@ -680,19 +797,33 @@ __global__ __launch_bounds__(kDenseThreads) void lm_wmma_kernel(
#pragma unroll MT >= 4 ? 2 : 4
for (uint32_t ks = 0; ks < kBlock; ks += 16u) {
const uint32_t kf = sb * kBlock + ks; /* K inside the staged tile */
[[maybe_unused]] lm_s8v ac[kPre ? MT : 1];
if constexpr (kPre) {
#pragma unroll
for (uint32_t t = 0; t < MT; ++t) ac[t] = an[t];
aload(kf + 16u < kFK ? kf + 16u : kf);
}
const i2v raw = frag<kFK>(s_w, wv * 16u, kf, lane);
const lm_s8v bf = e4m3x8_to_bf16<I8>((uint32_t)raw[0], (uint32_t)raw[1]);
const lm_s8v bf =
e4m3x8_to_bf16<I8>((uint32_t)raw[0], (uint32_t)raw[1]);
/* THE ACTIVATION LOAD IS UNCONDITIONAL: a padding row reads the last real row again and a select
* zeroes it. Guarding the load with `m < m_real` puts each one in its own branch with its WMMA
* right behind it, and the compiler is then free to wait for every load before issuing the next
* -- MT round trips a K step where one would do. LLVM 24 does exactly that, and it cost M = 64
* 40%. The clamped row is always in bounds and already in cache, so the extra loads are free. */
#pragma unroll
for (uint32_t t = 0; t < MT; ++t) {
const uint32_t m = t * 16u + c;
const lm_s8v af =
(m < m_real) ? *(const lm_s8v*)(A + (size_t)m * a_ld + kt + kf + h * 8u)
: (lm_s8v)(short)0;
[[maybe_unused]] const uint32_t mr = (m < m_real) ? m : (m_real - 1u);
lm_s8v af;
if constexpr (kPre) af = ac[t];
else af = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u);
if (m >= m_real) af = (lm_s8v)(short)0;
part[t] =
__builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(af, bf, part[t]);
}
}
const float sc = bscale(scl[(kt + sb * kBlock) / kBlock]);
const float sc = bscale(sraw[sb]);
#pragma unroll
for (uint32_t t = 0; t < MT; ++t)
#pragma unroll
+104 -36
View File
@@ -53,6 +53,7 @@
#include <cstdlib>
#include <map>
#include <mutex>
#include <type_traits>
namespace {
@@ -334,9 +335,34 @@ constexpr bool kNarrowWeightNT = false;
* per 128x128 tile. Only the fold reads the difference: one weight scale per accumulator row on
* the narrow path, one per lane's column on the prefill tile. The fp8 instantiations are
* unaffected. */
/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget every shape here was
* tuned at. The narrow tile's NT accumulators and its K-step unroll are sized against it, and a
* compiler left to choose moves it either way -- LLVM 24 spends 25 to 55 more VGPRs on NT 3 and 4
* at FK 256 and drops a wave or two, which cost the 64-row verify step 15%. One and two waves a
* block are held by LDS, not registers, and carry the LDS-bound count. */
constexpr uint32_t f8_waves(bool full, bool aw, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) {
if (!aw) return 6u;
if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u;
if (mw == 2u) return nt == 1u ? 12u : nt == 2u ? 8u : nt == 3u ? 5u : 4u;
if (!i8) {
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u
: (full && mw >= 8u) ? 10u : 9u;
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? 9u : mw == 4u ? 7u : 8u;
}
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u)
: full ? 7u : 9u;
if (nt == 1u) return 12u;
if (nt == 2u) return full ? 9u : mw == 4u ? 9u : 10u;
if (nt == 3u) return full ? (mw == 16u ? 8u : 7u) : (mw == 4u ? 8u : 9u);
return full ? (mw == 4u ? 5u : 6u) : (mw == 4u ? 7u : 8u);
}
template <bool Full, bool AW, uint32_t NT, uint32_t MT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false>
__global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel(
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, AW, NT, MW, FK, I8))
void gemm_fp8a8_kernel(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr,
@@ -579,6 +605,25 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel(
}
}
/* THE FOLD'S ACTIVATION SCALES, A TILE AHEAD (fp8 prefill tile): eight a lane, read at the
* top of the staged tile that ends in a fold so its WMMA cover them. Loaded where the fold
* runs, LLVM 24 issues them there and waits for each one in turn. At FK <= kBlock the fold
* fires only at a tile's last step, so the tile is known here. */
constexpr bool kAsAhead = !AW && !I8 && FK <= kBlock;
[[maybe_unused]] float asn[kAsAhead ? MT : 1][8];
if constexpr (kAsAhead) {
if ((c0 + FK) % kBlock == 0 || c0 + FK >= kend) {
const uint32_t kb = (c0 + FK - 1) / kBlock;
#pragma unroll
for (uint32_t i = 0; i < MT; ++i)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t);
asn[i][t] = (Full || r < rows) ? ((const float*)Sa)[(size_t)r * sa_ld + kb]
: 0.0f;
}
}
}
#pragma unroll
for (uint32_t ks = 0; ks < FK; ks += kK) {
i2v af[MT], bf[NT];
@@ -724,9 +769,12 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel(
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
const uint32_t r = m0 + wm + i * 16 + acc_row(lane, t);
as[i][t] = (Full || r < rows)
? ws * ((const float*)Sa)[(size_t)r * sa_ld + kb]
: 0.0f;
if constexpr (kAsAhead)
as[i][t] = (Full || r < rows) ? ws * asn[i][t] : 0.0f;
else
as[i][t] = (Full || r < rows)
? ws * ((const float*)Sa)[(size_t)r * sa_ld + kb]
: 0.0f;
}
#pragma unroll
for (uint32_t i = 0; i < MT; ++i)
@@ -833,11 +881,11 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel(
*(uint2*)(Q + (size_t)tok * q_ld + col0) =
make_uint2((uint32_t)pk[0], (uint32_t)pk[1]);
if (Yb) {
__attribute__((aligned(16))) uint16_t hy[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) hy[t] = f32_to_bf16(v[j][t]);
/* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written through
* a uint16_t[8], LLVM 24 assembles the pairs from register halves. */
uint16_t* const yr = Yb + (size_t)tok * y_ld + col0;
*(uint4*)yr = *(const uint4*)hy;
*(uint4*)yr = make_uint4(bf16x2_rne(v[j][0], v[j][1]), bf16x2_rne(v[j][2], v[j][3]),
bf16x2_rne(v[j][4], v[j][5]), bf16x2_rne(v[j][6], v[j][7]));
}
}
@@ -873,40 +921,60 @@ __global__ __launch_bounds__(MW * kWave) void gemm_fp8a8_kernel(
* are exactly when `rows` is a multiple of 8: `r` is already one (m0, wm, i*16 and
* `(lane>>4)*8` all are), so `col * rows + r` is too. */
const bool vec8 = AW && (rows & 7u) == 0u;
/* THE SPLIT-K AND VEC8 TESTS ARE TAKEN ONCE, outside the store loop. Inside it, gfx12's
* compiler keeps a scalar compare and branch on each at every one of the tile's stores -- 64
* of each at NT 8 -- where LLVM 22 unswitched the loop; and with the per-element fallback in
* the same body it rounds both paths' values to 16-bit halves once, so the vec8 words are
* assembled from register halves instead of one byte permute a pair. The same stores either
* way. */
auto store = [&](auto split, auto v8) {
constexpr bool CK = decltype(split)::value;
constexpr bool V8 = decltype(v8)::value;
#pragma unroll
for (uint32_t i = 0; i < MT; ++i)
for (uint32_t i = 0; i < MT; ++i)
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t col = n0 + wn + j * 16 + c;
if (!Full && col >= nb) continue;
const uint32_t rb = m0 + wm + i * 16;
const uint32_t r0 = rb + acc_row(lane, 0);
if (vec8 && (Full || r0 + 8u <= rows)) {
const size_t o = (size_t)col * rows + r0;
if (ck) {
__attribute__((aligned(16))) float pv[8];
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t col = n0 + wn + j * 16 + c;
if (!Full && col >= nb) continue;
const uint32_t rb = m0 + wm + i * 16;
const uint32_t r0 = rb + acc_row(lane, 0);
if (V8 && (Full || r0 + 8u <= rows)) {
const size_t o = (size_t)col * rows + r0;
if constexpr (CK) {
__attribute__((aligned(16))) float pv[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) pv[t] = out[i][j][t];
*(uint4*)(part + o) = *(const uint4*)pv;
*(uint4*)(part + o + 4) = *(const uint4*)(pv + 4);
} else {
__attribute__((aligned(16))) uint16_t hy[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) hy[t] = f32_to_bf16(out[i][j][t]);
*(uint4*)(c16 + o) = *(const uint4*)hy;
for (uint32_t t = 0; t < 8; ++t) pv[t] = out[i][j][t];
*(uint4*)(part + o) = *(const uint4*)pv;
*(uint4*)(part + o + 4) = *(const uint4*)(pv + 4);
} else {
/* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits): written
* through a uint16_t[8], LLVM 24 assembles the pairs from register halves
* where LLVM 22 used one byte permute a pair. */
const f8v& ov = out[i][j];
*(uint4*)(c16 + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]),
bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7]));
}
continue;
}
continue;
}
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
const uint32_t r = rb + acc_row(lane, t);
if (!Full && r >= rows) continue;
// AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. See the AW comment.
const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col;
if (ck) part[o] = out[i][j][t];
else c16[o] = f32_to_bf16(out[i][j][t]);
for (uint32_t t = 0; t < 8; ++t) {
const uint32_t r = rb + acc_row(lane, t);
if (!Full && r >= rows) continue;
// AW: A held the weight, so [r][col] is [N][M] and C is [M][N]. See the AW
// comment.
const size_t o = AW ? (size_t)col * rows + r : (size_t)r * nb + col;
if constexpr (CK) part[o] = out[i][j][t];
else c16[o] = f32_to_bf16(out[i][j][t]);
}
}
}
};
if (vec8) {
if (ck) store(std::true_type{}, std::true_type{});
else store(std::false_type{}, std::true_type{});
} else {
if (ck) store(std::true_type{}, std::false_type{});
else store(std::false_type{}, std::false_type{});
}
// ---- THE SPLIT'S FINISHER, WHICH IS WHY THERE IS USUALLY NO SECOND LAUNCH ------------------
//
+27 -5
View File
@@ -145,11 +145,17 @@ static __device__ __forceinline__ void mxd_epilogue(
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;
// rounded as (__hip_bfloat16) rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#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;
v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i];
mxd_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(mxd_u4*)(C + (size_t)m * N + nb) = o;
}
}
}
@@ -194,8 +200,23 @@ static __device__ __forceinline__ void mxd_epilogue(
}
}
/* THE WAVES A SIMD EACH TILE SHAPE RUNS AT (R4D_WAVES): the register budget the decode tile was
* tuned at, by K block, M fragments and activation-scale form, so a compiler release cannot move
* it -- LLVM 24 adds two VGPRs to the DBK 64, three-fragment form and drops it from sixteen waves to
* twelve. Where LLVM 22 itself ran out of registers (DBK 128 at seven and eight fragments without
* block activation scales, 256 VGPRs and a spill) the budget is the one the tile reaches without
* spilling. */
constexpr int mxd_waves(int dbk, int dtm, bool ablk) {
if (dbk == 64)
return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10)
: dtm == 7 ? 9 : (ablk ? 8 : 9);
return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6)
: 6;
}
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kernel(
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(mxd_waves(DBK, DTM, ABLK))
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,
@@ -314,7 +335,8 @@ __global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kern
// 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(
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
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,
+9 -3
View File
@@ -300,13 +300,19 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
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;
// rounded as (__hip_bfloat16) rounds, packed in whole registers (see bf16x2_rne_nan)
float v[8];
#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]);
v[e] = acc[i][j][e] * rf * sc[i];
}
*(mxt_u4*)(C + (size_t)m * N + nb) = o.v;
mxt_u4 o;
o.x = bf16x2_rne_nan(v[0], v[1]);
o.y = bf16x2_rne_nan(v[2], v[3]);
o.z = bf16x2_rne_nan(v[4], v[5]);
o.w = bf16x2_rne_nan(v[6], v[7]);
*(mxt_u4*)(C + (size_t)m * N + nb) = o;
}
}
}
+136 -93
View File
@@ -119,6 +119,28 @@ __device__ __forceinline__ float sigmoidf_(float v) { return 1.0f / (1.0f + __ex
__device__ __forceinline__ float siluf_(float v) { return v * sigmoidf_(v); }
__device__ __forceinline__ float nbf(float v) { return bf2f(f2bf(v)); }
/* BF16 IN WHOLE REGISTERS. gfx12's compiler holds a 16-bit value in a register HALF: eight f2bf
* results written through a union of shorts are eight half moves before the pack, and a short
* loaded on its own is a d16 load that leaves the register's other half live, so it waits on that
* register's last write. These keep every value 32 bits wide -- pairs packed with f2bf2, whose
* rounding is f2bf's, a pair word's halves read with a shift and a mask, a lone bf16 loaded
* zero-extended -- and give the same bits. */
__device__ __forceinline__ uint4 f2bf8(const float (&f)[8]) {
return make_uint4(f2bf2(f[0], f[1]), f2bf2(f[2], f[3]), f2bf2(f[4], f[5]), f2bf2(f[6], f[7]));
}
__device__ __forceinline__ void bf8_f(uint4 v, float (&f)[8]) {
f[0] = bf16w_lo(v.x); f[1] = bf16w_hi(v.x); f[2] = bf16w_lo(v.y); f[3] = bf16w_hi(v.y);
f[4] = bf16w_lo(v.z); f[5] = bf16w_hi(v.z); f[6] = bf16w_lo(v.w); f[7] = bf16w_hi(v.w);
}
__device__ __forceinline__ void bf8_f(r4d_u32x4 v, float (&f)[8]) {
f[0] = bf16w_lo(v.x); f[1] = bf16w_hi(v.x); f[2] = bf16w_lo(v.y); f[3] = bf16w_hi(v.y);
f[4] = bf16w_lo(v.z); f[5] = bf16w_hi(v.z); f[6] = bf16w_lo(v.w); f[7] = bf16w_hi(v.w);
}
/* Read through a GLOBAL pointer: through a generic one the load is still flat_load_d16_b16. */
typedef __attribute__((address_space(1))) const unsigned short* hc_gu16;
__device__ __forceinline__ uint32_t bfw(const unsigned short* p) { return *(hc_gu16)p; }
__device__ __forceinline__ float bfw_f(uint32_t w) { return __uint_as_float(w << 16); }
/* ---- THE E4M3 MIXING MATRICES (r4d_hc_fp8.h) ------------------------------------------------
*
* Every kernel below that reads mix_down or mix_up has an F8 form, selected by the stored dtype:
@@ -152,10 +174,9 @@ __device__ __forceinline__ uint4 e4m3x8_bf16(const unsigned char* __restrict__ c
const uint2 c = *(const uint2*)codes;
float f[8];
e4m3x8(c.x, c.y, f);
union { uint4 v; unsigned short s[8]; } o;
#pragma unroll
for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * sc);
return o.v;
for (int e = 0; e < 8; ++e) f[e] *= sc;
return f2bf8(f);
}
/* A WAVE'S DOT OF THE NATURAL-ORDER LDS VECTOR WITH ONE E4M3 ROW OF mix_down. A lane takes
@@ -644,22 +665,22 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short
constexpr int kSsIter = 5;
long i = tid;
for (; i + (long)(kSsIter - 1) * kThreads < n; i += (long)kSsIter * kThreads) {
unsigned short ev[kSsIter], hv[kSsIter][kHcMax];
uint32_t ev[kSsIter], hv[kSsIter][kHcMax];
#pragma unroll
for (int q = 0; q < kSsIter; ++q) {
const long iq = i + (long)q * kThreads;
ev[q] = ep[iq];
ev[q] = bfw(ep + iq);
#pragma unroll
for (int c = 0; c < kHcMax; ++c)
if (c < hc) hv[q][c] = hp[(long)c * n + iq];
if (c < hc) hv[q][c] = bfw(hp + (long)c * n + iq);
}
#pragma unroll
for (int q = 0; q < kSsIter; ++q) {
const float evf = bf2f(ev[q]);
const float evf = bfw_f(ev[q]);
pe += evf * evf;
#pragma unroll
for (int c = 0; c < kHcMax; ++c)
if (c < hc) { const float v = bf2f(hv[q][c]); part[c] += v * v; }
if (c < hc) { const float v = bfw_f(hv[q][c]); part[c] += v * v; }
}
}
for (; i < n; i += kThreads) {
@@ -723,13 +744,13 @@ void mtp_enter_kernel(const unsigned short* __restrict__ h, const unsigned short
const long q = base + (long)tid * 8;
if (q >= n) break;
const long ch = q & ~(kPer - 1);
unsigned short out[8];
float out[8];
#pragma unroll
for (int t = 0; t < 8; ++t) {
const long li = ch + lane8 + (long)t * kWave;
out[t] = f2bf(bf2f(src[li]) * sc * (wv[li] + wadd));
out[t] = bfw_f(bfw(src + li)) * sc * (wv[li] + wadd);
}
*(uint4*)(dst + q) = *(const uint4*)out;
*(uint4*)(dst + q) = f2bf8(out);
}
}
} else {
@@ -785,8 +806,14 @@ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)size
* columns share one pass over `h` and one grouped reduction. It is held TRANSPOSED inside each
* 256-element chunk; wave_dot_swz above is the whole argument for that, and it is the difference
* between eight conflicted 16-bit LDS reads a chunk and one ds_load_b128. */
/* THE WAVES A SIMD: nine for the E4M3 dot, the budget it was tuned at. Left to choose, LLVM 24
* builds it at 120 VGPRs for twelve waves, which costs 11% at four rows and 20% at seven with the
* weight read cold -- the shapes a speculative decode step runs. The bf16 form keeps the full
* range, which is what it is built at without the attribute; pinning it to sixteen changes its
* code. */
template <bool F8>
__global__ __launch_bounds__(kThreads)
__attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16)))
void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w,
const void* __restrict__ downv, long dld,
const unsigned short* __restrict__ injw,
@@ -882,11 +909,11 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr
float acc = 0.0f;
long i = tid;
for (; i + (long)(kPreSs - 1) * kThreads < n; i += (long)kPreSs * kThreads) {
unsigned short hv[kPreSs];
uint32_t hv[kPreSs];
#pragma unroll
for (int p = 0; p < kPreSs; ++p) hv[p] = hp[cb + i + (long)p * kThreads];
for (int p = 0; p < kPreSs; ++p) hv[p] = bfw(hp + cb + i + (long)p * kThreads);
#pragma unroll
for (int p = 0; p < kPreSs; ++p) { const float v = bf2f(hv[p]); acc += v * v; }
for (int p = 0; p < kPreSs; ++p) { const float v = bfw_f(hv[p]); acc += v * v; }
}
for (; i < n; i += kThreads) { const float v = bf2f(hp[cb + i]); acc += v * v; }
acc = wave_sum(acc);
@@ -921,28 +948,28 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr
const long q = base + (long)tid * 8;
if (q >= n) break;
const long ch = cb + (q & ~(kPer - 1));
unsigned short out[8];
float out[8];
#pragma unroll
for (int t = 0; t < 8; ++t) {
const long li = ch + lane + (long)t * kWave;
out[t] = f2bf(bf2f(hp[li]) * sc * (w[li] + wadd));
out[t] = bfw_f(bfw(hp + li)) * sc * (w[li] + wadd);
}
*(uint4*)(sN + cb + q) = *(const uint4*)out;
*(uint4*)(sN + cb + q) = f2bf8(out);
}
} else {
constexpr int kPreScale = 8;
long i = tid;
for (; i + (long)(kPreScale - 1) * kThreads < n; i += (long)kPreScale * kThreads) {
float wv[kPreScale];
unsigned short hv[kPreScale];
uint32_t hv[kPreScale];
#pragma unroll
for (int p = 0; p < kPreScale; ++p) {
wv[p] = w[cb + i + (long)p * kThreads];
hv[p] = hp[cb + i + (long)p * kThreads];
hv[p] = bfw(hp + cb + i + (long)p * kThreads);
}
#pragma unroll
for (int p = 0; p < kPreScale; ++p)
sN[cb + i + (long)p * kThreads] = f2bf(bf2f(hv[p]) * sc * (wv[p] + wadd));
sN[cb + i + (long)p * kThreads] = f2bf(bfw_f(hv[p]) * sc * (wv[p] + wadd));
}
for (; i < n; i += kThreads)
sN[cb + i] = f2bf(bf2f(hp[cb + i]) * sc * (w[cb + i] + wadd));
@@ -1618,11 +1645,11 @@ void hc_down_tiled_kernel(const unsigned short* __restrict__ h, const float* __r
long r = r0 + rr; if (r >= rows) r = rows - 1;
const float sc = scalein[r * kHcMax + c];
const float* wp = w + k0 + k8;
union { uint4 v; unsigned short s[8]; } in, out;
in.v = *(const uint4*)(h + r * hrow + k0 + k8);
float f8v[8];
bf8_f(*(const uint4*)(h + r * hrow + k0 + k8), f8v);
#pragma unroll
for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * sc * (wp[e] + wadd));
*(uint4*)(sA + rr * kTAP + k8) = out.v;
for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * sc * (wp[e] + wadd);
*(uint4*)(sA + rr * kTAP + k8) = f2bf8(f8v);
}
for (int idx = tid; idx < NT * (kTKT / 8); idx += kThreads) {
const int tt = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8;
@@ -1786,15 +1813,18 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re
arow[i] = r < rows ? r : rows - 1;
}
uint4 pa[kAV];
/* The bf16-weight form stages through a native vector: in uint4 LLVM 24 keeps these arrays in
* scratch. The fp8 form is promoted either way and keeps uint4, at its tuned register count. */
using Stg = std::conditional_t<F8, uint4, r4d_u32x4>;
Stg pa[kAV];
float psc[kAV], pw[8];
uint4 pb[kBV];
Stg pb[kBV];
float pbs[kBV];
auto fetch = [&](long k0) {
const int c = (int)(k0 / n);
#pragma unroll
for (int i = 0; i < kAV; ++i) {
pa[i] = *(const uint4*)(h + arow[i] * hrow + k0 + k8a);
pa[i] = *(const Stg*)(h + arow[i] * hrow + k0 + k8a);
psc[i] = scalein[arow[i] * kHcMax + c];
}
#pragma unroll
@@ -1808,39 +1838,40 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re
if (F8 && col < lr) {
const unsigned char* row = (const unsigned char*)downv + col * dld;
const uint2 cc = *(const uint2*)(row + k);
pb[b] = make_uint4(cc.x, cc.y, 0u, 0u);
pb[b] = Stg{cc.x, cc.y, 0u, 0u};
pbs[b] = ((const float*)(row + HN))[k / r4d_hc8::kDownGroup];
} else {
const unsigned short* src = (col < lr) ? (const unsigned short*)downv + col * HN
: injw + (col - lr) * HN;
pb[b] = *(const uint4*)(src + k);
pb[b] = *(const Stg*)(src + k);
}
}
};
auto stage = [&]() {
#pragma unroll
for (int i = 0; i < kAV; ++i) {
union { uint4 v; unsigned short s[8]; } in, out;
in.v = pa[i];
float f8v[8];
bf8_f(pa[i], f8v);
#pragma unroll
for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * psc[i] * (pw[e] + wadd));
*(uint4*)(sA + (ar + i * kRS) * kTAP + k8a) = out.v;
for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * psc[i] * (pw[e] + wadd);
*(uint4*)(sA + (ar + i * kRS) * kTAP + k8a) = f2bf8(f8v);
}
#pragma unroll
for (int b = 0; b < kBV; ++b) {
const int idx = tid + b * kThreads, tt = idx / kKV, k8 = (idx % kKV) * 8;
if (idx >= NT * kKV || tt >= nlive * 16) continue;
long col = c0 + tt; if (col >= ncol) col = ncol - 1;
uint4 v = pb[b];
if (F8 && col < lr) {
float f[8];
e4m3x8(v.x, v.y, f);
union { uint4 v; unsigned short s[8]; } o;
Stg v = pb[b];
if constexpr (F8) {
if (col < lr) {
float f[8];
e4m3x8(v.x, v.y, f);
#pragma unroll
for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * pbs[b]);
v = o.v;
for (int e = 0; e < 8; ++e) f[e] = f[e] * pbs[b];
v = f2bf8(f);
}
}
*(uint4*)(sB + tt * kTAP + k8) = v;
*(Stg*)(sB + tt * kTAP + k8) = v;
}
};
@@ -2303,10 +2334,9 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld,
if constexpr (F8) {
float f[8];
e4m3x8(v.x, v.y, f);
union { uint4 v; unsigned short s[8]; } o;
#pragma unroll
for (int e = 0; e < 8; ++e) o.s[e] = f2bf(f[e] * pbs[i]);
v = k0 + k8a + 8 <= lr ? o.v : make_uint4(0u, 0u, 0u, 0u);
for (int e = 0; e < 8; ++e) f[e] = f[e] * pbs[i];
v = k0 + k8a + 8 <= lr ? f2bf8(f) : make_uint4(0u, 0u, 0u, 0u);
}
*(uint4*)(sB + (tr + i * kRS) * kTAP + k8a) = v;
}
@@ -2341,11 +2371,11 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld,
const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8;
if (r0 + rl >= rows) continue;
const long j = (long)c * n + i0 + i8;
union { uint4 v; unsigned short s[8]; } in, out;
in.v = pn[i];
float f8v[8];
bf8_f(pn[i], f8v);
#pragma unroll
for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * pns[i] * (w[j + e] + wadd));
*(uint4*)(sN + (rl * HC + c) * CH + i8) = out.v;
for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * pns[i] * (w[j + e] + wadd);
*(uint4*)(sN + (rl * HC + c) * CH + i8) = f2bf8(f8v);
}
__syncthreads();
@@ -2629,10 +2659,9 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_
const float sc = ((const float*)(row + HN))[k / r4d_hc8::kDownGroup];
float fv[8];
e4m3x8(*(const uint32_t*)(row + k), *(const uint32_t*)(row + k + 8), fv);
union { uint4 v; unsigned short s[8]; } u;
#pragma unroll
for (int e = 0; e < 8; ++e) u.s[e] = f2bf(fv[e] * sc);
o = u.v;
for (int e = 0; e < 8; ++e) fv[e] = fv[e] * sc;
o = f2bf8(fv);
} else {
const unsigned short* src = (col < lr) ? (const unsigned short*)downv + col * HN
: injw + (col - lr) * HN;
@@ -2711,11 +2740,11 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res
auto stageA = [&](unsigned short* dst) {
#pragma unroll
for (int i = 0; i < kAV; ++i) {
union { uint4 v; unsigned short s[8]; } in, out;
in.v = pa[i];
float f8v[8];
bf8_f(pa[i], f8v);
#pragma unroll
for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * psc[i] * (pw[e] + wadd));
*(uint4*)(dst + (ar + i * kRS) * kTAP + k8a) = out.v;
for (int e = 0; e < 8; ++e) f8v[e] = f8v[e] * psc[i] * (pw[e] + wadd);
*(uint4*)(dst + (ar + i * kRS) * kTAP + k8a) = f2bf8(f8v);
}
};
@@ -2883,18 +2912,18 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned
for (int k = 0; k < kSsRows; ++k) acc[k] = 0.0f;
long j = lane;
for (; j + (long)(kSsPre - 1) * kWave < len; j += (long)kSsPre * kWave) {
unsigned short v[kSsRows][kSsPre];
uint32_t v[kSsRows][kSsPre];
#pragma unroll
for (int k = 0; k < kSsRows; ++k)
if (k < nr) {
#pragma unroll
for (int q = 0; q < kSsPre; ++q) v[k][q] = p[k][j + (long)q * kWave];
for (int q = 0; q < kSsPre; ++q) v[k][q] = bfw(p[k] + j + (long)q * kWave);
}
#pragma unroll
for (int k = 0; k < kSsRows; ++k)
if (k < nr) {
#pragma unroll
for (int q = 0; q < kSsPre; ++q) { const float f = bf2f(v[k][q]); acc[k] += f * f; }
for (int q = 0; q < kSsPre; ++q) { const float f = bfw_f(v[k][q]); acc[k] += f * f; }
}
}
for (; j < len; j += kWave)
@@ -2976,28 +3005,40 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned
if constexpr (F8) {
float f[8];
e4m3x8(o.c.x, o.c.y, f);
union { uint4 v; unsigned short s[8]; } u;
#pragma unroll
for (int q = 0; q < 8; ++q) u.s[q] = f2bf(f[q] * o.s);
return u.v;
for (int q = 0; q < 8; ++q) f[q] = f[q] * o.s;
return f2bf8(f);
} else {
return o.v;
}
};
/* AN A ITEM'S ROWS ARE THE SAME EVERY K STEP: its token and sub-stream are a 64-bit division
* by `hc` and its remainder, worked out once here as element offsets. Left in the step, gfx12's
* compiler expands the division again every slice -- twenty times over at the 64-row tile and
* fifty at the 128-row one -- where LLVM 22 moved it out of the loop. The same addresses. */
uint32_t aoh[kAI], aoe[kAI], aow[kAI], ak8[kAI];
#pragma unroll
for (int a = 0; a < kAI; ++a) {
const int idx = tid + a * kThreads;
const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8;
const long Ri = r0 + rr;
const long rt = (Ri < R) ? Ri / hc : rows - 1, kt = (Ri < R) ? Ri % hc : 0;
aoh[a] = (uint32_t)(rt * hrow + kt * n + k8);
aoe[a] = (uint32_t)(rt * erow + k8);
aow[a] = (uint32_t)(kt * n + k8);
ak8[a] = (uint32_t)k8;
}
auto issue = [&](long k0) {
#pragma unroll
for (int a = 0; a < kAI; ++a) {
const int idx = tid + a * kThreads;
if (idx >= RT * (kTKT / 8)) break;
const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8;
const long Ri = r0 + rr;
const long rt = (Ri < R) ? Ri / hc : rows - 1, kt = (Ri < R) ? Ri % hc : 0;
ap[a].h = *(const uint4*)(h + rt * hrow + kt * n + k0 + k8);
ap[a].e = *(const uint4*)(e + rt * erow + k0 + k8);
ap[a].wh0 = *(const float4*)(wh + kt * n + k0 + k8);
ap[a].wh1 = *(const float4*)(wh + kt * n + k0 + k8 + 4);
ap[a].we0 = *(const float4*)(we + k0 + k8);
ap[a].we1 = *(const float4*)(we + k0 + k8 + 4);
ap[a].h = *(const uint4*)(h + aoh[a] + k0);
ap[a].e = *(const uint4*)(e + aoe[a] + k0);
ap[a].wh0 = *(const float4*)(wh + aow[a] + k0);
ap[a].wh1 = *(const float4*)(wh + aow[a] + k0 + 4);
ap[a].we0 = *(const float4*)(we + ak8[a] + k0);
ap[a].we1 = *(const float4*)(we + ak8[a] + k0 + 4);
}
#pragma unroll
for (int b = 0; b < kBI; ++b) {
@@ -3019,19 +3060,19 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned
if (idx >= RT * (kTKT / 8)) break;
const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8;
const float sc = s_rs[rr], se = s_re[rr];
union { uint4 v; unsigned short s[8]; } in, out;
const float wp[8] = { ap[a].wh0.x, ap[a].wh0.y, ap[a].wh0.z, ap[a].wh0.w,
ap[a].wh1.x, ap[a].wh1.y, ap[a].wh1.z, ap[a].wh1.w };
const float wq[8] = { ap[a].we0.x, ap[a].we0.y, ap[a].we0.z, ap[a].we0.w,
ap[a].we1.x, ap[a].we1.y, ap[a].we1.z, ap[a].we1.w };
in.v = ap[a].h;
float f8v[8];
bf8_f(ap[a].h, f8v);
#pragma unroll
for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * sc * (wp[q] + wadd));
*(uint4*)(sAh + rr * kTAP + k8) = out.v;
in.v = ap[a].e;
for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * sc * (wp[q] + wadd);
*(uint4*)(sAh + rr * kTAP + k8) = f2bf8(f8v);
bf8_f(ap[a].e, f8v);
#pragma unroll
for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * se * (wq[q] + wadd));
*(uint4*)(sAe + rr * kTAP + k8) = out.v;
for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * se * (wq[q] + wadd);
*(uint4*)(sAe + rr * kTAP + k8) = f2bf8(f8v);
}
#pragma unroll
for (int b = 0; b < kBI; ++b) {
@@ -3068,11 +3109,14 @@ void mtp_enter_tiled_kernel(const unsigned short* __restrict__ h, const unsigned
if (nt >= NT16) continue;
const long j = j0 + nt * 16 + nn;
if (j >= n) continue;
/* The eight rows are consecutive output rows: one division for the first, and the
* (token, sub-stream) pair stepped from there rather than divided out again a row. */
const long Rq = r0 + mt * 16 + e0;
long tq = Rq / hc, kq = Rq % hc;
#pragma unroll
for (int q = 0; q < 8; ++q) {
const long Ri = r0 + mt * 16 + e0 + q;
if (Ri >= R) continue;
x[(Ri / hc) * xrow + (Ri % hc) * n + j] = f2bf(acc[im][in][q]);
if (Rq + q < R) x[tq * xrow + kq * n + j] = f2bf(acc[im][in][q]);
if (++kq == hc) { kq = 0; ++tq; }
}
}
}
@@ -3126,11 +3170,11 @@ void mtp_prefill_scale_kernel(const unsigned short* __restrict__ h,
float acc = 0.0f;
long j = lane;
for (; j + (long)(kPre - 1) * kWave < len; j += (long)kPre * kWave) {
unsigned short v[kPre];
uint32_t v[kPre];
#pragma unroll
for (int q = 0; q < kPre; ++q) v[q] = p[j + (long)q * kWave];
for (int q = 0; q < kPre; ++q) v[q] = bfw(p + j + (long)q * kWave);
#pragma unroll
for (int q = 0; q < kPre; ++q) { const float f = bf2f(v[q]); acc += f * f; }
for (int q = 0; q < kPre; ++q) { const float f = bfw_f(v[q]); acc += f * f; }
}
for (; j < len; j += kWave) { const float f = bf2f(p[j]); acc += f * f; }
acc = wave_sum(acc);
@@ -3212,7 +3256,7 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow,
float4 rg0[AL], rg1[AL];
uint2 rc[WL];
float rsc[WL];
uint4 rw[WL];
r4d_u32x4 rw[WL]; /* registers; uint4 would sit in scratch */
auto fetch = [&](long k0) {
#pragma unroll
for (int i = 0; i < AL; ++i) {
@@ -3227,7 +3271,7 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow,
rc[i] = *(const uint2*)(wrow[i] + k);
rsc[i] = ((const float*)(wrow[i] + n))[k / r4d_hc8::kDownGroup];
} else {
rw[i] = *(const uint4*)(wsrc[i] + k0);
rw[i] = *(const r4d_u32x4*)(wsrc[i] + k0);
}
}
};
@@ -3238,25 +3282,24 @@ void mtp_prefill_gemm_kernel(const unsigned short* __restrict__ src, long srow,
__syncthreads(); /* the previous tile's fragments are read */
#pragma unroll
for (int i = 0; i < AL; ++i) {
union { uint4 v; unsigned short s[8]; } in, out;
in.v = ra[i];
float f8v[8];
bf8_f(ra[i], f8v);
const float g[8] = { rg0[i].x, rg0[i].y, rg0[i].z, rg0[i].w,
rg1[i].x, rg1[i].y, rg1[i].z, rg1[i].w };
#pragma unroll
for (int q = 0; q < 8; ++q) out.s[q] = f2bf(bf2f(in.s[q]) * asc[i] * (g[q] + wadd));
*(uint4*)adst[i] = out.v;
for (int q = 0; q < 8; ++q) f8v[q] = f8v[q] * asc[i] * (g[q] + wadd);
*(uint4*)adst[i] = f2bf8(f8v);
}
#pragma unroll
for (int i = 0; i < WL; ++i) {
if constexpr (F8) {
float f[8];
e4m3x8(rc[i].x, rc[i].y, f);
union { uint4 v; unsigned short s[8]; } o;
#pragma unroll
for (int q = 0; q < 8; ++q) o.s[q] = f2bf(f[q] * rsc[i]);
*(uint4*)wdst[i] = o.v;
for (int q = 0; q < 8; ++q) f[q] = f[q] * rsc[i];
*(uint4*)wdst[i] = f2bf8(f);
} else {
*(uint4*)wdst[i] = rw[i];
*(r4d_u32x4*)wdst[i] = rw[i];
}
}
__syncthreads();
+23 -5
View File
@@ -314,15 +314,32 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(
// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is
// the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot
// drift because both are stated and neither is inferred.
//
// A ROW IS SPLIT OVER grid.y, kSiluPer elements a thread. One workgroup a row put a decode step's few
// rows on as many workgroups, each walking its row a strided element at a time behind an exp and a
// divide: latency-bound, and the shape of that walk was up to the compiler. Here a thread's
// elements are independent and their loads unconditional (a column past the row reads its last
// element and the store drops it), so they are all in flight at once. Same arithmetic an element.
constexpr uint32_t kSiluPer = 4;
__global__ __launch_bounds__(kThreads) void silu_mul_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float g = bf2f(gr[i]);
yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(gr[n + i]));
const uint32_t i0 = blockIdx.y * (kSiluPer * kThreads) + threadIdx.x;
uint16_t gv[kSiluPer], uv[kSiluPer];
#pragma unroll
for (uint32_t u = 0; u < kSiluPer; ++u) {
const uint32_t i = i0 + u * kThreads, ic = i < n ? i : n - 1u;
gv[u] = gr[ic];
uv[u] = gr[n + ic];
}
#pragma unroll
for (uint32_t u = 0; u < kSiluPer; ++u) {
const uint32_t i = i0 + u * kThreads;
const float g = bf2f(gv[u]);
if (i < n) yr[i] = f32_to_bf16((g / (1.0f + expf(-g))) * bf2f(uv[u]));
}
}
@@ -776,8 +793,9 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y
if (M <= 0 || n <= 0) return -2;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(silu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
const uint32_t chunks = ((uint32_t)n + kSiluPer * kThreads - 1u) / (kSiluPer * kThreads);
hipLaunchKernelGGL(silu_mul_kernel, dim3((uint32_t)M, chunks), dim3(kThreads), 0,
(hipStream_t)stream, (const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
(uint32_t)gu_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+168 -59
View File
@@ -773,13 +773,26 @@ __device__ __forceinline__ Stage8 stage8_load_w(const uint8_t* __restrict__ src,
}
return r;
}
/* A staged tile row as loaded, or the zero a dead row stages. */
__device__ __forceinline__ Stage8 stage8_keep(const Stage8& s, bool live) {
Stage8 r;
r.v = live ? s.v : make_uint4(0, 0, 0, 0);
r.w = live ? s.w : make_uint4(0, 0, 0, 0);
return r;
}
template <bool UW>
__device__ __forceinline__ uint32_t u32_load_w(const uint32_t* p) {
if constexpr (!UW) return *p;
return *(r4d_moe_gu32)p;
}
/* A 16-BIT SCALE LOADED ZERO-EXTENDED INTO A WHOLE REGISTER. Kept 16-bit, LLVM 24 loads it into a
* register HALF (global_load_d16_b16), which leaves the other half live in the same register: the
* load then depends on that register's last write, and the waitcnt pass answers with a full wait
* at the branch joins around the scale loads. The first pass's three loads -- this scale, the
* activation scale, the activation -- went out one round trip each, which cost the down
* projection's four-pass blocks 25-30%. Widened here, it is LLVM 22's global_load_u16. */
template <bool UW>
__device__ __forceinline__ uint16_t u16_load_w(const uint16_t* p) {
__device__ __forceinline__ uint32_t u16_load_w(const uint16_t* p) {
if constexpr (!UW) return *p;
return *(r4d_moe_gu16)p;
}
@@ -961,11 +974,23 @@ static_assert(sizeof(MoeTab) == 16, "the code table is four words");
*
* RS finds an ES block's run in one round trip -- see the RS note at the run search. It covers
* up to kMaxExpert experts; a wider expert count takes the chunked search, which numbers the runs
* the same way. */
* the same way.
*
* THE WAVES A SIMD EACH FORM RUNS AT (R4D_WAVES), as every form was measured: the ES prefill grid
* at 9-11 (5 at FK 256, where the staged pass is the register budget), the aligned form at 9-12,
* the uniform grid at 8-9. Left to itself LLVM 24 spends about 30 more VGPRs on the aligned
* split-K form for one to three fewer waves, which cost its prefill tiles 16-52%. */
constexpr uint32_t moe_waves(uint32_t ntl, int w4, bool es, bool al, uint32_t fk, bool rs) {
return es ? (fk == 256u ? 5u : w4 == 0 ? (rs ? 10u : 11u) : w4 == 1 ? 11u : w4 == 3 ? 9u : 10u)
: al ? (ntl == 16u ? (w4 == 1 ? 12u : 9u) : ntl == 8u ? (w4 <= 1 ? 10u : 9u) : 9u)
: (w4 <= 1 ? 9u : 8u);
}
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
__global__ __launch_bounds__(WGM * WGN * kWave) R4D_WAVES(moe_waves(NTL, W4, ES, AL, FK, RS))
void moe_gemm_q_kernel(
const uint8_t* __restrict__ Aq, const float* __restrict__ As,
const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3,
const int32_t* __restrict__ sorted, const int32_t* __restrict__ off,
@@ -1325,7 +1350,14 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
if (re <= rs) break;
/* Not this block's run: walk past it. Block-uniform, so no barrier is skipped by some
* threads and not others. */
if (ES && run != jrun) { rs = re; ++run; continue; }
/* Not this block's run: never true, since under ES the loop starts at the block's run.
* It stays for the fp8 weight (W4 0) alone, as the back edge it makes: the CFG
* structurizer keeps it, and LLVM 24's waitcnt pass then places the decode form's first-pass
* waits differently. With it the four-bit forms' first pass went out one load a round trip
* (FK 256 gate_up at one and two tokens 4-7% slower than 7.2); without it the fp8 form's
* K loop did (11-13% slower at one and two tokens). Each form is built the way it measured
* faster: r4d_selftest --perfmoe --cold and the MoE fixture's cold kbench. */
if (ES && W4 == 0 && run != jrun) { rs = re; ++run; continue; }
/* The expert's class, and where this block's columns sit in its weight. Block-uniform: a
* pad tile zeroes the run's rows and moves on without touching LDS or a barrier. `cshift`
@@ -1341,7 +1373,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
}
rs = re;
++run;
if (ES) break;
if (ES || AL) break;
continue;
}
const uint32_t wn0 = part * fc + j0; /* the weight row of the block's column 0 */
@@ -1419,11 +1451,28 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
uint4 bpre4[kBP]; /* W4: packed nibbles, expanded at store time as before */
uint32_t spre[W4 == 4 ? kBP : 1]; /* W4 4: the same 32 elements' sign bits */
Stage8 bpre8[kBP]; /* otherwise: the fp8 bytes themselves */
/* kUL: WHETHER EACH STAGED ROW IS LIVE. Under kUL a row's tile is loaded whether it is
* live or not -- a dead row reads a row that exists -- and the zero it stages is selected
* at the LDS store, from these. Loaded only when live, the zero is written into the
* load's destination first, and that write lands on registers the previous pass's load
* filled: on the path where a wave's lanes all skipped that load's store branch, the
* waitcnt pass cannot see the load collected, so it waits for every load in flight before
* the write. Each pass's loads then went out one pair a round trip -- three a K step at
* the aligned down projection's tile, 15% of its time -- where an unconditional load into
* the same registers needs no wait at all (loads of one kind retire in order). The
* one-run-a-block form (ES) keeps the guarded loads: unconditional, it measured 1.5%
* slower, and it does not have the waits. */
constexpr bool kUL = UW && AL;
[[maybe_unused]] bool aok[kUL ? kAP : 1];
[[maybe_unused]] bool bok[kUL ? kBP : 1];
/* thread tid < FM: its row's activation scale, one a 128-wide block of the pass */
float pas[kBpS] = {};
/* thread FM + c: column c's weight scale (w4), or the block's (fp8); at W4 3 its four --
* again one a 128-wide block of the pass */
using PwsT = std::conditional_t<W4 == 3, uint32_t, uint16_t>;
/* At W4 3 the scale IS 32 bits, its four E4M3 groups packed: a 16-bit register would keep
* two of them. Otherwise a 16-bit scale: under AL held zero-extended in a whole register
* (see u16_load_w), the other forms measured 1% slower that way and keep it 16-bit. */
using PwsT = std::conditional_t<AL || W4 == 3, uint32_t, uint16_t>;
PwsT pws[kBpS] = {};
/* UW: the thread's scale as loaded, and whether it is live -- the zero is selected where
* it is staged. Two registers, one a role, and NOT initialised: the two branches run in
@@ -1433,7 +1482,12 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
float pau[UW ? kBpS : 1];
PwsT pwu[UW ? kBpS : 1];
bool pok = false;
auto issue = [&](uint32_t cc) {
/* `first` is the pass at cc 0 as a TYPE, not a test of cc: the early weight is read there
* and nowhere else, and a runtime `cc == 0` in the loop's issue(c0 + FK) is one the compiler
* cannot rule out (the sum is unsigned and may wrap), so it kept the ew_ registers live
* across every pass -- under LLVM 24, sixteen VGPRs the WMMA block then went without: at
* the pinned occupancy it read each fragment pair behind a full LDS wait. */
auto issue = [&](uint32_t cc, auto first) {
const uint32_t kbk = cc / kBlock;
if constexpr (UW) {
/* UNDER UW THE SCALE LOADS ARE UNCONDITIONAL -- from a row that exists when this
@@ -1479,7 +1533,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
else if constexpr (W4)
pws[h] = j0 + nn < fc
? u16_load_w<UW>(Wsp + (size_t)(wn0 + nn) * ws_ld + kbk + h)
: (uint16_t)0;
: 0u;
else if (nn == 0)
pws[h] = u16_load_w<UW>(Wsp + (size_t)kb_n * ws_ld + kbk + h);
}
@@ -1490,26 +1544,40 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
if (r >= FM) continue;
const int32_t tok = s_tok[r];
const bool ok = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re;
apre[p] = stage8_load(Aq + (size_t)(ok ? tok : 0) * a_ld + cc + sk, ok);
const uint8_t* src = Aq + (size_t)(ok ? tok : 0) * a_ld + cc + sk;
if constexpr (kUL) {
aok[p] = ok;
apre[p] = stage8_load_w<UW>(src, true);
} else
apre[p] = stage8_load(src, ok);
}
if constexpr (AL) {
if constexpr (AL && decltype(first)::value) {
/* the first pass's weight is already in flight */
static_assert(kEwBP == kBP && kEwRPP == kRPP,
"the early weight stages the pass issue() would");
if (cc == 0) { /* the first pass's weight is already in flight */
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
if (sn + p * kRPP >= FN) continue;
/* The dead rows' zeros, as w4_load / stage8_load give them. */
for (uint32_t p = 0; p < kBP; ++p) {
if (sn + p * kRPP >= FN) continue;
if constexpr (kUL) {
/* loaded from a row that exists; the store selects the dead rows' zero */
bok[p] = ew_ok[p];
if constexpr (W4) {
bpre4[p] = ew_ok[p] ? ew_b4[p] : make_uint4(0, 0, 0, 0);
if constexpr (W4 == 4) spre[p] = ew_ok[p] ? ew_sp[p] : 0u;
} else {
bpre8[p].v = ew_ok[p] ? ew_b8[p].v : make_uint4(0, 0, 0, 0);
bpre8[p].w = ew_ok[p] ? ew_b8[p].w : make_uint4(0, 0, 0, 0);
}
bpre4[p] = ew_b4[p];
if constexpr (W4 == 4) spre[p] = ew_sp[p];
} else
bpre8[p] = ew_b8[p];
continue;
}
/* The dead rows' zeros, as w4_load / stage8_load give them. */
if constexpr (W4) {
bpre4[p] = ew_ok[p] ? ew_b4[p] : make_uint4(0, 0, 0, 0);
if constexpr (W4 == 4) spre[p] = ew_ok[p] ? ew_sp[p] : 0u;
} else {
bpre8[p].v = ew_ok[p] ? ew_b8[p].v : make_uint4(0, 0, 0, 0);
bpre8[p].w = ew_ok[p] ? ew_b8[p].w : make_uint4(0, 0, 0, 0);
}
return;
}
return;
}
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
@@ -1518,21 +1586,23 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
const bool ok = (j0 + r) < fc;
/* W4: half the bytes off the same row, expanded on the way in. `w_ld` is the
* PACKED byte pitch there, which is why it is not divided here. At W4 4 the row's
* sign plane follows its K/2 bytes of nibbles, a bit an element. */
* sign plane follows its K/2 bytes of nibbles, a bit an element. Under kUL a dead
* row reads the tile's first row, and the store selects its zero (see bok). */
const uint8_t* wr = Wp + (size_t)(kUL && !ok ? wn0 : wn0 + r) * w_ld;
if constexpr (kUL) bok[p] = ok;
if constexpr (W4) {
const uint8_t* wr = Wp + (size_t)(wn0 + r) * w_ld;
bpre4[p] = w4_load_w<UW>(wr + ((cc + sk) >> 1), ok);
bpre4[p] = w4_load_w<UW>(wr + ((cc + sk) >> 1), kUL || ok);
if constexpr (W4 == 4)
spre[p] = ok ? u32_load_w<UW>((const uint32_t*)(wr + (K >> 1) +
((cc + sk) >> 3)))
: 0u;
spre[p] = kUL || ok ? u32_load_w<UW>((const uint32_t*)(wr + (K >> 1) +
((cc + sk) >> 3)))
: 0u;
} else
bpre8[p] = stage8_load_w<UW>(Wp + (size_t)(wn0 + r) * w_ld + cc + sk, ok);
bpre8[p] = stage8_load_w<UW>(wr + cc + sk, kUL || ok);
}
};
/* `s_tok` is settled by the barrier above the run loop and no run rewrites it, so priming
* ahead of the loop's own barrier reads nothing another thread is still writing. */
issue(0);
issue(0u, std::true_type{});
/* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE -- no thread reads what another wrote
* to global memory inside it. __syncthreads() is a workgroup fence over every address
@@ -1561,18 +1631,21 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
for (uint32_t p = 0; p < kAP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r >= FM) continue;
stage8_store<FK>(s_a, r, sk, apre[p]);
stage8_store<FK>(s_a, r, sk, kUL ? stage8_keep(apre[p], aok[p]) : apre[p]);
}
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r >= FN) continue;
/* a dead row's zero, where the packed form held it before (see bok) */
const bool live = !kUL || bok[p];
const uint4 b4 = live ? bpre4[p] : make_uint4(0, 0, 0, 0);
if constexpr (W4 == 4)
stage8_store<FK>(s_b, r, sk, w5_expand(bpre4[p], spre[p], tab.v));
stage8_store<FK>(s_b, r, sk, w5_expand(b4, live ? spre[p] : 0u, tab.v));
else if constexpr (W4)
stage8_store<FK>(s_b, r, sk, w4_expand(bpre4[p], tab.v));
stage8_store<FK>(s_b, r, sk, w4_expand(b4, tab.v));
else
stage8_store<FK>(s_b, r, sk, bpre8[p]);
stage8_store<FK>(s_b, r, sk, kUL ? stage8_keep(bpre8[p], live) : bpre8[p]);
}
/* The scales as issued; under UW the dead ones are zeroed here (see issue). */
auto pas_v = [&](uint32_t h) {
@@ -1601,7 +1674,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
s_ws[tid - FM] = (W4 || tid == FM) ? bscale(pws_v(0)) : 0.0f;
}
}
if (c0 + FK < K) issue(c0 + FK);
if (c0 + FK < K) issue(c0 + FK, std::false_type{});
kbar();
if (!wlive) continue;
@@ -1748,7 +1821,11 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
rs = re;
++run;
if (ES) break; /* one run a block, and it is done */
/* One run a block under ES and AL, and it is done. Under AL a second pass of this loop would
* leave at once (the map's run ends at al_end), but as a loop it lets the compiler hoist
* the first pass's selects of the early weight out of it, to the top: LLVM 24 does, and
* then waits for that weight before the pass's other loads are issued. */
if (ES || AL) break;
}
}
/* The whole argument list against the descriptor (see MoeTab): every instantiation takes the same
@@ -1850,11 +1927,15 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
* the (tile, run) form's runs do: an operand may name fewer rows than its buffer, never more.
* A run that would start past T is then empty and has no tile, so the tile count also stays
* inside the grid's bound. */
/* The loads are unconditional -- a thread past the experts reads off[n_expert] again and a
* select drops it -- so the NPT + 1 of them issue in one round. Guarded, each sits in a branch
* of its own with its wait behind it: NPT + 1 round trips in front of the first barrier. */
uint32_t ov[NPT + 1];
#pragma unroll
for (uint32_t k = 0; k <= NPT; ++k) {
const uint32_t x = tid * NPT + k;
const uint32_t o = x <= n_expert ? (uint32_t)off[x] : 0u;
const uint32_t raw = (uint32_t)off[x <= n_expert ? x : n_expert];
const uint32_t o = x <= n_expert ? raw : 0u;
ov[k] = o < T ? o : T;
}
uint32_t nt[NPT], cnt = 0;
@@ -1947,7 +2028,7 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
uint4 bpre4[kBP];
uint32_t spre[W4 == 4 ? kBP : 1];
Stage8 bpre8[kBP];
using PwsT = std::conditional_t<W4 == 3, uint32_t, uint16_t>;
using PwsT = uint32_t; /* a 16-bit scale zero-extended: see u16_load_w */
float pau[1];
PwsT pwu[1];
bool pok = false;
@@ -2297,9 +2378,14 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel(
#pragma unroll
for (uint32_t j = 0; j < WN; ++j) acc[i][j] = (mb_v8f)(0.0f);
/* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8 of it; a row outside the run
* or a dropped slot stages zeros and issues no load, so the bytes read are the live rows. */
/* Chunk c of a tile is row c / kCPR, elements (c % kCPR) * 8 of it. A row outside the run,
* a dropped slot or a column past N stages zeros. EVERY LOAD IS ISSUED, a dead row's from a
* row that exists -- the activation's row 0, the tile's last weight row -- and the store
* selects its zero: a load under its own condition is an exec-masked branch, and the
* waitcnt pass then waits inside it, which serialises the pass's loads (moe_gemm_q_kernel's
* K-loop note). */
uint4 apre[kAC], bpre[kBC];
bool aok[kAC], bok[kBC];
auto issue = [&](uint32_t k0) {
#pragma unroll
for (uint32_t p = 0; p < kAC; ++p) {
@@ -2307,37 +2393,45 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_bf16_kernel(
if (c >= FM * kCPR) continue;
const uint32_t r = c / kCPR, kk = (c % kCPR) * 8;
const int32_t tok = s_tok[r];
const bool ok = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re;
apre[p] = ok ? *(const uint4*)(A + (size_t)tok * a_ld + k0 + kk)
: make_uint4(0, 0, 0, 0);
aok[p] = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re;
apre[p] = *(const uint4*)(A + (size_t)(aok[p] ? tok : 0) * a_ld + k0 + kk);
}
#pragma unroll
for (uint32_t p = 0; p < kBC; ++p) {
const uint32_t c = tid + p * NTHR;
if (c >= FN * kCPR) continue;
const uint32_t r = c / kCPR, kk = (c % kCPR) * 8;
bpre[p] = (n0 + r) < N ? *(const uint4*)(Wp + (size_t)(n0 + r) * w_ld + k0 + kk)
: make_uint4(0, 0, 0, 0);
bok[p] = (n0 + r) < N;
bpre[p] = *(const uint4*)(Wp + (size_t)(bok[p] ? n0 + r : N - 1) * w_ld + k0 + kk);
}
};
issue(0);
/* THE K LOOP'S BARRIERS ORDER LDS AND NOTHING ELSE, so they are lds_barrier():
* __syncthreads() is a fence over global memory too, `s_wait_loadcnt 0` in front of the
* barrier, and the next pass's prefetch would be waited for right after it is issued
* instead of behind this pass's WMMA. The prefetch is collected by one explicit wait where
* the stores begin -- a release fence on the global address space, the spelling the
* waitcnt pass reads as `s_wait_loadcnt 0` (moe_gemm_q_kernel's K-loop note). */
for (uint32_t k0 = 0; k0 < K; k0 += kBK16) {
__syncthreads(); /* the previous pass's fragments are read */
lds_barrier(); /* the previous pass's fragments are read */
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "global");
#pragma unroll
for (uint32_t p = 0; p < kAC; ++p) {
const uint32_t c = tid + p * NTHR;
if (c >= FM * kCPR) continue;
*(uint4*)(s_a + (c / kCPR) * kP16 + (c % kCPR) * 8) = apre[p];
*(uint4*)(s_a + (c / kCPR) * kP16 + (c % kCPR) * 8) =
aok[p] ? apre[p] : make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (uint32_t p = 0; p < kBC; ++p) {
const uint32_t c = tid + p * NTHR;
if (c >= FN * kCPR) continue;
*(uint4*)(s_b + (c / kCPR) * kP16 + (c % kCPR) * 8) = bpre[p];
*(uint4*)(s_b + (c / kCPR) * kP16 + (c % kCPR) * 8) =
bok[p] ? bpre[p] : make_uint4(0, 0, 0, 0);
}
if (k0 + kBK16 < K) issue(k0 + kBK16);
__syncthreads();
lds_barrier();
if (!wlive) continue;
#pragma unroll
@@ -3043,7 +3137,8 @@ static inline long long r4d_blockmap_bytes(long long cap) {
/* ONE WORKGROUP, because the whole of it is a scan over at most kMaxExpert counters and a second
* launch to split that across the device would cost more than the scan does. The offsets are read
* into LDS once so the scan is not 512 dependent global loads.
* once, in parallel, so the scan is not 512 dependent global loads. The launch is NT threads, a
* thread owning experts tid, tid + NT, ...
*
* THE PREFIX IS PARALLEL: a DPP scan in each wave and one exchange of the wave totals, 256 counts
* a tile -- three tiles at 512 experts, whose n_expert + 1 counts end one past the second. On one
@@ -3055,20 +3150,31 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel(
uint32_t* __restrict__ map) {
constexpr uint32_t NT = 256, NW = NT / kWave, kTiles = (kMaxExpert + NT) / NT;
__shared__ uint32_t s_cnt[kMaxExpert + 1];
__shared__ int32_t s_off[kMaxExpert + 1];
__shared__ int32_t s_wt[kTiles][NW];
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
for (uint32_t e = tid; e <= n_expert; e += blockDim.x) s_off[e] = off[e];
__syncthreads();
/* EVERY OFFSET THIS THREAD NEEDS IN ONE ROUND OF LOADS: both ends of each expert it owns
* (e = tid + i * NT), the index clamped so every load is unconditional, all issued before the
* first is waited on. A loop over e that stores each offset to LDS before the next load makes
* one dependent trip to memory per expert a thread owns -- three at 512 experts -- and the
* offsets are read cold, straight after the router wrote them. The counts and the map's rows
* then come from these registers, so the offsets never pass through LDS. */
int32_t lo[kTiles], hi[kTiles];
#pragma unroll
for (uint32_t i = 0; i < kTiles; ++i) {
const uint32_t e = tid + i * NT;
lo[i] = off[e < n_expert ? e : n_expert];
hi[i] = off[e + 1 < n_expert ? e + 1 : n_expert];
}
const uint32_t live = (uint32_t)off[n_expert];
/* Blocks this expert needs. A zero-row run needs none, and asking for one would put an empty
* block in the map that the GEMM would then have to recognise. */
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]);
s_cnt[e] = (run + FM - 1) / FM;
#pragma unroll
for (uint32_t i = 0; i < kTiles; ++i) {
const uint32_t e = tid + i * NT;
if (e < n_expert) s_cnt[e] = ((uint32_t)(hi[i] - lo[i]) + FM - 1) / FM;
}
/* The tail of dropped slots, carried as one more "expert" so the scan places it too. */
const uint32_t live = (uint32_t)s_off[n_expert];
if (tid == 0) s_cnt[n_expert] = T > live ? (T - live + FM - 1) / FM : 0u;
__syncthreads();
@@ -3094,13 +3200,16 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel(
if (tid == 0) map[0] = carry < cap ? carry : cap; /* the count, clamped to the grid */
__syncthreads();
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]);
#pragma unroll
for (uint32_t i = 0; i < kTiles; ++i) {
const uint32_t e = tid + i * NT;
if (e >= n_expert) continue;
const uint32_t run = (uint32_t)(hi[i] - lo[i]);
uint32_t o = s_cnt[e];
for (uint32_t r = 0; r < run; r += FM, ++o) {
if (o >= cap) break;
map[1 + 2 * o + 0] = e;
map[1 + 2 * o + 1] = (uint32_t)s_off[e] + r;
map[1 + 2 * o + 1] = (uint32_t)lo[i] + r;
}
}
if (tid == 0) {
+46 -37
View File
@@ -1,5 +1,6 @@
// r4d_ple_conv_bf16.hip -- Per-Layer Embedding's dilated depthwise convolution, its silu, and the
// residual add that finishes the layer.
// residual add that finishes the layer; and, as `causal_conv1d`, the same convolution with no
// activation, no residual and no dilation, which is LFM2's short convolution.
//
// ============================== WHAT IT COMPUTES ==============================
//
@@ -83,6 +84,9 @@ static_assert(kPcMaxHist < kPcBT, "the conv history must fit inside tile 0 for t
* against uses std::exp. The GDN conv, which is instruction-bound, makes the opposite trade. */
__device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z)); }
/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window
* with none, no residual and dilation one. */
template <bool SILU>
__global__ __launch_bounds__(kPcThreads) void ple_conv_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
uint16_t* __restrict__ cs, const int32_t* __restrict__ cu,
@@ -125,14 +129,15 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel(
float acc = 0.0f;
#pragma unroll
for (uint32_t j = 0; j < kPcMaxW; ++j) {
if (j >= wid) break;
const int32_t src = t - (int32_t)hist + (int32_t)(j * dil);
const float v = src >= 0 ? bf16_to_f32(xc[(size_t)src * xld])
: (hc ? bf16_to_f32(hc[(src + (int32_t)hist) * cs_tok]) : 0.0f);
acc += v * wt[j];
if (j < wid) {
const int32_t src = t - (int32_t)hist + (int32_t)(j * dil);
const float v = src >= 0 ? bf16_to_f32(xc[(size_t)src * xld])
: (hc ? bf16_to_f32(hc[(src + (int32_t)hist) * cs_tok]) : 0.0f);
acc += v * wt[j];
}
}
const float r = rc ? bf16_to_f32(rc[(size_t)t * rld]) : 0.0f;
yc[(size_t)t * yld] = f32_to_bf16(r + pc_silu(acc));
yc[(size_t)t * yld] = f32_to_bf16(r + (SILU ? pc_silu(acc) : acc));
}
/* THE WINDOW THIS STEP LEAVES BEHIND, in the same launch and with no barrier at all.
@@ -162,47 +167,36 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel(
uint16_t keep[kPcMaxHist];
if (nacc) {
#pragma unroll
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) {
if (i + 1 >= hist) break;
keep[i] = hc ? hc[(size_t)(i + 1) * cs_tok] : (uint16_t)0;
}
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i)
if (i + 1 < hist) keep[i] = hc ? hc[(size_t)(i + 1) * cs_tok] : (uint16_t)0;
#pragma unroll
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) {
if (i + 1 >= hist) break;
dst[(size_t)i * cs_tok] = keep[i];
}
for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i)
if (i + 1 < hist) dst[(size_t)i * cs_tok] = keep[i];
for (int32_t t = 0; t < slen && (long long)hist - 1 + t < state_len; ++t)
dst[(size_t)(hist - 1 + (uint32_t)t) * cs_tok] = xc[(size_t)t * xld];
return;
}
#pragma unroll
for (uint32_t i = 0; i < kPcMaxHist; ++i) {
if (i >= hist) break;
const int32_t src = slen - (int32_t)hist + (int32_t)i;
keep[i] = src >= 0 ? xc[(size_t)src * xld]
: (hc ? hc[(src + (int32_t)hist) * cs_tok] : (uint16_t)0);
if (i < hist) {
const int32_t src = slen - (int32_t)hist + (int32_t)i;
keep[i] = src >= 0 ? xc[(size_t)src * xld]
: (hc ? hc[(src + (int32_t)hist) * cs_tok] : (uint16_t)0);
}
}
#pragma unroll
for (uint32_t i = 0; i < kPcMaxHist; ++i) {
if (i >= hist) break;
dst[(size_t)i * cs_tok] = keep[i];
}
for (uint32_t i = 0; i < kPcMaxHist; ++i)
if (i < hist) dst[(size_t)i * cs_tok] = keep[i];
}
enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y };
/* causal_conv1d's operands: ple_conv's without `resid`. */
enum { CC_X = 0, CC_W, CC_CS, CC_CU, CC_CIDX, CC_HINIT, CC_NACC, CC_Y };
} // namespace
extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, PC_X);
const RadTensor* w = r4d_opt(a, PC_W);
const RadTensor* cs = r4d_opt(a, PC_CS);
const RadTensor* cu = r4d_opt(a, PC_CU);
const RadTensor* resid = r4d_opt(a, PC_RESID);
const RadTensor* cidx = r4d_opt(a, PC_CIDX);
const RadTensor* hini = r4d_opt(a, PC_HINIT);
const RadTensor* nacc = r4d_opt(a, PC_NACC);
const RadTensor* y = r4d_opt(a, PC_Y);
int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, const RadTensor* w,
const RadTensor* cs, const RadTensor* cu, const RadTensor* resid,
const RadTensor* cidx, const RadTensor* hini, const RadTensor* nacc,
const RadTensor* y) {
if (!x || !w || !cu || !y) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || w->dtype != RAD_BF16 || y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
@@ -255,8 +249,8 @@ extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) {
const uint32_t cb = (uint32_t)((n + kPcThreads - 1) / kPcThreads);
const uint32_t tb = (uint32_t)((T + kPcBT - 1) / kPcBT);
hipLaunchKernelGGL(ple_conv_kernel, dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), 0,
(hipStream_t)s,
const auto kernel = silu ? ple_conv_kernel<true> : ple_conv_kernel<false>;
hipLaunchKernelGGL(kernel, dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), 0, (hipStream_t)s,
(const uint16_t*)r4d_addr(x), (const uint16_t*)r4d_addr(w),
have_cs ? (uint16_t*)r4d_addr(cs) : nullptr,
(const int32_t*)r4d_addr(cu),
@@ -269,3 +263,18 @@ extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) {
cs_slot, cs_ch, cs_tok, state_len);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
} // namespace
extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) {
return conv_launch(a, s, true, r4d_opt(a, PC_X), r4d_opt(a, PC_W), r4d_opt(a, PC_CS),
r4d_opt(a, PC_CU), r4d_opt(a, PC_RESID), r4d_opt(a, PC_CIDX),
r4d_opt(a, PC_HINIT), r4d_opt(a, PC_NACC), r4d_opt(a, PC_Y));
}
extern "C" int r4d_rad_causal_conv1d(const RadArgs* a, RadStream s) {
if (r4d_geti_or(a, "dilation", 1) != 1) return R4D_NO(RAD_E_INVAL);
return conv_launch(a, s, false, r4d_opt(a, CC_X), r4d_opt(a, CC_W), r4d_opt(a, CC_CS),
r4d_opt(a, CC_CU), nullptr, r4d_opt(a, CC_CIDX), r4d_opt(a, CC_HINIT),
r4d_opt(a, CC_NACC), r4d_opt(a, CC_Y));
}
+6
View File
@@ -111,6 +111,9 @@ int r4d_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_gqa4_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*);
/* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */
int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream);
/* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body,
* different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */
int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream);
@@ -407,6 +410,7 @@ int r4d_rad_ngram_ids (const RadArgs*, RadStream);
int r4d_rad_ngram_ids_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_ple_gate (const RadArgs*, RadStream);
int r4d_rad_ple_conv (const RadArgs*, RadStream);
int r4d_rad_causal_conv1d (const RadArgs*, RadStream);
int r4d_rad_cast (const RadArgs*, RadStream);
int r4d_rad_gather_rows (const RadArgs*, RadStream);
int r4d_rad_gather_rows_u8 (const RadArgs*, RadStream);
@@ -440,6 +444,8 @@ int r4d_rad_rope (const RadArgs*, RadStream);
int r4d_rad_layernorm (const RadArgs*, RadStream);
int r4d_rad_layernorm_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_grid_embed (const RadArgs*, RadStream);
int r4d_rad_grid_embed_aa (const RadArgs*, RadStream);
int r4d_rad_grid_embed_aa_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_grid_embed_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream);
int r4d_rad_gemm_nt_bias_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
+27 -17
View File
@@ -102,21 +102,37 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
auto gain = [&](int i) -> float {
return w_f32 ? ((const float*)w)[i] : __bfloat162float(((const __hip_bfloat16*)w)[i]);
};
auto normed = [&](int i, float inv) -> float {
const float v = __bfloat162float(in[i]);
// ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of
// this file: the reference stores the norm and RoPEs what it reads back.
return __bfloat162float(__float2bfloat16(v * inv * (gain(i) + wadd)));
// ROUNDED TO bf16 BEFORE THE ROTATION, which is the whole bit-identity argument at the top of
// this file: the reference stores the norm and RoPEs what it reads back.
auto normed = [&](float v, float g, float inv) -> float {
return __bfloat162float(__float2bfloat16(v * inv * (g + wadd)));
};
// EVERYTHING THE ROTATION READS IS LOADED HERE, ahead of the reduction, so it is in flight while
// the sum of squares goes round: this lane's element and gain, its partner's, and its cos and
// sin. None of it depends on the norm. The indices are clamped rather than the loads guarded --
// a lane past the head reads its last element, a lane past the rotary range its own element and
// column 0 of the table (rot >= 2, so the table has one) -- and the values are used only where
// the guards below say.
const int tc = t < HD ? t : HD - 1;
const bool rl = t < rot, first = t < half;
const int pt = rl ? (first ? t + half : t - half) : tc;
const int ci = rl ? (first ? t : t - half) : 0;
const size_t co = (size_t)p * rot;
const float vt = __bfloat162float(in[tc]), gt = gain(tc);
const float vp = __bfloat162float(in[pt]), gp = gain(pt);
const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]);
const float s = cs_f32 ? csf[co + half + ci] : __bfloat162float(csb[co + half + ci]);
float ss = 0.0f;
if (t < HD) { const float v = __bfloat162float(in[t]); ss = v * v; }
if (t < HD) ss = vt * vt;
// rmsnorm_bf16's block_sum, transcribed: the wave butterfly, then the wave partials summed in
// ASCENDING index order. Both halves matter -- an accumulation over the same values in a
// different order breaks the bit-equality argument above.
// different order breaks the bit-equality argument above. The barrier orders the partials in LDS
// and nothing else, so the loads above stay in flight across it.
ss = r4d_wave_sum(ss);
if ((t & 31) == 0) lds[t >> 5] = ss;
__syncthreads();
lds_barrier();
float sum = 0.0f;
#pragma unroll
for (int wv = 0; wv < THR / 32; ++wv) sum += lds[wv];
@@ -124,15 +140,9 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
float res = 0.0f;
if (t < HD) {
res = normed(t, inv);
if (t < rot) {
const bool first = t < half;
const int pt = first ? t + half : t - half;
const int ci = first ? t : t - half;
const size_t co = (size_t)p * rot;
const float c = cs_f32 ? csf[co + ci] : __bfloat162float(csb[co + ci]);
const float s = cs_f32 ? csf[co + half + ci] : __bfloat162float(csb[co + half + ci]);
const float xp = normed(pt, inv);
res = normed(vt, gt, inv);
if (rl) {
const float xp = normed(vp, gp, inv);
res = first ? (res * c - xp * s) : (xp * s + res * c);
}
}
+5 -1
View File
@@ -357,16 +357,20 @@ __global__ __launch_bounds__(kMxWaves * kWave) void qsa_score_mx_kernel(
const int bend = wb0 + tpw * 16 < nbs ? wb0 + tpw * 16 : nbs;
const int32_t* tab = bt + (size_t)seq * bt_ld;
/* THE NEXT TILE'S PAGE ID IS READ WHILE THIS TILE'S KEY IS OUT: the key's address
* depends on it, so read in its own iteration it is a second load latency every tile. */
int pg_next = wb0 + col < bend ? tab[wb0 + col] : -1;
for (int b0 = wb0; b0 < bend; b0 += 16) {
/* The A operand: block `b0 + col`'s key, one page-id read and eight fragment loads. A
* block past the end or without a page reads page 0's key, which always exists, and
* is overwritten or skipped at the store. */
const int b = b0 + col;
const int pg = b < bend ? tab[b] : -1;
const int pg = pg_next;
const unsigned short* kp = bk + (size_t)(pg >= 0 ? pg : 0) * bk_ld + 4 * half;
v8bf kf[kMxKS];
#pragma unroll
for (int ks = 0; ks < kMxKS; ++ks) kf[ks] = fragP(kp + ks * 16);
pg_next = b + 16 < bend ? tab[b + 16] : -1;
/* Which of the tile's sixteen blocks have no page: lanes 0-15 each read one. */
const unsigned absent = (unsigned)__ballot(pg < 0) & 0xFFFFu;
+94
View File
@@ -1810,6 +1810,23 @@ static const RadOperandSpec oPleConv[] = {
{ "num_accepted", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
/* ple_conv's operands without `resid`, its parameters without `dilation`. */
static const RadParamSpec pCausalConv[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "width", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oCausalConv[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "conv_state", RAD_OPD_INOUT, 0 },
{ "cu", RAD_OPD_IN, 0 },
{ "cache_idx", RAD_OPD_IN, 1 },
{ "has_init", RAD_OPD_IN, 1 },
{ "num_accepted", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pNgramIds[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
@@ -2015,6 +2032,12 @@ static const RadOpSchema kSchemas[] = {
"x += a side x side table resampled bilinearly (corners aligned, taps clamped) to each "
"row's grid; coord is [4, M] row, column, height, width. The taps are summed in f32 "
"and rounded before the add."),
SCHEMA("grid_embed_aa", pGridEmbed, oGridEmbed,
"x += the side x side table resampled as torch's F.interpolate(bilinear, "
"align_corners=False, antialias=True) resamples it to the row's grid -- SigLIP2's "
"position embedding: per axis a triangle filter on half-pixel centres, widened by the "
"scale when shrinking, its in-table taps normalised. Separable, f32, rounded once "
"before the add; coordinates clamp into their grid."),
SCHEMA("gemm_nt_bias", pGemmBias, oGemmBias,
"y = res + act(a @ b^T + bias), rounded to bf16 after the biased product, after the "
"activation and after the residual -- the unfused chain's three tensors."),
@@ -2051,6 +2074,10 @@ static const RadOpSchema kSchemas[] = {
"Absent, every token commits: the read is at offset zero and the last "
"(width-1)*dilation inputs land at offset zero, which is the prefill chunk. "
"`resid` absent drops the add and leaves the plain convolution."),
SCHEMA("causal_conv1d", pCausalConv, oCausalConv,
"y[t] = sum_j w[c][j] * x[t - (width-1-j)], ple_conv at dilation one with no "
"activation and no residual: LFM2's short convolution, whose gates the caller applies. "
"The window, `has_init`, `cache_idx` and `num_accepted` are ple_conv's."),
SCHEMA("ngram_ids", pNgramIds, oNgramIds,
"ids[m][h] = remainder(hash of the n-gram ending at m, vocab_sizes[h]) + offsets[h]. "
"Heads are `ngram - 1` equal blocks, block b using the (b+2)-gram. A shift that would "
@@ -2469,6 +2496,17 @@ static const RadConstraint cAttnDecodeH256G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* The prefill pair at head_dim 64 (LFM2: 32 query heads over 8). There is no decode row at this
* width -- the split-KV kernel's lanes hold 128 or 256 columns -- so the query-tiled kernel serves
* every q_len. */
static const RadConstraint cAttnPrefillH64G4Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's
* QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two
* ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is
@@ -3402,6 +3440,9 @@ static const RadConstraint cPleGate[] = { C_IN("dtype", "bf16"), C_GE("n", 1),
static const RadConstraint cPleConv[] = { C_IN("dtype", "bf16"), C_GE("width", 1),
C_LE("width", 5), C_GE("dilation", 1),
C_LE("dilation", 4) };
/* The same kernel undilated: the window is width-1 deep, and the taps are held in registers. */
static const RadConstraint cCausalConv[] = { C_IN("dtype", "bf16"), C_GE("width", 2),
C_LE("width", 8) };
static const RadConstraint cKvStore[] = { C_GE("block_size", 1), C_IN("kv_dtype", "bf16") };
static const RadConstraint cKvStoreFp8[] = { C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3") };
static const RadConstraint cRopeRow[] = { C_GE("head_dim", 1),
@@ -3491,6 +3532,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_ple_conv, nullptr, nullptr, nullptr,
nullptr, nullptr },
{ "causal_conv1d_bf16", "causal_conv1d", "conv",
"depthwise causal conv with no activation (ple_conv's kernel); one thread a channel",
"width 2 to 8, undilated",
"bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cCausalConv), NOTUNE,
nullptr, nullptr, r4d_rad_causal_conv1d, nullptr, nullptr, nullptr,
nullptr, nullptr },
{ "ngram_ids_i32", "ngram_ids", "vocab",
"PLE's hashed n-gram row ids, one thread a token",
"any heads and n-gram size up to 8; heads must divide into ngram-1 equal blocks",
@@ -3684,6 +3734,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_grid_embed, nullptr, nullptr, nullptr,
r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_describe },
{ "grid_embed_aa_bf16", "grid_embed_aa", "elem",
"a learned position grid resampled as torch's antialiased bilinear and added in (SigLIP2)",
"side up to 1024, any n; coord [4, M] dense; one workgroup a row, its taps in LDS",
"bf16 x, bf16 or f32 table, i32 coord, f32 taps",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGridEmbed), NOTUNE,
nullptr, nullptr, r4d_rad_grid_embed_aa, nullptr, nullptr, nullptr,
r4d_shape_grid_embed, nullptr, nullptr, r4d_rad_grid_embed_aa_describe },
{ "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm",
"biased GEMM C = res + act(A @ W^T + bias): eight waves over an LDS-staged 64-deep K tile, "
"the K tail staged as zeros, the activation and residual in the store",
@@ -4097,6 +4156,24 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h64_gqa4_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 64, 4 queries per kv head, paged block 16, varlen",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH64G4Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h64_gqa4_bf16kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 64, 4 queries per kv head, paged block 16, varlen",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH64G4Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
@@ -5697,6 +5774,23 @@ extern "C" int rad_kernel_concurrent(int i) {
return 1;
}
/* WHICH ROWS ARE COLLECTIVES (rad_abi.h): every row whose instance its init builds with the
* exchange buffers, peer flags and handshake of the all-reduce family -- the standalone all-reduces
* and gathers, and the norms and hc writes with one folded in -- and each one's `_host` twin, which
* exchanges through the pinned mailbox instead. Keyed on the init because that is what makes a row
* one: a kernel that reduces across ranks cannot run without the instance only these build. */
extern "C" int rad_kernel_collective(int i) {
const RadKernelInfo* k = rad_kernel_at(i);
if (!k || !k->init) return 0;
const bool coll = host_init_for(k->init) != nullptr || k->init == r4d_rad_ar_host_init ||
k->init == r4d_rad_ar_ln_host_init || k->init == r4d_rad_ar_hc_wide_host_init;
if (!coll) return 0;
/* The two-rank hc writes end the engine's link hold themselves, through `link_gate`, as soon as
* the peer's push has landed over P2P (RAD_LINK_ENDED); through the host mailbox they leave it
* to the engine. */
return (k->launch == r4d_rad_ar_hc_write || k->launch == r4d_rad_ar_gather_hc_write) ? 2 : 1;
}
/* ------------------------------------------------------------------------ tuned config access
*
* THE CHOSEN POINT ARRIVES AS ORDINARY PARAMETERS. The core resolved one instantiation of this
+76 -53
View File
@@ -412,6 +412,9 @@ static void cross_check(const Plugin& pl) {
}
/* ================================================================== the device phase */
/* --cold MIB: bytes read through the caches before every timed launch; see st_time_us. */
static int64_t g_cold = 0;
#ifdef RAD_HAVE_HIP
/* EVERY hipError_t IN THIS FILE IS CHECKED, and that is not pedantry about a `nodiscard`. A
@@ -465,6 +468,63 @@ static void* dalloc(size_t bytes) {
return p;
}
/* ---- THE TIMED WINDOW, WARM OR COLD (--cold MIB).
*
* Warm, a perf mode launches `iters` times back to back on one set of operands, so a weight that
* fits in L2 (8 MiB here) or the last-level cache (64 MiB) is read from cache after the first
* launch: --perfmoe's whole expert set times at ten thousand GB/s "of weight", sixteen times what
* the part's DRAM delivers. The engine streams its weights cold every step, and a change in how a
* kernel waits on memory can look free warm and cost microseconds there.
*
* Cold, every launch is preceded by a read of g_cold bytes through the hierarchy and timed alone
* between two events, and the median launch is the figure. The read is device copies into one
* kColdChunk destination: copied in full, the span would leave that many dirty lines for the
* timed launch to write back, which inflates exactly the bandwidth-bound kernels this mode is for.
* The flush buffers are allocated outside dalloc because dfree_all runs between shapes. */
constexpr int64_t kColdChunk = 4ll << 20;
template <class F>
static double st_time_us(F&& launch, int iters, hipStream_t s) {
if (iters <= 0) return 0.0;
if (g_cold <= 0) {
hipEvent_t e0, e1;
st_ev_create(&e0); st_ev_create(&e1);
st_ev_record(e0, s);
for (int i = 0; i < iters; ++i) launch(i);
st_ev_record(e1, s);
st_ev_sync(e1);
float ms = 0.0f;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0); st_ev_destroy(e1);
return (double)ms * 1000.0 / iters;
}
static void* src = nullptr;
static void* dst = nullptr;
if (!src && (hipMalloc(&src, (size_t)g_cold) != hipSuccess ||
hipMalloc(&dst, (size_t)std::min(g_cold, kColdChunk)) != hipSuccess)) {
std::printf("--cold: no %lld MiB of device memory for the flush\n",
(long long)(g_cold >> 20));
std::exit(1);
}
std::vector<hipEvent_t> ev(2 * (size_t)iters);
for (hipEvent_t& e : ev) st_ev_create(&e);
for (int i = 0; i < iters; ++i) {
for (int64_t off = 0; off < g_cold; off += kColdChunk)
hip_ck(hipMemcpyAsync(dst, (const char*)src + off,
(size_t)std::min(kColdChunk, g_cold - off),
hipMemcpyDeviceToDevice, s), "hipMemcpyAsync", __LINE__);
st_ev_record(ev[2 * (size_t)i], s);
launch(i);
st_ev_record(ev[2 * (size_t)i + 1], s);
}
st_ev_sync(ev.back());
std::vector<float> t((size_t)iters);
for (int i = 0; i < iters; ++i) st_ev_elapsed(&t[(size_t)i], ev[2 * (size_t)i], ev[2 * (size_t)i + 1]);
for (hipEvent_t e : ev) st_ev_destroy(e);
std::sort(t.begin(), t.end());
return (double)t[t.size() / 2] * 1000.0;
}
static void dfree_all() {
for (void* p : g_allocs) st_free(p);
g_allocs.clear();
@@ -5328,21 +5388,10 @@ static void perf_row(const Plugin& pl, const char* name, std::vector<RadTensor>
return;
}
hipEvent_t e0, e1;
st_ev_create(&e0);
st_ev_create(&e1);
st_ev_record(e0, nullptr);
for (int i = 0; i < iters; ++i) {
const double us = st_time_us([&](int i) {
ts[widx].data = (uint8_t*)wbase + (size_t)(i % copies) * wbytes;
r->launch(&a, nullptr);
}
st_ev_record(e1, nullptr);
st_ev_sync(e1);
float ms = 0;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0);
st_ev_destroy(e1);
const double us = (double)ms * 1000.0 / iters;
}, iters, nullptr);
std::printf(" %-22s %8.1f us %6.1f GB/s\n", name, us, bytes / (us * 1e3));
}
@@ -5557,16 +5606,7 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) {
}
st_ev_destroy(w0); st_ev_destroy(w1);
}
hipEvent_t e0, e1;
st_ev_create(&e0); st_ev_create(&e1);
st_ev_record(e0, nullptr);
for (int i = 0; i < iters; ++i) r->launch(&a, nullptr);
st_ev_record(e1, nullptr);
st_ev_sync(e1);
float ms = 0;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0); st_ev_destroy(e1);
const double us = (double)ms * 1000.0 / iters;
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
std::printf(" %-30s %9.2f us %6.1f GB/s\n", name, us, bytes / (us * 1e3));
};
@@ -5869,16 +5909,7 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512,
}
st_ev_destroy(w0); st_ev_destroy(w1);
}
hipEvent_t e0, e1;
st_ev_create(&e0); st_ev_create(&e1);
st_ev_record(e0, nullptr);
for (int i = 0; i < iters; ++i) r->launch(&a, nullptr);
st_ev_record(e1, nullptr);
st_ev_sync(e1);
float ms = 0.0f;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0); st_ev_destroy(e1);
const double us = (double)ms * 1000.0 / iters;
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost);
std::string same = "";
if (f == 0) {
@@ -6193,16 +6224,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
st_ev_elapsed(&wms, w0, w1);
}
st_ev_destroy(w0); st_ev_destroy(w1);
hipEvent_t e0, e1;
st_ev_create(&e0); st_ev_create(&e1);
st_ev_record(e0, hs);
for (int i = 0; i < iters; ++i) r->launch(&a, rst);
st_ev_record(e1, hs);
st_ev_sync(e1);
float ms = 0.0f;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0); st_ev_destroy(e1);
const double us = (double)ms * 1000.0 / iters;
const double us = st_time_us([&](int) { r->launch(&a, rst); }, iters, hs);
const double flop = 2.0 * (double)M * (double)HN * (double)(2 * lr + hc);
std::printf("%s at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + "
"rotated), %s: %.1f us a call, %.1f TFLOP/s\n", rn, (long long)M,
@@ -10280,18 +10302,9 @@ static void moe16_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int
if (pl.pin_moe) pl.pin_moe(0);
continue;
}
hipEvent_t e0, e1;
st_ev_create(&e0); st_ev_create(&e1);
for (int i = 0; i < 3; ++i) r->launch(&a, nullptr);
st_ev_record(e0, nullptr);
for (int i = 0; i < iters; ++i) r->launch(&a, nullptr);
st_ev_record(e1, nullptr);
st_ev_sync(e1);
float ms = 0.0f;
st_ev_elapsed(&ms, e0, e1);
st_ev_destroy(e0); st_ev_destroy(e1);
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
if (pl.pin_moe) pl.pin_moe(0);
const double us = (double)ms * 1000.0 / iters;
st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost);
std::string same;
if (f == 0) first = got;
@@ -11246,6 +11259,8 @@ static void device_phase(const Plugin& pl) {
attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0);
attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0);
attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1);
attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1);
attn_gq_fold_case(pl, 3, false);
attn_gq_fold_case(pl, 24, false);
attn_gq_fold_case(pl, 3, true);
@@ -12934,6 +12949,11 @@ static void usage(void) {
" prefill-tile form (PF2 from M=512) compared byte for byte and timed\n"
" as one op each;\n"
" run it under libr4d/isa/trace.sh for its launches.\n"
" --cold MIB: with a --perf mode, time cold: read MIB through the caches before\n"
" every timed launch (256 empties this card's L2 and last level) and\n"
" time each launch alone, the median reported. Warm, a weight under\n"
" 64 MiB is read from cache after the first launch; the engine reads\n"
" its weights cold.\n"
" --perfmoe M [iters] [experts] [top_k] [pooled%%]: the routed-expert w4 GEMM,\n"
" both projections at rank 0's tp2 width split, over a skewed routing of\n"
" an M-token chunk (512 experts, top 10 by default); every form, each\n"
@@ -13016,6 +13036,9 @@ int main(int argc, char** argv) {
qsa_ctx = std::strtoll(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_m = std::strtoll(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_it = (int)std::strtol(argv[++i], nullptr, 0);
} else if (!std::strcmp(argv[i], "--cold")) {
if (i + 1 >= argc) { usage(); return 2; }
g_cold = std::strtoll(argv[++i], nullptr, 0) << 20;
} else if (!std::strcmp(argv[i], "--perfmoe")) {
/* The routed-expert GEMM at a prefill chunk of M tokens, every prefill form. */
if (i + 1 >= argc) { usage(); return 2; }
+91 -8
View File
@@ -120,6 +120,58 @@ __global__ __launch_bounds__(kThr) void grid_embed_kernel(
}
}
// ---------------------------------------------------------------------------- grid_embed_aa
// ref_grid_embed_aa: torch's antialiased half-pixel bilinear resample (SigLIP2's position table).
// Thread 0 lays out the row's two tap lists -- at most `side` each -- in LDS; every thread then
// takes channels, summing the taps in libref's order (a row of columns, then the rows), and the sum
// is rounded once before the add.
__device__ __forceinline__ int aa_taps(int at, int size, int side, float* w, int* lo) {
size = size < 1 ? 1 : size;
at = at < 0 ? 0 : (at >= size ? size - 1 : at);
const float scale = (float)side / (float)size;
const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support;
const float center = scale * ((float)at + 0.5f);
int a = (int)(center - support + 0.5f), b = (int)(center + support + 0.5f);
a = a < 0 ? 0 : a;
b = b > side ? side : b;
float total = 0.0f;
for (int j = a; j < b; ++j) {
const float d = fabsf(((float)j - center + 0.5f) * inv);
w[j - a] = d < 1.0f ? 1.0f - d : 0.0f;
total += w[j - a];
}
for (int j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f;
*lo = a;
return b > a ? b - a : 0;
}
template <bool TF32>
__global__ __launch_bounds__(kThr) void grid_embed_aa_kernel(
unsigned short* __restrict__ x, const void* __restrict__ tab, const int32_t* __restrict__ crd,
uint32_t n, int side, uint32_t x_ld, uint32_t plane) {
extern __shared__ float aa_w[]; // [2 * side]: the row taps, then the column taps
__shared__ int aa_span[4]; // h0, nh, w0, nw
const uint32_t m = blockIdx.x;
if (threadIdx.x == 0) {
aa_span[1] = aa_taps(crd[m], crd[2 * plane + m], side, aa_w, &aa_span[0]);
aa_span[3] = aa_taps(crd[plane + m], crd[3 * plane + m], side, aa_w + side, &aa_span[2]);
}
__syncthreads();
const int h0 = aa_span[0], nh = aa_span[1], w0 = aa_span[2], nw = aa_span[3];
unsigned short* __restrict__ xr = x + (size_t)m * x_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThr) {
float acc = 0.0f;
for (int y = 0; y < nh; ++y) {
float row = 0.0f;
for (int c = 0; c < nw; ++c)
row += ldw<TF32>(tab, (uint32_t)((h0 + y) * side + w0 + c) * n + i) * aa_w[side + c];
acc += row * aa_w[y];
}
const float pe = bf2f(f32_to_bf16(acc));
xr[i] = f32_to_bf16(bf2f(xr[i]) + pe);
}
}
// ---------------------------------------------------------------------------- gemm_nt_bias
#define VB_BK 64
#define VB_PITCH (VB_BK + 8) // 144-byte LDS rows: gemm_bf16_nt_tiled's bank argument
@@ -176,29 +228,29 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel(
// THE K TAIL IS STAGED AS ZEROS: K is a multiple of 8, so a 16-byte chunk is wholly inside K
// or wholly past it, and a zero chunk contributes exactly nothing to the dot products.
const uint4 zero = make_uint4(0, 0, 0, 0);
uint4 ra[AL], rw[WL];
const r4d_u32x4 zero = (r4d_u32x4)(0u);
r4d_u32x4 ra[AL], rw[WL]; // registers; uint4 would sit in scratch
#pragma unroll
for (int i = 0; i < AL; ++i) ra[i] = ae[i] < K ? *(const uint4*)(A + aoff[i]) : zero;
for (int i = 0; i < AL; ++i) ra[i] = ae[i] < K ? *(const r4d_u32x4*)(A + aoff[i]) : zero;
#pragma unroll
for (int i = 0; i < WL; ++i) rw[i] = we[i] < K ? *(const uint4*)(W + woff[i]) : zero;
for (int i = 0; i < WL; ++i) rw[i] = we[i] < K ? *(const r4d_u32x4*)(W + woff[i]) : zero;
const int nk = (K + VB_BK - 1) / VB_BK;
for (int kt = 0; kt < nk; ++kt) {
__syncthreads();
#pragma unroll
for (int i = 0; i < AL; ++i) *(uint4*)adst[i] = ra[i];
for (int i = 0; i < AL; ++i) *(r4d_u32x4*)adst[i] = ra[i];
#pragma unroll
for (int i = 0; i < WL; ++i) *(uint4*)wdst[i] = rw[i];
for (int i = 0; i < WL; ++i) *(r4d_u32x4*)wdst[i] = rw[i];
__syncthreads();
if (kt + 1 < nk) {
const int k1 = (kt + 1) * VB_BK;
#pragma unroll
for (int i = 0; i < AL; ++i)
ra[i] = k1 + ae[i] < K ? *(const uint4*)(A + aoff[i] + k1) : zero;
ra[i] = k1 + ae[i] < K ? *(const r4d_u32x4*)(A + aoff[i] + k1) : zero;
#pragma unroll
for (int i = 0; i < WL; ++i)
rw[i] = k1 + we[i] < K ? *(const uint4*)(W + woff[i] + k1) : zero;
rw[i] = k1 + we[i] < K ? *(const r4d_u32x4*)(W + woff[i] + k1) : zero;
}
#pragma unroll
for (int s = 0; s < VB_BK / 16; ++s) {
@@ -307,6 +359,37 @@ static int rad_grid_embed_body(const RadArgs* a, const R4dSink& sk) {
}
R4D_ENTRY(r4d_rad_grid_embed, rad_grid_embed_body)
/* grid_embed_aa: grid_embed's operands and checks, the antialiased resample. */
static int rad_grid_embed_aa_body(const RadArgs* a, const R4dSink& sk) {
const RadTensor* x = r4d_opt(a, GE_X);
const RadTensor* tab = r4d_opt(a, GE_TAB);
const RadTensor* crd = r4d_opt(a, GE_CRD);
if (!x || !tab || !crd) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || crd->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE);
if (tab->dtype != RAD_BF16 && tab->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(tab)) return R4D_NO(RAD_E_STRIDE);
const long long n = r4d_geti_or(a, "n", r4d_dim(tab, (int)tab->rank - 1));
const long long side = r4d_geti_or(a, "side", 0);
if (n <= 0 || side <= 0 || side > 1024 || r4d_numel(tab) < side * side * n)
return R4D_NO(RAD_E_SHAPE);
long long M = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
if (x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M || !r4d_contig(crd))
return R4D_NO(RAD_E_SHAPE);
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const uint32_t plane = (uint32_t)crd->shape[1];
const size_t lds = (size_t)(2 * side) * sizeof(float);
if (tab->dtype == RAD_F32)
return R4D_EMIT(sk, grid_embed_aa_kernel<true>, dim3((uint32_t)M), dim3(kThr), lds,
(unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd),
(uint32_t)n, (int)side, (uint32_t)x_ld, plane);
return R4D_EMIT(sk, grid_embed_aa_kernel<false>, dim3((uint32_t)M), dim3(kThr), lds,
(unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd),
(uint32_t)n, (int)side, (uint32_t)x_ld, plane);
}
R4D_ENTRY(r4d_rad_grid_embed_aa, rad_grid_embed_aa_body)
/* ------------------------------------------------------------------ gemm_nt_bias */
enum { GB_A = 0, GB_W, GB_BIAS, GB_RES, GB_Y };