libr4d: GLM-5.3's kernels -- mHC, KDA, the DSA indexer, MLA, f32-scaled FP8, MXFP4 experts

The device rows for GLM-5.3-Flash's ops, at its geometry and at TP4 and TP8 slices:

- mhc_pre / mhc_post / mhc_contract, and mhc_pre_partial / mhc_pre_finish, which run mhc_pre's
  own projection and finishing kernels with its chunk-sum order, so the pair is byte-identical
  to mhc_pre at n 4096, hc 4, chunk 2048.
- kda_update_k128_v128_bf16, one, two or four value rows a wave, both state forms.
- dsa_pool_fp8, dsa_query_fp8 and dsa_score_fp8 (fp8 WMMA, 32 heads of 128).
- mla_attn: a matrix row whose WMMA tile holds a query's heads, or pairs eight heads of two
  neighbouring queries over the union of their page tables, above the wave row; mla_project
  with up to eight rows a thread or wave.
- gemm_nt_f32 and router_sigmoid_topk in tiled and one-wave-a-row forms; gemm_fp8a8_f32scale
  and moe_gemm_fp8a8_f32scale read f32 block scales in place; moe_gemm_mxfp4a8 decodes e2m1 into
  exact E4M3 bytes for fp8 WMMA, with an expert-major decode form and a wide prefill form.
- swiglu_clamped, and the device-only fusions of GLM's MoE block: swiglu_clamped_quant_fp8,
  router_sigmoid_topk_scatter, and moe_scatter_inv / moe_gather_inv, which pass the gather's slot
  table from the sort instead of rebuilding it.

moe_gather takes f32 routing weights in its column-per-thread kernel. The sort and the gather
kernels move from r4d_moe.hip into r4d_moe_sort.h and r4d_moe_gather.h, so the fused router and
gather instantiate the same code.

Every form that replaces another gives its bytes: tests/r4d_emu runs the kernels on the host
(test_f32, test_fp8f32, test_kda, test_mhc, test_mla, test_moefuse, test_moemx), r4d_selftest
compares them on a card against libref and against each other, and plugin_test pins the
mla_attn band. docs/OPS.md states what libr4d serves.

Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com>
This commit is contained in:
NunzeandJohn McDonough authored and StillDeadcode committed 2026-10-19 20:13:47 +02:00
1 parent da77f86332
commit 78c58841bf
31 files changed
+12371 -302

No files matched your search

+7
View File
@@ -103,6 +103,13 @@ set(R4D_UNITS
# launches behind one entry point: the mix depends on every column of the low-rank waist, so it
# needs a grid-wide barrier.
"r4d_hc_bf16|"
"r4d_mhc|"
"r4d_glm|"
"r4d_dsa|"
"r4d_mla|"
"r4d_kda|"
"r4d_moe_mxfp4|"
"r4d_fp8_f32scale|"
"r4d_ngram_ids|"
"r4d_ple_gate_bf16|"
"r4d_ple_conv_bf16|"
+4
View File
@@ -643,6 +643,10 @@ void r4d_moe_gemm_pin_down_dec(int pin);
// (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes).
// All bit-identical; r4d_selftest compares their bytes.
void r4d_hc_read_pin_prefill(int form);
// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
// Bit-identical; r4d_selftest compares them and --perfmla times both.
void r4d_mla_matrix_pin_form(int form);
// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the
// next call, and returns how many launches the previous recording saw (which may exceed its cap).
// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel
+298
View File
@@ -0,0 +1,298 @@
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_fwht.h"
#include "r4d_q8.h"
#include "r4d_fp8_wmma.h"
#include <climits>
namespace {
__global__ void dsa_query_kernel(const uint16_t* x, uint8_t* q, float* scale, long xp, long qp,
long sp, int rows) {
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
if (r >= rows) return;
float v[4];
#pragma unroll
for (int d = 0; d < 4; ++d) v[d] = bf16_to_f32(x[(long)r * xp + lane * 4 + d]);
r4d_fwht_wave<128>(v, lane);
float am = 1e-4f;
#pragma unroll
for (int d = 0; d < 4; ++d) {
v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f));
am = fmaxf(am, fabsf(v[d]));
}
#pragma unroll
for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32));
const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f));
const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0));
if (!lane) scale[(long)r * sp] = sc;
const uint32_t packed = q8_pack4<false>(v[0], v[1], v[2], v[3], 1.0f / sc);
uint8_t* dst = q + (long)r * qp + lane * 4;
if (((uintptr_t)dst & 3) == 0)
*(uint32_t*)dst = packed;
else {
#pragma unroll
for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d));
}
}
int query_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
if (r4d_geti_or(a, "n", 0) != 128 || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
x.shape[0] < 1 || x.shape[0] > INT_MAX - 3 || x.shape[1] != 128 ||
q.shape[0] != x.shape[0] || q.shape[1] != 128 || s.shape[0] != x.shape[0] ||
s.shape[1] != 1 || x.stride[1] != 1 || q.stride[1] != 1 || s.stride[1] != 1 ||
x.stride[0] < 128 || q.stride[0] < 128 || s.stride[0] < 1)
return RAD_E_SHAPE;
return R4D_EMIT(stream, dsa_query_kernel, dim3((x.shape[0] + 3) / 4), dim3(128), 0,
(const uint16_t*)x.data, (uint8_t*)q.data, (float*)s.data, x.stride[0],
q.stride[0], s.stride[0], (int)x.shape[0]);
}
struct ScoreMeta {
long qr, qh, qsr, qsc, gr, gc, kr, ksr, btr, btc, cur, ncr, op;
int rows, blocks, seqs, pages;
};
__device__ uint32_t bytes4(const uint8_t* p) {
if (!((uintptr_t)p & 3)) return *(const uint32_t*)p;
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
/* Two waves cover all 32 heads and reuse the query across `kScoreTiles` 16-key tiles, one up to 32
* blocks and two past them. FP8 dot products stay on WMMA; scales and the signed per-head gates
* fold only after the per-head ReLU. */
template <int kScoreTiles>
__global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* gate,
const uint8_t* k, const float* ks, const int* bt, const int* cu,
const int* nc, float* out, ScoreMeta m) {
constexpr int kScoreKeys = 16 * kScoreTiles;
__shared__ __align__(16) uint8_t qa[32 * 136], kb[kScoreKeys * 136];
__shared__ int seq, pages[kScoreKeys];
__shared__ float scales[kScoreKeys], coefficients[32], partial[2][kScoreKeys];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int r = blockIdx.y, b0 = blockIdx.x * kScoreKeys;
if (!tid) {
seq = -1;
for (int s = 0; s < m.seqs; ++s)
if (r >= cu[(long)s * m.cur] && r < cu[(long)(s + 1) * m.cur]) {
seq = s;
break;
}
}
__syncthreads();
const int live = seq >= 0 ? min(nc[(long)seq * m.ncr], m.blocks) : 0;
if (b0 >= live) {
for (int i = tid; i < kScoreKeys; i += 64)
if (b0 + i < m.blocks) out[(long)r * m.op + b0 + i] = -INFINITY;
return;
}
for (int i = tid; i < kScoreKeys; i += 64) {
const int b = b0 + i;
int p = seq >= 0 && b < m.blocks && b < nc[(long)seq * m.ncr]
? bt[(long)seq * m.btr + b * m.btc]
: -1;
if (p >= m.pages) p = -1;
pages[i] = p;
scales[i] = p >= 0 ? ks[(long)p * m.ksr] : 0;
}
if (tid < 32)
coefficients[tid] = qs[(long)r * m.qsr + tid * m.qsc] * gate[(long)r * m.gr + tid * m.gc];
for (int j = tid; j < 32 * 32; j += 64) {
const int h = j / 32, d = (j % 32) * 4;
*(uint32_t*)(qa + h * 136 + d) = bytes4(q + (long)r * m.qr + (long)h * m.qh + d);
}
__syncthreads();
for (int j = tid; j < kScoreKeys * 32; j += 64) {
const int b = j / 32, d = (j % 32) * 4, p = pages[b];
*(uint32_t*)(kb + b * 136 + d) = p >= 0 ? bytes4(k + (long)p * m.kr + d) : 0;
}
__syncthreads();
r4d_fp8::f8v acc[kScoreTiles];
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile) acc[tile] = r4d_fp8::acc_zero();
#pragma unroll
for (int d = 0; d < 128; d += 16) {
const auto a = r4d_fp8::frag<128>(qa, wave * 16, d, lane);
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile)
acc[tile] = r4d_fp8::mma(a, r4d_fp8::frag<128>(kb, tile * 16, d, lane), acc[tile]);
}
#pragma unroll
for (int tile = 0; tile < kScoreTiles; ++tile) {
float value = 0;
#pragma unroll
for (int j = 0; j < 8; ++j)
value += fmaxf(acc[tile][j], 0.0f) * coefficients[wave * 16 + (lane >> 4) * 8 + j];
value += __shfl_xor(value, 16, 32);
if (lane < 16) partial[wave][tile * 16 + lane] = value;
}
__syncthreads();
for (int i = tid; i < kScoreKeys; i += 64)
if (b0 + i < m.blocks)
out[(long)r * m.op + b0 + i] =
pages[i] >= 0 ? (partial[0][i] + partial[1][i]) * scales[i] * 0.015625f : -INFINITY;
}
int score_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 9) return RAD_E_INVAL;
RadTensor q = a->t[0], qs = a->t[1];
const auto& g = a->t[2];
RadTensor k = a->t[3], ks = a->t[4];
const bool packed = k.dtype == RAD_U8;
if (packed) {
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
((uintptr_t)k.data & 3))
return RAD_E_SHAPE;
ks = {};
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
ks.dtype = RAD_F32;
ks.rank = 1;
ks.shape[0] = k.shape[0];
ks.stride[0] = k.stride[0] / 4;
k.dtype = RAD_F8E4M3;
k.rank = 2;
k.shape[1] = 128;
k.stride[1] = 1;
}
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &o = a->t[8];
if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && q.shape[0] == o.shape[0] * 32 &&
qs.shape[0] == q.shape[0]) {
q.rank = 3;
q.shape[0] = o.shape[0];
q.shape[2] = q.shape[1];
q.shape[1] = 32;
q.stride[2] = q.stride[1];
q.stride[1] = q.stride[0];
q.stride[0] *= 32;
qs.shape[0] = o.shape[0];
qs.shape[1] = 32;
qs.stride[1] = qs.stride[0];
qs.stride[0] *= 32;
}
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
g.dtype != RAD_F32 || ks.dtype != RAD_F32 || o.dtype != RAD_F32 || bt.dtype != RAD_I32 ||
cu.dtype != RAD_I32 || nc.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 9; ++i)
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "heads", 0) != 32 || q.rank != 3 ||
q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != 32 || q.shape[2] != 128 ||
q.stride[2] != 1 || q.stride[1] < 128 || q.stride[0] < 32 * q.stride[1] || qs.rank != 2 ||
g.rank != 2 || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0] || qs.shape[1] != 32 ||
g.shape[1] != 32 || qs.stride[1] < 1 || g.stride[1] < 1 ||
qs.stride[0] < 32 * qs.stride[1] || g.stride[0] < 32 * g.stride[1] || k.rank != 2 ||
k.shape[0] < 1 || k.shape[0] > INT_MAX || k.shape[1] != 128 || k.stride[1] != 1 ||
k.stride[0] < 128 || ks.rank != 1 || ks.shape[0] != k.shape[0] || ks.stride[0] < 1 ||
bt.rank != 2 || bt.shape[0] < 1 || bt.shape[0] > INT_MAX || bt.stride[1] < 1 ||
cu.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || nc.rank != 1 ||
nc.shape[0] != bt.shape[0] || cu.stride[0] < 1 || nc.stride[0] < 1 || o.rank != 2 ||
o.shape[0] != q.shape[0] || o.shape[1] < 1 || o.shape[1] > INT_MAX - 15 ||
o.shape[1] > bt.shape[1] || o.stride[1] != 1 || o.stride[0] < o.shape[1] ||
bt.stride[0] < bt.shape[1] * bt.stride[1])
return RAD_E_SHAPE;
ScoreMeta m{ q.stride[0], q.stride[1], qs.stride[0], qs.stride[1], g.stride[0],
g.stride[1], k.stride[0], ks.stride[0], bt.stride[0], bt.stride[1],
cu.stride[0], nc.stride[0], o.stride[0], (int)q.shape[0], (int)o.shape[1],
(int)bt.shape[0], (int)k.shape[0] };
#define SCORE(NT) \
R4D_EMIT(stream, (dsa_score_kernel<NT>), dim3((m.blocks + 16 * NT - 1) / (16 * NT), m.rows), \
dim3(64), 0, (const uint8_t*)q.data, (const float*)qs.data, (const float*)g.data, \
(const uint8_t*)k.data, (const float*)ks.data, (const int*)bt.data, \
(const int*)cu.data, (const int*)nc.data, (float*)o.data, m)
if (m.blocks <= 32) return SCORE(1);
return SCORE(2);
#undef SCORE
}
/* One wave per pool: all softmax channels and the full Hadamard stay in registers. */
__global__ void dsa_pool_kernel(const uint16_t* kg, const float* ape, uint8_t* q, float* scale,
const int* page, uint8_t* cache, long kp, long ap, long qp, long sp,
long pp, long cp, int rows, int pages) {
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
if (r >= rows) return;
float v[4];
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int col = lane * 4 + d;
float g[4], mx = -INFINITY;
#pragma unroll
for (int j = 0; j < 4; ++j) {
g[j] = bf16_to_f32(kg[((long)r * 4 + j) * kp + 128 + col]) + ape[(long)j * ap + col];
mx = fmaxf(mx, g[j]);
}
float num = 0, den = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const float p = expf(g[j] - mx);
num += p * bf16_to_f32(kg[((long)r * 4 + j) * kp + col]);
den += p;
}
v[d] = bf16_to_f32(f32_to_bf16(num / den));
}
r4d_fwht_wave<128>(v, lane);
float am = 1e-4f;
#pragma unroll
for (int d = 0; d < 4; ++d) {
v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f));
am = fmaxf(am, fabsf(v[d]));
}
#pragma unroll
for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32));
const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f));
const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0));
if (!lane) scale[(long)r * sp] = sc;
const uint32_t packed = q8_pack4<false>(v[0], v[1], v[2], v[3], 1.0f / sc);
uint8_t* dst = q + (long)r * qp + lane * 4;
if (((uintptr_t)dst & 3) == 0)
*(uint32_t*)dst = packed;
else {
#pragma unroll
for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d));
}
if (cache) {
const int p = page[(long)r * pp];
if (p >= 0 && p < pages) {
uint8_t* out = cache + (long)p * cp;
*(uint32_t*)(out + lane * 4) = packed;
if (!lane) *(float*)(out + 128) = sc;
}
}
}
int pool_body(const RadArgs* a, RadStream stream) {
if (r4d_geti_or(a, "block_size", 4) != 4) return RAD_E_SHAPE;
if (!a || a->n_t < 4) return RAD_E_INVAL;
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
if (cache &&
(page->dtype != RAD_I32 || page->rank != 1 || page->shape[0] != q.shape[0] ||
page->stride[0] < 1 || cache->dtype != RAD_U8 || cache->rank != 4 || cache->shape[0] < 1 ||
cache->shape[0] > INT_MAX || cache->shape[1] != 1 || cache->shape[2] != 4 ||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
return RAD_E_SHAPE;
if (kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32)
return RAD_E_DTYPE;
if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "ratio", 0) != 4 || kg.rank != 2 ||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || !kg.data || !ape.data || !q.data ||
!s.data || q.shape[0] < 1 || q.shape[0] > INT_MAX / 4 || kg.shape[0] != q.shape[0] * 4 ||
kg.shape[1] != 256 || ape.shape[0] != 4 || ape.shape[1] != 128 || q.shape[1] != 128 ||
s.shape[0] != q.shape[0] || s.shape[1] != 1 || kg.stride[1] != 1 || ape.stride[1] != 1 ||
q.stride[1] != 1 || s.stride[1] != 1 || kg.stride[0] < 256 || ape.stride[0] < 128 ||
q.stride[0] < 128 || s.stride[0] < 1)
return RAD_E_SHAPE;
return R4D_EMIT(
stream, dsa_pool_kernel, dim3((q.shape[0] + 3) / 4), dim3(128), 0, (const uint16_t*)kg.data,
(const float*)ape.data, (uint8_t*)q.data, (float*)s.data,
page ? (const int*)page->data : nullptr, cache ? (uint8_t*)cache->data : nullptr,
kg.stride[0], ape.stride[0], q.stride[0], s.stride[0], page ? page->stride[0] : 0,
cache ? cache->stride[0] : 0, (int)q.shape[0], cache ? (int)cache->shape[0] : 0);
}
}
extern "C" int r4d_rad_dsa_pool(const RadArgs* a, RadStream stream) { return pool_body(a, stream); }
extern "C" int r4d_rad_dsa_query(const RadArgs* a, RadStream stream) {
return query_body(a, stream);
}
extern "C" int r4d_rad_dsa_score(const RadArgs* a, RadStream stream) {
return score_body(a, stream);
}
+642
View File
@@ -0,0 +1,642 @@
/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no
* checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output
* tile a block; the dense decode and prefill forms below them produce the same bytes faster. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_fp8_wmma.h"
#include "r4d_launch.h"
#include <climits>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace {
struct Meta {
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
int T, N, K, experts, topk, sorted_a, tile;
};
__device__ const uint8_t* entry(const void* p, long step, int e) {
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
}
template <bool Grouped>
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0,
const void* w1, const void* s1, const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64;
__shared__ uint8_t qa[16 * 136], wb[64 * 136];
__shared__ int source[16];
int first = (int)blockIdx.y * (Grouped ? m.tile : 16);
const int limit = min(first + (Grouped ? m.tile : 16), m.T);
while (first < limit) {
int expert = 0, end = limit;
if constexpr (Grouped) {
// Tile sorted rows rather than launching every expert, most of which are empty
// during native MTP decode. Split a tile at each expert boundary.
if (sorted[first] < 0 || offsets[m.experts] <= first) {
for (int c = tid; c < 64; c += 128)
if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0;
++first;
continue;
}
int lo = 0, hi = m.experts;
while (lo + 1 < hi) {
const int mid = (lo + hi) / 2;
if (offsets[mid] <= first)
lo = mid;
else
hi = mid;
}
expert = lo;
end = min(limit, offsets[expert + 1]);
if (end <= first) return;
}
const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e);
if (tid < 16) {
const int r = first + tid;
const int flat = Grouped && r < end ? sorted[r] : r;
source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1;
}
__syncthreads();
auto acc = r4d_fp8::acc_zero();
for (int k0 = 0; k0 < m.K; k0 += 128) {
for (int j = tid; j < 16 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4, src = source[r];
uint32_t v = 0;
if (src >= 0) {
const auto* p = a + (long)src * m.ar + k0 + c;
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
((uint32_t)p[3] << 24);
}
*(uint32_t*)(qa + r * 136 + c) = v;
}
for (int j = tid; j < 64 * 32; j += 128) {
const int r = j / 32, c = (j % 32) * 4;
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
__syncthreads();
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int src = source[(lane >> 4) * 8 + j];
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
acc[j] += raw[j] * scale;
}
__syncthreads();
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
__syncthreads();
first = end;
}
}
/* The grouped form expert-major: a block per (column span, expert) takes every row of its
* expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in
* the sorted order (the row tiles above re-read it once per tile its run spans). Each element
* keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw *
* (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in
* stages of StageK, as one stage sequence with the next stage loaded into registers while the
* current one computes from LDS. Block row `experts` zeroes the dropped rows past
* offsets[experts]. */
typedef unsigned f8_u4 __attribute__((ext_vector_type(4)));
template <int StageK>
struct F8Stage {
static constexpr int KB = StageK / 128;
f8_u4 a[StageK / 128], w[StageK / 32];
float wsc[KB], sa;
};
template <int StageK, int ColTiles>
__global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, const float* as,
const void* w0, const void* s0,
const void* w1, const void* s1,
const int* sorted, const int* offsets,
uint16_t* y, Meta m) {
using St = F8Stage<StageK>;
constexpr int KB = St::KB, P = StageK + 8;
__shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P];
__shared__ float sa[16 * KB];
__shared__ int source[16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y,
colb = blockIdx.x * 64 * ColTiles;
if (e == m.experts) {
const int r0 = offsets[m.experts];
for (long i = tid; i < (long)(m.T - r0) * 64 * ColTiles; i += 128) {
const int c = colb + (int)(i % (64 * ColTiles));
if (c < m.N) y[(long)(r0 + i / (64 * ColTiles)) * m.yr + c] = 0;
}
return;
}
const int lo = offsets[e], hi = offsets[e + 1];
if (lo >= hi) return;
const int parity = e & 1;
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2);
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2);
const int ksn = (m.K + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + 63) / 64),
S = tiles * ksn;
const int rowbase = (lane >> 4) * 8;
for (int r0 = lo; r0 < hi; r0 += 16) {
__syncthreads();
if (tid < 16) {
const int r = r0 + tid, flat = r < hi ? sorted[r] : -1;
source[tid] = r < hi && flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1;
}
__syncthreads();
bool rv[8];
#pragma unroll
for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0;
auto load = [&](int s, St& R) {
const int col0 = colb + (s / ksn) * 64, k0 = (s % ksn) * StageK;
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16,
src = source[r];
R.a[i] = f8_u4{ 0, 0, 0, 0 };
if (src >= 0 && k0 + c < m.K)
__builtin_memcpy(&R.a[i], a + (long)src * m.ar + k0 + c, 16);
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
R.w[i] = f8_u4{ 0, 0, 0, 0 };
if (k0 + c < m.K)
__builtin_memcpy(&R.w[i], w + (long)(col0 + r) * m.wr + k0 + c, 16);
}
#pragma unroll
for (int kb = 0; kb < KB; ++kb)
R.wsc[kb] =
k0 + kb * 128 < m.K ? ws[(long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128] : 0;
if (tid < 16 * KB) {
const int src = source[tid / KB], kb = k0 + (tid % KB) * 128;
R.sa = src >= 0 && kb < m.K ? as[(long)src * m.asr + kb / 128] : 0;
}
};
auto store = [&](const St& R) {
#pragma unroll
for (int i = 0; i < StageK / 128; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(qa + r * P + c) = R.a[i];
}
#pragma unroll
for (int i = 0; i < StageK / 32; ++i) {
const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16;
*reinterpret_cast<f8_u4*>(wb + r * P + c) = R.w[i];
}
if (tid < 16 * KB) sa[tid] = R.sa;
};
auto acc = r4d_fp8::acc_zero();
St R;
load(0, R);
for (int s = 0; s < S; ++s) {
store(R);
float wsc[KB];
#pragma unroll
for (int kb = 0; kb < KB; ++kb) wsc[kb] = R.wsc[kb];
__syncthreads();
if (s + 1 < S) load(s + 1, R);
const int k0 = (s % ksn) * StageK;
#pragma unroll
for (int kb = 0; kb < KB; ++kb) {
if (k0 + kb * 128 >= m.K) break;
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = kb * 128; k < (kb + 1) * 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<StageK>(qa, 0, k, lane),
r4d_fp8::frag<StageK>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float scale = rv[j] ? sa[(rowbase + j) * KB + kb] * wsc[kb] : 0;
acc[j] += raw[j] * scale;
}
}
if (s % ksn == ksn - 1) {
const int c = colb + (s / ksn) * 64 + wave * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = r0 + rowbase + j;
if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
}
acc = r4d_fp8::acc_zero();
}
__syncthreads();
}
}
}
// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same
// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's
// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale *
// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and
// C, so which rows and columns share a tile does not change it.
// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at
// once, the fragments loaded straight from global memory; R row tiles share each weight fragment
// and C column tiles each activation fragment. Each wave scales its own partial products (the
// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then
// every wave folds a share of the outputs, adding the round's products in block order to the
// output's running sum, which lives in LDS between rounds. The block's activation scales are
// staged in LDS when they fit (`stage`).
template <int R, int C>
__global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uint8_t* w,
const float* ws, uint16_t* y, Meta m, int stage) {
constexpr int SL = R * C * 8;
R4D_DYN_LDS(float, lds);
const int lane = threadIdx.x & 31, s = threadIdx.x >> 5, S = blockDim.x >> 5, h = lane >> 4;
const int c0 = blockIdx.x * 16 * C, first = (int)blockIdx.y * R * 16, KB = m.K / 128;
float* part = lds;
float* sums = part + S * SL * 32;
float* scales = sums + SL * 32;
if (stage)
for (int i = threadIdx.x; i < R * 16 * KB; i += blockDim.x) {
const int r = first + i / KB;
scales[i] = r < m.T ? as[(long)r * m.asr + i % KB] : 0;
}
for (int i = threadIdx.x; i < SL * 32; i += blockDim.x) sums[i] = 0;
const uint8_t* arow[R];
bool alive[R];
#pragma unroll
for (int t = 0; t < R; ++t) {
const int r = first + t * 16 + (lane & 15);
alive[t] = r < m.T;
arow[t] = a + (long)(alive[t] ? r : 0) * m.ar + h * 8;
}
__syncthreads();
for (int k0 = 0; k0 < KB; k0 += S) {
const int kb = k0 + s;
if (kb < KB) {
r4d_fp8::i2v b[C][8];
float weight_scale[C];
#pragma unroll
for (int c = 0; c < C; ++c) {
const uint8_t* wrow =
w + (long)(c0 + c * 16 + (lane & 15)) * m.wr + h * 8 + (long)kb * 128;
#pragma unroll
for (int q = 0; q < 8; ++q) {
const uint2 v = *(const uint2*)(wrow + q * 16);
b[c][q][0] = (int)v.x;
b[c][q][1] = (int)v.y;
}
weight_scale[c] = ws[(long)((c0 + c * 16) / 128) * m.sr + kb];
}
#pragma unroll
for (int t = 0; t < R; ++t) {
r4d_fp8::i2v f[8];
#pragma unroll
for (int q = 0; q < 8; ++q) {
uint2 v = make_uint2(0, 0);
if (alive[t]) v = *(const uint2*)(arow[t] + (long)kb * 128 + q * 16);
f[q][0] = (int)v.x;
f[q][1] = (int)v.y;
}
float act[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int rr = t * 16 + h * 8 + j, r = first + rr;
act[j] =
stage ? scales[rr * KB + kb] : (r < m.T ? as[(long)r * m.asr + kb] : 0);
}
#pragma unroll
for (int c = 0; c < C; ++c) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int q = 0; q < 8; ++q) raw = r4d_fp8::mma(f[q], b[c][q], raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? act[j] * weight_scale[c] : 0;
part[((long)s * SL + (t * C + c) * 8 + j) * 32 + lane] = raw[j] * scale;
}
}
}
}
__syncthreads();
for (int slot = s; slot < SL; slot += S) {
float acc = sums[slot * 32 + lane];
for (int q = 0; q < S && k0 + q < KB; ++q)
acc += part[((long)q * SL + slot) * 32 + lane];
sums[slot * 32 + lane] = acc;
}
__syncthreads();
}
for (int slot = s; slot < SL; slot += S) {
const int t = slot / (C * 8), c = slot / 8 % C, j = slot % 8,
r = first + t * 16 + h * 8 + j;
if (r < m.T)
y[(long)r * m.yr + c0 + c * 16 + (lane & 15)] = f32_to_bf16(sums[slot * 32 + lane]);
}
}
// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight
// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded
// into registers while the current one is multiplied.
template <int R>
__global__ void __launch_bounds__(128)
fp8_f32scale_rows(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
uint16_t* y, Meta m) {
constexpr int P = 136, AV = R * 16 * 8 / 128, WV = 64 * 8 / 128;
__shared__ uint8_t qa[R * 16 * P], wb[64 * P];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, h = lane >> 4,
n0 = blockIdx.x * 64;
const int first = (int)blockIdx.y * R * 16, KB = m.K / 128;
uint4 av[AV], wv[WV];
auto load = [&](int kb) {
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
av[i] = first + r < m.T
? *(const uint4*)(a + (long)(first + r) * m.ar + (long)kb * 128 + c)
: make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16;
wv[i] = *(const uint4*)(w + (long)(n0 + r) * m.wr + (long)kb * 128 + c);
}
};
r4d_fp8::f8v acc[R];
#pragma unroll
for (int t = 0; t < R; ++t) acc[t] = r4d_fp8::acc_zero();
load(0);
for (int kb = 0; kb < KB; ++kb) {
// The 136-byte pitch keeps 8-byte alignment only, so each 16 bytes go in as two halves.
auto put = [](uint8_t* p, const uint4& v) {
((uint2*)p)[0] = make_uint2(v.x, v.y);
((uint2*)p)[1] = make_uint2(v.z, v.w);
};
#pragma unroll
for (int i = 0; i < AV; ++i) {
const int j = tid + i * 128;
put(qa + (j / 8) * P + (j % 8) * 16, av[i]);
}
#pragma unroll
for (int i = 0; i < WV; ++i) {
const int j = tid + i * 128;
put(wb + (j / 8) * P + (j % 8) * 16, wv[i]);
}
__syncthreads();
if (kb + 1 < KB) load(kb + 1);
const float weight_scale = ws[(long)(n0 / 128) * m.sr + kb];
#pragma unroll
for (int t = 0; t < R; ++t) {
auto raw = r4d_fp8::acc_zero();
#pragma unroll
for (int k = 0; k < 128; k += 16)
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, t * 16, k, lane),
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j;
const float scale = r < m.T ? as[(long)r * m.asr + kb] * weight_scale : 0;
acc[t][j] += raw[j] * scale;
}
}
__syncthreads();
}
#pragma unroll
for (int t = 0; t < R; ++t)
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int r = first + t * 16 + h * 8 + j, c = n0 + wave * 16 + (lane & 15);
if (r < m.T) y[(long)r * m.yr + c] = f32_to_bf16(acc[t][j]);
}
}
// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a
// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C
// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical;
// the choice is speed only.
struct Form {
int kind = 0, r = 0, s = 0, c = 1;
}; // kind 0 legacy, 1 decode, 2 rows
constexpr int kLdsCap = 64 * 1024;
long decode_lds(int R, int S, int C, long KB, bool stage) {
return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4;
}
// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers
// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last
// and the exchange fits the LDS.
Form decode_plan(long N, long K, long T) {
Form f;
f.kind = 1;
const long tiles = (T + 15) / 16, kb = K / 128;
f.r = (int)(tiles >= 3 ? 3 : tiles);
const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r);
f.s = 1;
while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 &&
decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap)
f.s *= 2;
return f;
}
Form dense_form(long N, long K, long T) {
if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) {
if (!std::strcmp(e, "legacy")) return Form{};
if (!std::strncmp(e, "rows", 4)) {
Form f;
f.kind = 2;
f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4;
return f;
}
if (!std::strncmp(e, "decode", 6)) {
Form f = decode_plan(N, K, T);
int r = 0, s = 0, c = 1;
const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c);
if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 &&
(c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) {
f.r = r;
f.s = s;
f.c = c;
}
return f;
}
}
// Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16
// rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512
// (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65
// to 128 rows decode1x8 holds at K 4096 and the row tiles win at K 2048 and below. Among the
// row tiles (and past 128 rows) the 16-row tile beats the 64-row tile by a quarter; the 32-row
// tile wins at N 4096.
const long kb = K / 128;
Form f;
const bool rows =
T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096);
if (!rows) {
f.kind = 1;
f.r = 1;
f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1;
f.s = 8;
while (f.s > 1 && f.s > kb) f.s /= 2;
return f;
}
f.kind = 2;
f.r = T > 64 && N >= 4096 ? 2 : 1;
return f;
}
template <int R>
int emit_rows(RadStream stream, const uint8_t* xa, const float* xsa, const uint8_t* wa,
const float* wsa, uint16_t* ya, const Meta& m) {
return R4D_EMIT(stream, fp8_f32scale_rows<R>,
dim3(m.N / 64, (unsigned)((m.T + R * 16 - 1) / (R * 16))), dim3(128), 0, xa,
xsa, wa, wsa, ya, m);
}
int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const RadTensor& w,
const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) {
*done = false;
const Form f = dense_form(m.N, m.K, m.T);
if (!f.kind || m.wr % 16 || m.ar % 16 ||
(reinterpret_cast<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(w.data)) % 16)
return RAD_OK;
const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data;
const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data;
uint16_t* ya = (uint16_t*)y.data;
if (f.kind == 1) {
const long kb = m.K / 128;
const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap;
const long lds = decode_lds(f.r, f.s, f.c, kb, stage);
if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK;
*done = true;
const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)),
block(32 * f.s);
#define F32S_DECODE(R_, C_) \
if (f.r == R_ && f.c == C_) \
return R4D_EMIT(stream, (fp8_f32scale_decode<R_, C_>), grid, block, (uint32_t)lds, xa, \
xsa, wa, wsa, ya, m, stage);
F32S_DECODE(1, 1)
F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2)
F32S_DECODE(1, 4) F32S_DECODE(2, 4)
#undef F32S_DECODE
* done = false;
return RAD_OK;
}
*done = true;
if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m);
return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m);
}
int body(const RadArgs* a, RadStream stream, bool grouped) {
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4];
const int64_t N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX ||
r4d_geti_or(a, "group", 0) != 128 || r4d_geti_or(a, "pb1", 0) > 0)
return RAD_E_SHAPE;
if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 ||
ws.dtype != RAD_F32 || y.dtype != RAD_BF16)
return RAD_E_DTYPE;
if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 ||
y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 ||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
return RAD_E_SHAPE;
const int rank = grouped ? 3 : 2;
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
ws.stride[rank - 1] != 1)
return RAD_E_SHAPE;
Meta m{};
m.ar = x.stride[0];
m.asr = xs.stride[0];
m.yr = y.stride[0];
m.wr = w.stride[rank - 2];
m.sr = ws.stride[rank - 2];
m.T = (int)y.shape[0];
m.N = N;
m.K = K;
const void *w1 = nullptr, *s1 = nullptr;
const int *sorted = nullptr, *offsets = nullptr;
if (grouped) {
m.experts = r4d_geti_or(a, "n_expert", 0);
m.topk = r4d_geti_or(a, "top_k", 0);
const char* order = r4d_gets(a, "a_order");
m.sorted_a = order && !std::strcmp(order, "sorted");
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
!so.data || !st.data || !off.data)
return RAD_E_SHAPE;
m.wstep[0] = w.stride[0];
m.wstep[1] = wo.stride[0];
m.sstep[0] = ws.stride[0] * 4;
m.sstep[1] = so.stride[0] * 4;
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
w1 = wo.data;
s1 = so.data;
sorted = (const int*)st.data;
offsets = (const int*)off.data;
} else {
if (x.shape[0] != m.T) return RAD_E_SHAPE;
m.wstep[0] = N * m.wr;
m.sstep[0] = (N / 128) * m.sr * 4;
bool done = false;
const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done);
if (done || rc < 0) return rc;
}
m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16;
if (grouped) {
/* The expert-major form at every routed-row count unless the environment bounds or
* refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8
* slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and
* under 128 routed rows four tiles a block on top; at down's K of 256 every variant
* reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage
* and tiles can be pinned, for the microbenchmark. */
auto env_long = [](const char* name, long dflt) {
const char* v = std::getenv(name);
return v && *v ? std::strtol(v, nullptr, 10) : dflt;
};
const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS");
const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1);
if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) {
const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256);
const long tiles =
env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1);
#define F8_EXPERTS(SK, C) \
R4D_EMIT(stream, (fp8_f32scale_experts<SK, C>), \
dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \
offsets, (uint16_t*)y.data, m)
if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1);
#undef F8_EXPERTS
}
}
if (grouped)
return R4D_EMIT(stream, fp8_f32scale<true>, dim3(N / 64, (m.T + m.tile - 1) / m.tile),
dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data,
ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m);
return R4D_EMIT(stream, fp8_f32scale<false>, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted,
offsets, (uint16_t*)y.data, m);
}
int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); }
int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); }
}
extern "C" int r4d_rad_fp8_f32scale(const RadArgs* a, RadStream stream) { return dense(a, stream); }
extern "C" int r4d_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) {
return grouped(a, stream);
}
extern "C" int r4d_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e,
const int* sel, const RadTensor*, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 ||
e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 ||
e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 ||
sel[0] != (operand == 3 || operand == 7 ? 1 : 0))
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout.
}
+87 -1
View File
@@ -1,7 +1,7 @@
/* r4d_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch.
*
* `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops
* it replaces executable. Eleven of libr4d's fusions have no libref kernel, so this is their only
* it replaces executable. Most of libr4d's fusions have no libref kernel, so this is their only
* oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows,
* and expects identical bytes, not a tolerance.
*
@@ -149,6 +149,16 @@ struct Step {
return *this;
}
Step& pf64(const char* key, double v) {
if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
RadParam q{};
q.key = key;
q.kind = RAD_P_F64;
q.dval = v;
s->p[s->n_p++] = q;
return *this;
}
Step& pstr(const char* key, const char* v) {
if (!v || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; }
RadParam q{};
@@ -306,6 +316,82 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
}
}
/* ==========================================================================================
* swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass.
* (kernel: libr4d/r4d_glm.hip, swiglu_clamped_quant_kernel)
*
* Operands: [0] gate_up [1] q [2] scale [3] out_bf16?
*
* Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are
* quant_act_fp8's over that rounded value, so the chain is the two rows with the product between.
*/
extern "C" int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED;
const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0);
switch (step) {
case 0: {
Step s(out, "swiglu_clamped");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype");
return s.wire({ 0, mid }); /* gate_up, y */
}
case 1: {
Step s(out, "quant_act_fp8");
s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype");
return s.wire({ mid, 1, 2 }); /* x, q, scale */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill.
* (kernel: libr4d/r4d_glm.hip, router_sigmoid_scatter_kernel)
*
* Operands: [0] logits [1] bias [2] ids [3] weights [4] sorted_tok [5] expert_offset
* [6] expert_count [7] gate? [8] inverse?
*
* The sort runs over this rank's slice, so `moe_scatter`'s `n_expert` is the fused op's `n_local`;
* with the inverse it is `moe_scatter_inv`. The fill steps in only with the gate.
*/
extern "C" int r4d_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p, uint64_t present,
int step, RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
const int64_t ne = pi(p, n_p, "n_expert"), nl = pi(p, n_p, "n_local", ne);
if (ne <= 0 || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED;
switch (step) {
case 0: {
Step s(out, "router_sigmoid_topk");
s.mirror(p, n_p, "M").mirror(p, n_p, "n_expert").mirror(p, n_p, "top_k")
.mirror(p, n_p, "norm").mirror(p, n_p, "route_scale").mirror(p, n_p, "dtype");
return s.wire({ 0, 1, 2, 3 }); /* logits, bias, ids, weights */
}
case 1: {
const bool inv = RAD_FUSE_HAS(present, 8) != 0;
Step s(out, inv ? "moe_scatter_inv" : "moe_scatter");
s.mirror(p, n_p, "M").pint("n_expert", nl).mirror(p, n_p, "top_k")
.mirror_opt(p, n_p, "expert_base").mirror_opt(p, n_p, "protect");
if (inv) return s.wire({ 2, 4, 5, 6, 8 }); /* expert_ids, sorted_tok, offset, count, inverse */
return s.wire({ 2, 4, 5, 6 }); /* expert_ids, sorted_tok, offset, count */
}
case 2: {
if (!RAD_FUSE_HAS(present, 7)) return RAD_E_NOTFOUND;
Step s(out, "fill");
s.mirror(p, n_p, "M").pint("n", 1).pstr("dtype", "bf16").pf64("value", 1.0);
return s.wire({ 7 }); /* y */
}
default:
return RAD_E_NOTFOUND;
}
}
/* ==========================================================================================
* gate_quant_fp8 -- the same epilogue with the gate in its own operand.
* (kernel: libr4d/r4d_fused_quant_fp8.hip, gate_quant_fp8_kernel)
+471
View File
@@ -0,0 +1,471 @@
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_moe_sort.h"
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace {
__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp,
long yp, int n, int k) {
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), r = blockIdx.y;
if (col >= n) return;
float sum = 0;
for (int j = lane; j < k; j += 32)
sum = fmaf(bf16_to_f32(x[(long)r * xp + j]), w[(long)col * wp + j], sum);
#pragma unroll
for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32);
if (!lane) y[(long)r * yp + col] = sum;
}
// One wave computes R rows by C columns, so each loaded weight serves R rows and each input
// C columns. Every output keeps gemm_nt_f32_kernel's arithmetic: lane l accumulates
// k = l, l+32, ... in ascending order with fmaf, then the same xor butterfly. Tail rows and
// columns read a clamped valid address and are never stored.
template <int R, int C>
__global__ void __launch_bounds__(128)
gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp,
int m, int n, int k) {
const int lane = threadIdx.x & 31, c0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * C,
r0 = blockIdx.y * R;
if (c0 >= n) return;
const uint16_t* xr[R];
const float* wc[C];
#pragma unroll
for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp;
#pragma unroll
for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp;
float sum[R][C];
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = 0;
for (int j = lane; j < k; j += 32) {
float weight[C];
#pragma unroll
for (int c = 0; c < C; ++c) weight[c] = wc[c][j];
#pragma unroll
for (int q = 0; q < R; ++q) {
const float v = bf16_to_f32(xr[q][j]);
#pragma unroll
for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[c], sum[q][c]);
}
}
#pragma unroll
for (int q = 0; q < R; ++q)
#pragma unroll
for (int c = 0; c < C; ++c) {
#pragma unroll
for (int mask = 16; mask; mask >>= 1) sum[q][c] += __shfl_xor(sum[q][c], mask, 32);
}
if (lane) return;
#pragma unroll
for (int q = 0; q < R; ++q)
if (r0 + q < m)
#pragma unroll
for (int c = 0; c < C; ++c)
if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c];
}
// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or
// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only.
struct F32Tile {
int r, c;
};
constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 },
{ 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } };
F32Tile f32_tile(long rows, long n) {
if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) {
if (!std::strcmp(e, "legacy")) return { 0, 0 };
int r = 0, c = 0;
if (std::sscanf(e, "%dx%d", &r, &c) == 2)
for (const F32Tile& t : kF32Tiles)
if (t.r == r && t.c == c) return t;
}
// Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains
// 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A
// projection of a few columns has too few waves for wide tiles at any M.
if (n <= 8) return { 4, 1 };
if (rows <= 1) return { 0, 0 };
if (rows <= 2) return { 2, 1 };
if (rows < 16) return { 4, 1 };
if (rows < 64) return { 4, 4 };
return { 8, 4 };
}
template <int R, int C>
int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y,
long n, long k) {
const long m = x.shape[0];
return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel<R, C>),
dim3((unsigned)((n + 4 * C - 1) / (4 * C)), (unsigned)((m + R - 1) / R)),
dim3(128), 0, (const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
x.stride[0], w.stride[0], y.stride[0], (int)m, (int)n, (int)k);
}
int gemm_f32_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
const long n = r4d_geti_or(a, "N", 0), k = r4d_geti_or(a, "K", 0);
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
if (n < 1 || n > 512 || k < 1 || k > 16384 || x.rank != 2 || w.rank != 2 || y.rank != 2 ||
x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != k || w.shape[0] != n ||
w.shape[1] != k || y.shape[0] != x.shape[0] || y.shape[1] != n || x.stride[1] != 1 ||
w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k ||
y.stride[0] < n)
return RAD_E_SHAPE;
const F32Tile t = f32_tile(x.shape[0], n);
#define R4D_F32_TILE(R, C) \
if (t.r == R && t.c == C) return gemm_f32_tile<R, C>(stream, x, w, y, n, k);
R4D_F32_TILE(1, 1)
R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2)
R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4)
#undef R4D_F32_TILE
return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0,
(const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k);
}
__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids,
float* weights, long lp, long bp, long ip, long wp, int ne,
int k, int norm, float factor) {
__shared__ float probabilities[512], ranking[512];
const int r = blockIdx.x;
for (int e = threadIdx.x; e < ne; e += 256) {
const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e]));
probabilities[e] = p;
ranking[e] = p + bias[(long)e * bp];
}
__syncthreads();
if (threadIdx.x) return;
int index[32];
float chosen[32], total = 0;
for (int j = 0; j < k; ++j) {
int best = 0;
for (int e = 1; e < ne; ++e)
if (ranking[e] > ranking[best]) best = e;
index[j] = best;
chosen[j] = probabilities[best];
total += chosen[j];
ranking[best] = -INFINITY;
}
const float mult = norm ? factor / (total + 1e-20f) : factor;
for (int j = 0; j < k; ++j) {
ids[(long)r * ip + j] = index[j];
weights[(long)r * wp + j] = chosen[j] * mult;
}
}
// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the
// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict
// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks
// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are
// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here,
// while the scan takes expert 0 first when its rank is NaN.
// OWN is a template bound because the keys are registers; a lane-derived trip count would index
// them divergently, which gfx12 lowers to a v_movrels loop.
__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) {
uint32_t u = __float_as_uint(rank);
if (u == 0x80000000u) u = 0;
const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u);
return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull;
}
__device__ __forceinline__ unsigned long long router_wave_max(unsigned long long b) {
unsigned long long o;
o = r4d_xor_lane_u64<16>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<8>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<4>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<2>(b);
b = b > o ? b : o;
o = r4d_xor_lane_u64<1>(b);
b = b > o ? b : o;
return b;
}
// One row in one wave, from any grid: the standalone select and the fused one below run this. A
// lane below `k` returns its slot's expert as written to `ids`.
template <int OWN>
__device__ __forceinline__ int router_sigmoid_row(const float* logits, const float* bias, int* ids,
float* weights, long lp, long bp, long ip,
long wp, int r, int ne, int k, int norm,
float factor, int lane) {
float p[OWN];
unsigned long long key[OWN];
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const int e = lane + 32 * i, s = e < ne ? e : 0;
p[i] = 1.0f / (1.0f + expf(-logits[(long)r * lp + s]));
key[i] = e < ne ? router_rank_key(p[i] + bias[(long)s * bp], e) : 0ull;
}
unsigned long long below = ~0ull, mine = 0;
for (int j = 0; j < k; ++j) {
unsigned long long best = 0;
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const unsigned long long c = key[i] < below ? key[i] : 0ull;
best = c > best ? c : best;
}
best = router_wave_max(best);
if (lane == j) mine = best;
below = best;
}
const int e = mine ? (int)~(uint32_t)mine : 0;
float chosen = 0;
#pragma unroll
for (int i = 0; i < OWN; ++i) {
const float v = __shfl(p[i], e & 31, 32);
if ((e >> 5) == i) chosen = v;
}
float total = 0;
for (int j = 0; j < k; ++j)
total += __int_as_float(__builtin_amdgcn_readlane(__float_as_int(chosen), j));
const float mult = norm ? factor / (total + 1e-20f) : factor;
if (lane < k) {
ids[(long)r * ip + lane] = e;
weights[(long)r * wp + lane] = chosen * mult;
}
return e;
}
template <int OWN>
__global__ void __launch_bounds__(128)
router_sigmoid_wave_kernel(const float* logits, const float* bias, int* ids, float* weights,
long lp, long bp, long ip, long wp, int m, int ne, int k, int norm,
float factor) {
const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5);
if (r >= m) return;
(void)router_sigmoid_row<OWN>(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, norm,
factor, lane);
}
// router_sigmoid_topk, then moe_scatter over its ids, then the `fill` of an ungated shared arm's
// gate with 1, in one workgroup. Rows wrap over the NW waves; each leaves its slots in the sort's
// LDS list instead of re-reading `ids`. A slot carries the expert its row wrote, including the
// expert 0 of a row with fewer finite ranks than top_k, so every output equals the three launches'.
// INV also writes the inverse, as moe_scatter_inv does.
template <int OWN, uint32_t NW, bool INV>
__global__ void __launch_bounds__(NW * 32)
router_sigmoid_scatter_kernel(const float* logits, const float* bias, int* ids, float* weights,
int32_t* sorted, int32_t* off, int32_t* cnt, uint16_t* gate,
int32_t* inv, long lp, long bp, long ip, long wp, long gp, int m,
int ne, int n_local, int k, int norm, float factor, int base,
r4d_moesort::Protect prot) {
__shared__ r4d_moesort::ScatterLds<NW> sl;
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
for (int e = threadIdx.x; e < n_local; e += (int)(NW * 32)) sl.cnt[e] = 0;
for (int r = wave; r < m; r += (int)NW) {
const int e = router_sigmoid_row<OWN>(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k,
norm, factor, lane) -
base;
if (lane < k)
sl.e[r * k + lane] =
e >= 0 && e < n_local ? r4d_moesort::sort_place(e, (uint32_t)n_local, prot) : -1;
if (gate && !lane) gate[(long)r * gp] = f32_to_bf16(1.0f);
}
lds_barrier();
r4d_moesort::scatter_small_place<NW, INV>(sorted, off, cnt, (uint32_t)(m * k),
(uint32_t)n_local, sl, inv);
}
int router_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 4) return RAD_E_INVAL;
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0);
const float factor = (float)r4d_getf(a, "route_scale", 0);
if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || w.dtype != RAD_F32)
return RAD_E_DTYPE;
if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 ||
!lg.data || !bias.data || !ids.data || !w.data || lg.rank != 2 || lg.shape[0] < 1 ||
lg.shape[0] > 65535 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne ||
ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || w.shape[0] != lg.shape[0] ||
ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || ids.stride[1] != 1 ||
w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || w.stride[0] < k ||
bias.stride[0] < 1)
return RAD_E_SHAPE;
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
const char* select = std::getenv("RADIANCE_ROUTER_SELECT");
if (select && !std::strcmp(select, "old"))
return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0,
(const float*)lg.data, (const float*)bias.data, (int*)ids.data,
(float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0],
(int)ne, (int)k, norm, factor);
const dim3 grid((unsigned)((lg.shape[0] + 3) / 4));
if (ne <= 9 * 32)
return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0,
(const float*)lg.data, (const float*)bias.data, (int*)ids.data,
(float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0],
(int)lg.shape[0], (int)ne, (int)k, norm, factor);
return R4D_EMIT(stream, router_sigmoid_wave_kernel<16>, grid, dim3(128), 0,
(const float*)lg.data, (const float*)bias.data, (int*)ids.data, (float*)w.data,
lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0],
(int)ne, (int)k, norm, factor);
}
/* Operands: router_sigmoid_topk's four, moe_scatter's three outputs, then the optional gate and the
* optional inverse. The sort is the single-workgroup form, so M * top_k must fit it; a larger pass
* is refused rather than served at another cost. */
int router_scatter_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
const RadTensor *sorted = &a->t[4], *off = &a->t[5], *cnt = &a->t[6];
const RadTensor* gate = a->n_t > 7 ? r4d_opt(a, 7) : nullptr;
const RadTensor* inv = a->n_t > 8 ? r4d_opt(a, 8) : nullptr;
const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0);
const long nl = r4d_geti_or(a, "n_local", ne), base = r4d_geti_or(a, "expert_base", 0);
const float factor = (float)r4d_getf(a, "route_scale", 0);
if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 ||
w.dtype != RAD_F32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
cnt->dtype != RAD_I32 || (gate && gate->dtype != RAD_BF16) ||
(inv && inv->dtype != RAD_I32))
return RAD_E_DTYPE;
if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 ||
!lg.data || !bias.data || !ids.data || !w.data || !sorted->data || !off->data ||
!cnt->data || lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
bias.shape[0] != ne || ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] ||
w.shape[0] != lg.shape[0] || ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 ||
ids.stride[1] != 1 || w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k ||
w.stride[0] < k || bias.stride[0] < 1)
return RAD_E_SHAPE;
const long m = lg.shape[0], T = m * k;
if (T > (long)r4d_moesort::kScatterSmall || nl < 1 || nl > ne || base < 0 || base + nl > ne ||
!r4d_contig(sorted) || !r4d_contig(off) || !r4d_contig(cnt) || r4d_numel(sorted) < T ||
r4d_numel(off) < nl + 1 || r4d_numel(cnt) < nl ||
(inv && (!r4d_contig(inv) || r4d_numel(inv) < T)))
return RAD_E_SHAPE;
long long grows = 0;
const long long gp = gate ? r4d_rows_pitch(gate, 1, &grows) : 0;
if (gate && (gp < 1 || grows < m)) return RAD_E_SHAPE;
r4d_moesort::Protect prot;
const int prc = r4d_moesort::protect_of(a, nl, &prot);
if (prc != RAD_OK) return prc;
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
// A wave a row up to 32 rows, as router_topk_scatter: the rows a wave serves run back to back.
const int nw = m <= 8 ? 8 : m <= 16 ? 16 : 32;
#define R4D_RSS_I(OWN, NW, INV) \
return R4D_EMIT(stream, (router_sigmoid_scatter_kernel<OWN, NW, INV>), dim3(1), \
dim3((NW) * 32), 0, (const float*)lg.data, (const float*)bias.data, \
(int*)ids.data, (float*)w.data, (int32_t*)sorted->data, (int32_t*)off->data, \
(int32_t*)cnt->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \
inv ? (int32_t*)inv->data : (int32_t*)nullptr, lg.stride[0], bias.stride[0], \
ids.stride[0], w.stride[0], (long)gp, (int)m, (int)ne, (int)nl, (int)k, norm, \
factor, (int)base, prot)
#define R4D_RSS(OWN, NW) \
do { \
if (inv) R4D_RSS_I(OWN, NW, true); \
R4D_RSS_I(OWN, NW, false); \
} while (0)
if (ne <= 9 * 32) {
if (nw == 8) R4D_RSS(9, 8u);
if (nw == 16) R4D_RSS(9, 16u);
R4D_RSS(9, 32u);
}
if (nw == 8) R4D_RSS(16, 8u);
if (nw == 16) R4D_RSS(16, 16u);
R4D_RSS(16, 32u);
#undef R4D_RSS
#undef R4D_RSS_I
}
__global__ void swiglu_clamped_kernel(const uint16_t* gu, uint16_t* y, long gp, long yp, int n,
float limit) {
const long r = blockIdx.x;
const int i = blockIdx.y * 256 + threadIdx.x;
if (i >= n) return;
const float g = fminf(bf16_to_f32(gu[r * gp + i]), limit);
const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit);
y[r * yp + i] = f32_to_bf16((g / (1.0f + expf(-g))) * u);
}
int clamped_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 2) return RAD_E_INVAL;
const auto &gu = a->t[0], &y = a->t[1];
const long n = r4d_geti_or(a, "n", 0);
const float limit = (float)r4d_getf(a, "limit", 0);
if (gu.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
if (n < 1 || n > INT_MAX / 2 || !std::isfinite(limit) || limit <= 0 || !gu.data || !y.data ||
gu.rank != 2 || y.rank != 2 || y.shape[0] < 1 || y.shape[0] > 65535 ||
gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || y.shape[1] != n || gu.stride[1] != 1 ||
y.stride[1] != 1 || gu.stride[0] < 2 * n || y.stride[0] < n)
return RAD_E_SHAPE;
return R4D_EMIT(stream, swiglu_clamped_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0,
(const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], (int)n,
limit);
}
// swiglu_clamped, then quant_act_fp8 over its product, in one pass: a wave per (row, 128 columns),
// four columns a lane, as the quantiser maps them. Each element is swiglu_clamped_kernel's
// expression and each group quant_act_fp8_kernel's. The product is rounded to bf16 and read back
// before the absmax because the separate quantiser reads the stored bf16 bytes.
__global__ void __launch_bounds__(256)
swiglu_clamped_quant_kernel(const uint16_t* gu, uint16_t* y, uint8_t* q, float* s, long gp,
long yp, long qp, long sp, int n, int nkb, float limit) {
const long r = blockIdx.x;
const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
for (int kb = wave; kb < nkb; kb += (int)(blockDim.x >> 5)) {
const int c0 = kb * 128 + lane * 4;
float v[4], m = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) {
const int c = c0 + j;
v[j] = 0.0f;
if (c < n) {
const float g = fminf(bf16_to_f32(gu[r * gp + c]), limit);
const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + c]), -limit), limit);
const uint16_t h = f32_to_bf16((g / (1.0f + expf(-g))) * u);
if (y) y[r * yp + c] = h;
v[j] = bf16_to_f32(h);
}
}
#pragma unroll
for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j]));
m = r4d_wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f;
if (!lane) s[r * sp + kb] = sc;
const float inv = 1.0f / sc;
int pk = 0;
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false);
pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f),
fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true);
if (c0 < n) *(uint32_t*)(q + r * qp + c0) = (uint32_t)pk;
}
}
/* Operands: gate_up [M, 2n], q [M, n] E4M3, scale [M, ceil(n/128)] f32, out_bf16 [M, n] optional.
* n a multiple of 4 and group 128, as quant_act_fp8 requires. */
int clamped_quant_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
const auto &gu = a->t[0], &q = a->t[1], &sc = a->t[2];
const RadTensor* y = a->n_t > 3 ? r4d_opt(a, 3) : nullptr;
const long n = r4d_geti_or(a, "n", 0), nkb = (n + 127) / 128;
const float limit = (float)r4d_getf(a, "limit", 0);
if (gu.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || sc.dtype != RAD_F32 ||
(y && y->dtype != RAD_BF16))
return RAD_E_DTYPE;
if (r4d_geti_or(a, "group", 128) != 128 || n < 4 || n % 4 || n > INT_MAX / 2 ||
!std::isfinite(limit) || limit <= 0 || !gu.data || !q.data || !sc.data || gu.rank != 2 ||
q.rank != 2 || sc.rank != 2 || gu.shape[0] < 1 || gu.shape[0] > 65535 ||
gu.shape[1] != 2 * n || q.shape[0] != gu.shape[0] || q.shape[1] != n ||
sc.shape[0] != gu.shape[0] || sc.shape[1] != nkb || gu.stride[1] != 1 || q.stride[1] != 1 ||
sc.stride[1] != 1 || gu.stride[0] < 2 * n || q.stride[0] < n || sc.stride[0] < nkb ||
(y && (y->rank != 2 || y->shape[0] != gu.shape[0] || y->shape[1] != n ||
y->stride[1] != 1 || y->stride[0] < n)))
return RAD_E_SHAPE;
// A wave a group, at most eight: a row of GLM's TP8 expert width is two groups.
const unsigned thr = (unsigned)(nkb < 8 ? nkb : 8) * 32u;
return R4D_EMIT(stream, swiglu_clamped_quant_kernel, dim3((unsigned)gu.shape[0]), dim3(thr), 0,
(const uint16_t*)gu.data, y ? (uint16_t*)y->data : (uint16_t*)nullptr,
(uint8_t*)q.data, (float*)sc.data, gu.stride[0], y ? (long)y->stride[0] : 0L,
q.stride[0], sc.stride[0], (int)n, (int)nkb, limit);
}
}
extern "C" int r4d_rad_swiglu_clamped(const RadArgs* a, RadStream stream) {
return clamped_body(a, stream);
}
extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) {
return clamped_quant_body(a, stream);
}
extern "C" int r4d_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) {
return gemm_f32_body(a, stream);
}
extern "C" int r4d_rad_router_sigmoid_topk(const RadArgs* a, RadStream stream) {
return router_body(a, stream);
}
extern "C" int r4d_rad_router_sigmoid_topk_scatter(const RadArgs* a, RadStream stream) {
return router_scatter_body(a, stream);
}
+491
View File
@@ -0,0 +1,491 @@
/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots.
* One wave owns one, two or four value rows and keeps each row's 128-wide state in four
* registers per lane.
* Prefill uses the same recurrence and commits only its final state. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include <climits>
#include <cstdlib>
#include <cstring>
namespace {
struct KdaMeta {
int row[5], head[5];
long os0, os1, ss0, ss1, ss2;
long is0, is1, cs0, as0, hs0;
int tokens, slots, width, verify, anchor;
float lower, eps, scale;
};
struct KdaJob : KdaMeta {
const uint16_t* input[5];
const float *alog, *bias;
float* state;
uint16_t* out;
const int *idx, *cu, *accepted, *init;
};
__device__ float sum(float v) {
for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32);
return __shfl(v, 0, 32);
}
/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every
* other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits
* without the broadcast. */
template <bool Dpp>
__device__ __forceinline__ float wave_total(float v) {
if constexpr (Dpp)
return r4d_wave_sum(v);
else
return sum(v);
}
__device__ long factor_offset(long base, int logical, long pitch) {
return base + (logical / 128) * pitch + (logical % 128);
}
/* Separate dispatch: all old factor reads finish before the next window overwrites them. */
template <bool Dpp>
__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted,
const int* init, KdaMeta m) {
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
seq = blockIdx.z;
const int anchor = idx[(long)seq * m.is0],
scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1];
if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch)
return;
const long fb = (long)scratch * m.ss0 + (long)head * m.ss1;
const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2;
if (init && !init[(long)seq * m.hs0]) {
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0;
return;
}
const float count = state[fb];
const int na = accepted ? accepted[(long)seq * m.as0] : 1;
if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 ||
(count > 0 && na > count))
return;
float s[4];
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32];
for (int t = 0; t < (count > 0 ? na : 0); ++t) {
const int f = 1 + t * 385;
float k[4], prediction = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + d * 32;
k[d] = state[factor_offset(fb, f + c, m.ss2)];
s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)];
prediction += s[d] * k[d];
}
const float delta =
state[factor_offset(fb, f + 384, m.ss2)] *
(state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total<Dpp>(prediction));
#pragma unroll
for (int d = 0; d < 4; ++d) s[d] += delta * k[d];
}
#pragma unroll
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d];
}
__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
const uint16_t* g, const uint16_t* beta, const float* alog,
const float* bias, float* state_ptr, uint16_t* out,
const int* idx, const int* cu, const int* accepted_ptr,
const int* init, KdaMeta meta) {
KdaJob j{};
static_cast<KdaMeta&>(j) = meta;
j.input[0] = q;
j.input[1] = k;
j.input[2] = v;
j.input[3] = g;
j.input[4] = beta;
j.alog = alog;
j.bias = bias;
j.state = state_ptr;
j.out = out;
j.idx = idx;
j.cu = cu;
j.accepted = accepted_ptr;
j.init = init;
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5);
const int head = blockIdx.y, seq = blockIdx.z;
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
accepted > (j.anchor ? 32 : j.width) ||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
return;
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
if (read >= j.slots) return;
if (read < 0) {
if (!lane)
for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0;
return;
}
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
float state[4];
#pragma unroll
for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0;
const float gain = expf(j.alog[head]);
for (int t = begin; t < end; ++t) {
float q[4], k[4], decay[4], sq = 0, sk = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int channel = lane + d * 32;
q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]);
k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]);
sq += q[d] * q[d];
sk += k[d] * k[d];
const float raw =
bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]);
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel]))));
}
const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps);
const float beta =
1.0f /
(1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]])));
float predicted = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
q[d] *= qi;
k[d] *= ki;
state[d] *= decay[d];
predicted += state[d] * k[d];
}
predicted = sum(predicted);
const float value =
bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]);
if (j.anchor && j.verify) {
const int f = 1 + (t - begin) * 385;
if (e == 0) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + 32 * d;
j.state[factor_offset(fb, f + c, j.ss2)] = k[d];
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
}
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta;
}
if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value;
}
const float delta = beta * (value - predicted);
float result = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
state[d] += delta * k[d];
result += state[d] * q[d];
}
result = sum(result);
if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result);
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
if (write >= 0 && write < j.slots) {
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
#pragma unroll
for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d];
}
}
}
if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
}
/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do
* not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each
* row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda).
* With Prefetch the next token's operands are loaded while this one is reduced. */
template <int R, bool Prefetch>
__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
const uint16_t* g, const uint16_t* beta, const float* alog,
const float* bias, float* state_ptr, uint16_t* out, const int* idx,
const int* cu, const int* accepted_ptr, const int* init,
KdaMeta meta) {
static_assert(32 % R == 0, "the 128 value rows split evenly over the waves");
KdaJob j{};
static_cast<KdaMeta&>(j) = meta;
j.input[0] = q;
j.input[1] = k;
j.input[2] = v;
j.input[3] = g;
j.input[4] = beta;
j.alog = alog;
j.bias = bias;
j.state = state_ptr;
j.out = out;
j.idx = idx;
j.cu = cu;
j.accepted = accepted_ptr;
j.init = init;
const int lane = threadIdx.x & 31, e0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * R;
const int head = blockIdx.y, seq = blockIdx.z;
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
accepted > (j.anchor ? 32 : j.width) ||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
return;
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
if (read >= j.slots) return;
uint16_t* const out_row = j.out + (long)head * j.os1 + e0;
if (read < 0) {
if (lane < R)
for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0;
return;
}
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
float state[R][4];
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0;
const float gain = expf(j.alog[head]);
float shift[4];
#pragma unroll
for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d];
const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane;
const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane;
const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0;
const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane;
const uint16_t* const bb = j.input[4] + (long)head * j.head[4];
struct Token {
uint32_t q[4], k[4], g[4], beta, value[R];
};
auto fetch = [&](int t, Token& o) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d);
o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d);
o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d);
}
o.beta = ldg_u16(bb + (long)t * j.row[4]);
#pragma unroll
for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r);
};
Token cur;
if (Prefetch && begin < end) fetch(begin, cur);
for (int t = begin; t < end; ++t) {
[[maybe_unused]] Token next;
/* The last token loads itself again rather than a row past `end`. */
if constexpr (Prefetch)
fetch(t + 1 < end ? t + 1 : t, next);
else
fetch(t, cur);
float qv[4], kv[4], decay[4], sq = 0, sk = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] = bf16w_lo(cur.q[d]);
kv[d] = bf16w_lo(cur.k[d]);
sq += qv[d] * qv[d];
sk += kv[d] * kv[d];
const float raw = bf16w_lo(cur.g[d]);
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d]))));
}
const float qi = j.scale * rsqrtf(r4d_wave_sum(sq) + j.eps),
ki = rsqrtf(r4d_wave_sum(sk) + j.eps);
const float b = 1.0f / (1.0f + expf(-bf16w_lo(cur.beta)));
float predicted[R];
#pragma unroll
for (int r = 0; r < R; ++r) predicted[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
qv[d] *= qi;
kv[d] *= ki;
#pragma unroll
for (int r = 0; r < R; ++r) {
state[r][d] *= decay[d];
predicted[r] += state[r][d] * kv[d];
}
}
float value[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
predicted[r] = r4d_wave_sum(predicted[r]);
value[r] = bf16w_lo(cur.value[r]);
}
if (j.anchor && j.verify) {
const int f = 1 + (t - begin) * 385;
if (e0 == 0) {
#pragma unroll
for (int d = 0; d < 4; ++d) {
const int c = lane + 32 * d;
j.state[factor_offset(fb, f + c, j.ss2)] = kv[d];
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
}
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b;
}
if (!lane) {
#pragma unroll
for (int r = 0; r < R; ++r)
j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r];
}
}
float result[R];
#pragma unroll
for (int r = 0; r < R; ++r) {
const float delta = b * (value[r] - predicted[r]);
result[r] = 0;
#pragma unroll
for (int d = 0; d < 4; ++d) {
state[r][d] += delta * kv[d];
result[r] += state[r][d] * qv[d];
}
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
result[r] = r4d_wave_sum(result[r]);
if (lane == r) mine = result[r];
}
if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine);
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
if (write >= 0 && write < j.slots) {
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2;
#pragma unroll
for (int r = 0; r < R; ++r)
#pragma unroll
for (int d = 0; d < 4; ++d)
j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d];
}
}
if constexpr (Prefetch) cur = next;
}
if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
}
template <class Pitch>
bool headed(const RadTensor& t, long tokens, long heads, long dim, Pitch* row, Pitch* head) {
if (!t.data || t.dtype != RAD_BF16 || t.shape[0] != tokens || t.stride[0] > INT_MAX ||
(t.rank == 3 && t.stride[1] > INT_MAX))
return false;
if (t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim && t.stride[2] == 1 &&
t.stride[1] >= dim && t.stride[0] >= heads * t.stride[1]) {
*row = t.stride[0];
*head = t.stride[1];
return true;
}
if (t.rank == 2 && t.shape[1] == heads * dim && t.stride[1] == 1 &&
t.stride[0] >= heads * dim) {
*row = t.stride[0];
*head = dim;
return true;
}
return false;
}
bool vector(const RadTensor& t, uint32_t dt, long n) {
return t.data && t.dtype == dt && t.rank == 1 && t.shape[0] >= n && t.stride[0] == 1;
}
int body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 13) return RAD_E_INVAL;
const long H = r4d_geti_or(a, "heads", 0);
if (H < 1 || H > 65535 || r4d_geti_or(a, "head_k", 0) != 128 ||
r4d_geti_or(a, "head_v", 0) != 128)
return RAD_E_SHAPE;
KdaJob j{};
const auto &state = a->t[7], &idx = a->t[8], &cu = a->t[9];
const long tokens = a->t[0].shape[0];
if (tokens < 1 || tokens > INT_MAX || state.rank != 4 || state.dtype != RAD_F32 ||
!state.data || state.shape[0] < 1 || state.shape[0] > INT_MAX || state.shape[1] != H ||
state.shape[2] != 128 || state.shape[3] != 128 || state.stride[3] != 1 ||
state.stride[2] < 128 || state.stride[1] < 128 * state.stride[2] ||
state.stride[0] < H * state.stride[1] || cu.rank != 1 || cu.dtype != RAD_I32 || !cu.data ||
cu.shape[0] < 2 || cu.shape[0] > 65536 || cu.stride[0] < 1 || idx.rank != 2 ||
idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < cu.shape[0] - 1 || idx.shape[1] < 1 ||
idx.shape[1] > INT_MAX || idx.stride[1] < 1 || idx.stride[0] < idx.shape[1] * idx.stride[1])
return RAD_E_SHAPE;
for (int i = 0; i < 5; ++i) {
if (!headed(a->t[i], tokens, H, i == 4 ? 1 : 128, &j.row[i], &j.head[i]))
return RAD_E_SHAPE;
j.input[i] = (const uint16_t*)a->t[i].data;
}
if (!headed(a->t[12], tokens, H, 128, &j.os0, &j.os1) || !vector(a->t[5], RAD_F32, H) ||
!vector(a->t[6], RAD_F32, H * 128))
return RAD_E_SHAPE;
const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11);
if ((accepted && !vector(*accepted, RAD_I32, cu.shape[0] - 1)) ||
(init && !vector(*init, RAD_I32, cu.shape[0] - 1)))
return RAD_E_SHAPE;
const char* mode = r4d_gets(a, "mode");
if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) return RAD_E_INVAL;
j.verify = !std::strcmp(mode, "verify");
const char* form = r4d_gets(a, "state_form");
j.anchor = form && !std::strcmp(form, "anchor");
if (form && !j.anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
if (j.anchor && idx.shape[1] < 2) return RAD_E_SHAPE;
j.lower = (float)r4d_getf(a, "lower_bound", 0);
j.eps = (float)r4d_getf(a, "l2_eps", 0);
j.scale = (float)r4d_getf(a, "scale", 1);
if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 ||
!std::isfinite(j.scale))
return RAD_E_SHAPE;
j.tokens = (int)tokens;
j.slots = (int)state.shape[0];
j.width = (int)idx.shape[1];
j.alog = (const float*)a->t[5].data;
j.bias = (const float*)a->t[6].data;
j.state = (float*)state.data;
j.out = (uint16_t*)a->t[12].data;
j.ss0 = state.stride[0];
j.ss1 = state.stride[1];
j.ss2 = state.stride[2];
j.idx = (const int*)idx.data;
j.is0 = idx.stride[0];
j.is1 = idx.stride[1];
j.cu = (const int*)cu.data;
j.cs0 = cu.stride[0];
if (accepted) {
j.accepted = (const int*)accepted->data;
j.as0 = accepted->stride[0];
}
if (init) {
j.init = (const int*)init->data;
j.hs0 = init->stride[0];
}
/* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest
* holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and
* RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */
const char* kform = std::getenv("RADIANCE_KDA_FORM");
const bool old = kform && !std::strcmp(kform, "old");
const unsigned seqs = (unsigned)(cu.shape[0] - 1);
if (j.anchor && j.verify) {
const int rc =
old ? R4D_EMIT(stream, kda_replay_kernel<false>, dim3(32, (unsigned)H, seqs), dim3(128),
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j))
: R4D_EMIT(stream, kda_replay_kernel<true>, dim3(32, (unsigned)H, seqs), dim3(128),
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
if (rc != RAD_OK) return rc;
}
if (old)
return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0,
j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias,
j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
const char* rows_env = std::getenv("RADIANCE_KDA_ROWS");
const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4;
const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH");
const bool prefetch = !prefetch_env || prefetch_env[0] != '0';
#define KDA_ROWS(RR, PF) \
return R4D_EMIT(stream, (kda_rows_kernel<RR, PF>), dim3(32 / RR, (unsigned)H, seqs), \
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \
static_cast<KdaMeta>(j))
if (rows == 1) {
if (prefetch) KDA_ROWS(1, true);
KDA_ROWS(1, false);
}
if (rows == 2) {
if (prefetch) KDA_ROWS(2, true);
KDA_ROWS(2, false);
}
if (prefetch) KDA_ROWS(4, true);
KDA_ROWS(4, false);
#undef KDA_ROWS
}
}
extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); }
+17
View File
@@ -1197,6 +1197,23 @@ extern "C" int r4d_rad_unrelayout_moe_w4_mod4(const RadParam* p, int n_p, int op
return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n);
}
extern "C" int r4d_rad_layout_moe_mxfp4(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout*) {
if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED;
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, 32)) return RAD_E_DTYPE;
MoeView v;
const int rc = moe_view(p, n_p, operand, &v);
if (rc != RAD_OK) return rc;
const long long N = r4d_pgeti_or(v.p, v.n, "N", 0), K = r4d_pgeti_or(v.p, v.n, "K", 0);
const bool scale = operand == 3 || operand == 7;
if (n != 1 || !pl || !sel || !selects(enc, sel, n, scale ? "scale" : "codes") ||
!dims(pl[0], N, scale ? K / 32 : K) || K % 128) return RAD_E_SHAPE;
/* The exact selected canonical plane, not a relayout: it remains readable in place
* from the container or a mapped host pool. Unsupported is the ABI spelling for that. */
return RAD_E_UNSUPPORTED;
}
extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
+731
View File
@@ -0,0 +1,731 @@
/* GLM's mHC, kept separate from the Qwen gated-residual kernels. The GLM shape
* projects in parallel before one workgroup per token forms the Sinkhorn matrix.
* Mixing weights are declared f32; activations are bf16, coefficients stay f32. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cstdint>
namespace {
__device__ float warp_sum(float v) {
for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32);
return v;
}
// The final collapsed output is large enough to hold the projection partials
// until the finishing kernel has read them. Align within each pitched row.
__device__ float* partials(uint16_t* x, long row, long pitch) {
return reinterpret_cast<float*>((reinterpret_cast<uintptr_t>(x + row * pitch) + 3) &
~uintptr_t(3));
}
// Where projection partial (row, coefficient j, chunk) lives: inside the collapsed output's rows
// (mhc_pre), or a separate [rows][chunk][stride] matrix (mhc_pre_partial writes this rank's chunks
// from `first`, mhc_pre_finish reads every rank's after the gather). Kernels differ in address only.
// `pad` clears a Dense chunk's slots past the last partial, so the gathered payload is defined.
struct InX {
uint16_t* x;
long xp;
int chunks;
__device__ float* at(long row, int j, int chunk) const {
return partials(x, row, xp) + j * chunks + chunk;
}
__device__ void pad(long, int, int) const {}
};
struct Dense {
float* p;
long pp;
int stride, first;
__device__ float* at(long row, int j, int chunk) const {
return p + row * pp + (long)(chunk - first) * stride + j;
}
__device__ void pad(long row, int last, int chunk) const {
for (int j = last + 1; j < stride; ++j) *at(row, j, chunk) = 0;
}
};
template <class Out>
__global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out, int width, int mix,
int chunk0, long hp, long fp) {
__shared__ float sums[4];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int j = blockIdx.y, chunk = chunk0 + blockIdx.x;
const long row = blockIdx.z;
float sum = 0;
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
const float v = bf16_to_f32(h[row * hp + i]);
sum += v * (j == mix ? v : fn[(long)j * fp + i]);
}
sum = warp_sum(sum);
if (!lane) sums[wave] = sum;
__syncthreads();
if (!tid) {
*out.at(row, j, chunk) = sums[0] + sums[1] + sums[2] + sums[3];
if (j == mix) out.pad(row, mix, chunk);
}
}
// Prefill reuses each F32 mixing weight across four BF16 token rows.
// Each row keeps the same accumulation and reduction order as the scalar-row path.
template <class Out>
__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width,
int mix, int chunk0, long hp, long fp, long rows) {
__shared__ float sums[4][4];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int j = blockIdx.y, chunk = chunk0 + blockIdx.x;
const long first = (long)blockIdx.z * 4;
float sum[4] = { 0, 0, 0, 0 };
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
const float weight = j == mix ? 0 : fn[(long)j * fp + i];
#pragma unroll
for (int r = 0; r < 4; ++r)
if (first + r < rows) {
const float v = bf16_to_f32(h[(first + r) * hp + i]);
sum[r] += v * (j == mix ? v : weight);
}
}
#pragma unroll
for (int r = 0; r < 4; ++r) {
sum[r] = warp_sum(sum[r]);
if (!lane) sums[r][wave] = sum[r];
}
__syncthreads();
if (!tid)
for (int r = 0; r < 4; ++r)
if (first + r < rows) {
*out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3];
if (j == mix) out.pad(first + r, mix, chunk);
}
}
// Reuse each input across four coefficients and each weight across four rows.
// All per-output K accumulation and reduction orders match the rows4 path.
template <class Out>
__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out,
int width, int mix, int chunk0, long hp, long fp,
long rows) {
__shared__ float sums[4][4][4];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int first_j = blockIdx.y * 4, chunk = chunk0 + blockIdx.x;
const long first = (long)blockIdx.z * 4;
float sum[4][4]{};
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
float weight[4];
#pragma unroll
for (int q = 0; q < 4; ++q)
weight[q] = first_j + q < mix ? fn[(long)(first_j + q) * fp + i] : 0;
#pragma unroll
for (int r = 0; r < 4; ++r)
if (first + r < rows) {
const float v = bf16_to_f32(h[(first + r) * hp + i]);
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) sum[q][r] += v * (first_j + q == mix ? v : weight[q]);
}
}
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int r = 0; r < 4; ++r) {
sum[q][r] = warp_sum(sum[q][r]);
if (!lane) sums[q][r][wave] = sum[q][r];
}
}
__syncthreads();
if (tid < 16) {
const int q = tid / 4, r = tid % 4;
if (first_j + q <= mix && first + r < rows) {
*out.at(first + r, first_j + q, chunk) =
sums[q][r][0] + sums[q][r][1] + sums[q][r][2] + sums[q][r][3];
if (first_j + q == mix) out.pad(first + r, mix, chunk);
}
}
}
// The collapsed read x[i] = sum_j pre[j] * h[j*n + i] eight columns a thread, in 16-byte loads
// and stores. Each element keeps the scalar loop's order (from zero, j ascending), so its bits
// are the same; false when the rows are not 16-byte aligned, and the caller runs its own loop.
__device__ __forceinline__ bool mix_rows_vec(const uint16_t* hr, uint16_t* xr, const float* pre,
int n, int hc, int tid, int nt) {
if ((((uintptr_t)hr | (uintptr_t)xr) & 15) || (n & 7)) return false;
for (int i = tid * 8; i < n; i += nt * 8) {
float v[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
for (int j = 0; j < hc; ++j) {
const uint4 q = *reinterpret_cast<const uint4*>(hr + (long)j * n + i);
const uint32_t w[4] = { q.x, q.y, q.z, q.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
v[e] += pre[j] * bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1))));
}
uint32_t o[4];
#pragma unroll
for (int e = 0; e < 4; ++e)
o[e] = (uint32_t)f32_to_bf16(v[2 * e]) | ((uint32_t)f32_to_bf16(v[2 * e + 1]) << 16);
*reinterpret_cast<uint4*>(xr + i) = uint4{ o[0], o[1], o[2], o[3] };
}
return true;
}
// The projection partials four slots a lane. The kernels above give each of 128 threads one slot
// s, the sum over the chunk's columns s, s+128, ... in order; here lane L holds slots 4L..4L+3,
// so a row is read 8 bytes and a weight 16 bytes a load, and one wave does a whole block's work.
// Their reduction is replayed exactly: warp_sum pairs slot l with l+16, l+8, l+4, l+2 and l+1,
// here lanes +4, +2, +1 and then the lane's own slots, and the four waves' sums, at lanes 0, 8,
// 16 and 24, are added in order. R rows and four coefficients a wave, four independent waves a
// block, no barrier.
template <class Out, int R>
__global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h, const float* fn,
Out out, int mix, int chunk0,
int count, long hp, long fp,
long rows, long items) {
const int lane = threadIdx.x & 31;
const long item = (long)blockIdx.x * 4 + (threadIdx.x >> 5);
if (item >= items) return;
const int groups = (mix + 4) / 4;
const int chunk = chunk0 + (int)(item % count);
const int first_j = (int)((item / count) % groups) * 4;
const long first = item / count / groups * R;
float acc[4][R][4]{};
for (int t = 0; t < 16; ++t) {
const int col = chunk * 2048 + t * 128 + lane * 4;
float w[4][4];
#pragma unroll
for (int q = 0; q < 4; ++q) {
const float4 v =
first_j + q < mix
? *reinterpret_cast<const float4*>(fn + (long)(first_j + q) * fp + col)
: float4{ 0, 0, 0, 0 };
w[q][0] = v.x;
w[q][1] = v.y;
w[q][2] = v.z;
w[q][3] = v.w;
}
#pragma unroll
for (int r = 0; r < R; ++r)
if (first + r < rows) {
const uint2 hv = *reinterpret_cast<const uint2*>(h + (first + r) * hp + col);
const float v[4] = { bf16_to_f32((uint16_t)hv.x),
bf16_to_f32((uint16_t)(hv.x >> 16)),
bf16_to_f32((uint16_t)hv.y),
bf16_to_f32((uint16_t)(hv.y >> 16)) };
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int u = 0; u < 4; ++u)
acc[q][r][u] += v[u] * (first_j + q == mix ? v[u] : w[q][u]);
}
}
}
#pragma unroll
for (int q = 0; q < 4; ++q)
if (first_j + q <= mix) {
#pragma unroll
for (int r = 0; r < R; ++r)
if (first + r < rows) {
float c[4];
#pragma unroll
for (int u = 0; u < 4; ++u) {
float a = acc[q][r][u];
a += __shfl_down(a, 4, 32);
a += __shfl_down(a, 2, 32);
a += __shfl_down(a, 1, 32);
c[u] = a;
}
const float e0 = c[0] + c[2], e1 = c[1] + c[3], f = e0 + e1;
const float s1 = __shfl(f, 8, 32), s2 = __shfl(f, 16, 32),
s3 = __shfl(f, 24, 32);
if (!lane) {
*out.at(first + r, first_j + q, chunk) = f + s1 + s2 + s3;
if (first_j + q == mix) out.pad(first + r, mix, chunk);
}
}
}
}
template <class In, bool VecX>
__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale,
const float* base, uint16_t* x, float* post, float* comb, int n,
int hc, int iterations, float eps, float heps, long hp, long fp,
long xp, long pp, long cp, int chunks, In in) {
__shared__ float sums[8], inverse, coefficients[80], pre[8], c[64];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const long r = blockIdx.x;
const int width = hc * n, mix = hc * (hc + 2);
float ss = 0;
for (int i = tid; !chunks && i < width; i += 256) {
const float v = bf16_to_f32(h[r * hp + i]);
ss += v * v;
}
ss = warp_sum(ss);
if (!lane) sums[wave] = ss;
__syncthreads();
if (!tid) {
float s = 0;
if (chunks)
for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i);
else
for (int i = 0; i < 8; ++i) s += sums[i];
inverse = rsqrtf(s / (float)width + eps);
}
__syncthreads();
for (int j = wave; j < mix; j += 8) {
float dot = 0;
if (chunks)
for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i);
else
for (int i = lane; i < width; i += 32)
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
dot = warp_sum(dot);
if (!lane) coefficients[j] = dot * inverse;
}
__syncthreads();
if (!tid) {
for (int j = 0; j < hc; ++j) {
pre[j] = 1.0f / (1.0f + expf(-(coefficients[j] * scale[0] + base[j]))) + heps;
post[r * pp + j] =
2.0f / (1.0f + expf(-(coefficients[hc + j] * scale[1] + base[hc + j])));
}
for (int j = 0; j < hc; ++j) {
float mx = -INFINITY;
for (int k = 0; k < hc; ++k) {
const int q = 2 * hc + j * hc + k;
c[j * hc + k] = coefficients[q] * scale[2] + base[q];
mx = fmaxf(mx, c[j * hc + k]);
}
float sum = 0;
for (int k = 0; k < hc; ++k) {
c[j * hc + k] = expf(c[j * hc + k] - mx);
sum += c[j * hc + k];
}
for (int k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps;
}
for (int it = 0; it < iterations; ++it) {
if (it)
for (int j = 0; j < hc; ++j) {
float sum = 0;
for (int k = 0; k < hc; ++k) sum += c[j * hc + k];
for (int k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps;
}
for (int k = 0; k < hc; ++k) {
float sum = 0;
for (int j = 0; j < hc; ++j) sum += c[j * hc + k];
for (int j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps;
}
}
for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j];
}
__syncthreads();
if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
for (int i = tid; i < n; i += 256) {
float v = 0;
for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]);
x[r * xp + i] = f32_to_bf16(v);
}
}
// One wave handles GLM's 4x4 Sinkhorn matrix. Keep row/column sums in the
// scalar reference order; the other rows never participate in these shuffles.
// Writes post and comb; returns pre[lane] in lanes 0..3.
template <class In>
__device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* scale,
const float* base, float* post, float* comb,
int iterations, float eps, float heps, long pp,
long cp, const In& in) {
float inverse = 0;
if (!lane) {
float ss = 0;
for (int i = 0; i < 8; ++i) ss += *in.at(row, 24, i);
inverse = rsqrtf(ss / 16384.0f + eps);
}
inverse = __shfl(inverse, 0, 32);
float dot = 0;
if (lane < 24) {
float v[8];
for (int i = 0; i < 8; ++i) v[i] = *in.at(row, lane, i);
// The existing eight-chunk warp reduction pairs 0/4, 2/6, 1/5, 3/7.
dot = ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7]));
}
const float coefficient = dot * inverse;
const float post_coefficient = __shfl(coefficient, (lane + 4) & 31, 32);
const float matrix_coefficient = __shfl(coefficient, (lane + 8) & 31, 32);
float pre = 0;
if (lane < 4) {
pre = 1.0f / (1.0f + expf(-(coefficient * scale[0] + base[lane]))) + heps;
post[row * pp + lane] =
2.0f / (1.0f + expf(-(post_coefficient * scale[1] + base[4 + lane])));
}
float value = lane < 16 ? matrix_coefficient * scale[2] + base[8 + lane] : 0;
const int row_base = lane & ~3, col = lane & 3;
float mx = -INFINITY;
#pragma unroll
for (int j = 0; j < 4; ++j) mx = fmaxf(mx, __shfl(value, row_base + j, 32));
value = expf(value - mx);
float sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32);
value = value / sum + heps;
for (int it = 0; it < iterations; ++it) {
if (it) {
sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32);
value /= sum + heps;
}
sum = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) sum += __shfl(value, col + 4 * j, 32);
value /= sum + heps;
}
if (lane < 16) comb[row * cp + lane] = value;
return pre;
}
template <class In>
__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base,
uint16_t* x, float* post, float* comb, int iterations,
float eps, float heps, long hp, long xp, long pp, long cp,
In in) {
const int lane = threadIdx.x;
const long row = blockIdx.x;
const float pre =
glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in);
const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32),
p3 = __shfl(pre, 3, 32);
for (int i = lane; i < 4096; i += 32) {
float v = 0;
v += p0 * bf16_to_f32(h[row * hp + i]);
v += p1 * bf16_to_f32(h[row * hp + 4096 + i]);
v += p2 * bf16_to_f32(h[row * hp + 8192 + i]);
v += p3 * bf16_to_f32(h[row * hp + 12288 + i]);
x[row * xp + i] = f32_to_bf16(v);
}
}
// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing
// 4096 columns a row was most of a decode step's mhc_pre.
template <class In>
__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel(
const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb,
int iterations, float eps, float heps, long hp, long xp, long pp, long cp, In in) {
__shared__ float spre[4];
const int tid = threadIdx.x;
const long row = blockIdx.x;
if (tid < 32) {
const float pre =
glm_warp_mix(tid, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in);
if (tid < 4) spre[tid] = pre;
}
__syncthreads();
const float pre[4] = { spre[0], spre[1], spre[2], spre[3] };
if (mix_rows_vec(h + row * hp, x + row * xp, pre, 4096, 4, tid, 256)) return;
for (int i = tid; i < 4096; i += 256) {
float v = 0;
v += pre[0] * bf16_to_f32(h[row * hp + i]);
v += pre[1] * bf16_to_f32(h[row * hp + 4096 + i]);
v += pre[2] * bf16_to_f32(h[row * hp + 8192 + i]);
v += pre[3] * bf16_to_f32(h[row * hp + 12288 + i]);
x[row * xp + i] = f32_to_bf16(v);
}
}
__global__ void mhc_post_kernel(const uint16_t* x, const uint16_t* h, const float* post,
const float* comb, uint16_t* out, int n, int hc, long xp, long hp,
long pp, long cp, long op) {
const long r = blockIdx.y;
const int q = blockIdx.x * blockDim.x + threadIdx.x;
if (q >= n * hc) return;
const int k = q / n, i = q % n;
float v = 0;
for (int j = 0; j < hc; ++j)
v += comb[r * cp + j * hc + k] * bf16_to_f32(h[r * hp + j * n + i]);
v += post[r * pp + k] * bf16_to_f32(x[r * xp + i]);
out[r * op + q] = f32_to_bf16(v);
}
// mhc_post at four streams, eight columns of every output stream a thread: each input word is
// loaded once instead of once per output stream. Every output keeps mhc_post_kernel's order.
__global__ void mhc_post_vec_kernel(const uint16_t* x, const uint16_t* h, const float* post,
const float* comb, uint16_t* out, int n, long xp, long hp,
long pp, long cp, long op) {
const long r = blockIdx.y;
const int i = (blockIdx.x * blockDim.x + threadIdx.x) * 8;
if (i >= n) return;
float hv[4][8], xv[8];
auto unpack = [](const uint16_t* p, float* v) {
const uint4 q = *reinterpret_cast<const uint4*>(p);
const uint32_t w[4] = { q.x, q.y, q.z, q.w };
#pragma unroll
for (int e = 0; e < 8; ++e) v[e] = bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1))));
};
#pragma unroll
for (int j = 0; j < 4; ++j) unpack(h + r * hp + (long)j * n + i, hv[j]);
unpack(x + r * xp + i, xv);
#pragma unroll
for (int k = 0; k < 4; ++k) {
float c[4];
#pragma unroll
for (int j = 0; j < 4; ++j) c[j] = comb[r * cp + j * 4 + k];
const float pk = post[r * pp + k];
uint32_t o[4];
#pragma unroll
for (int e = 0; e < 8; e += 2) {
float v0 = 0, v1 = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
v0 += c[j] * hv[j][e];
v1 += c[j] * hv[j][e + 1];
}
v0 += pk * xv[e];
v1 += pk * xv[e + 1];
o[e >> 1] = (uint32_t)f32_to_bf16(v0) | ((uint32_t)f32_to_bf16(v1) << 16);
}
*reinterpret_cast<uint4*>(out + r * op + (long)k * n + i) = uint4{ o[0], o[1], o[2], o[3] };
}
}
__global__ void mhc_contract_kernel(const uint16_t* h, uint16_t* x, int n, int hc, long hp,
long xp) {
const long r = blockIdx.y;
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
float v = 0;
for (int j = 0; j < hc; ++j) v += bf16_to_f32(h[r * hp + j * n + i]);
x[r * xp + i] = f32_to_bf16(v / (float)hc);
}
bool matrix(const RadTensor& t, uint32_t dt, long rows, long cols) {
return t.data && t.dtype == dt && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols &&
t.stride[1] == 1 && t.stride[0] >= cols;
}
bool vector(const RadTensor& t, long n) {
return t.data && t.dtype == RAD_F32 && t.rank == 1 && t.shape[0] == n && t.stride[0] == 1;
}
bool geometry(const RadArgs* a, int* n, int* hc) {
const long nn = r4d_geti_or(a, "n", 0), hh = r4d_geti_or(a, "hc", 0);
if (nn < 1 || nn > 16384 || hh < 2 || hh > 8) return false;
*n = (int)nn;
*hc = (int)hh;
return true;
}
// GLM's split projection: eight 2048-column chunks of the 16384-wide residual, 24 coefficients
// and the sum of squares each. A Dense chunk holds those 25 partials in kPartStride slots.
constexpr int kChunkCols = 2048, kPartStride = 28;
template <class Out>
int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc,
int chunk0, int count, long rows) {
const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4");
const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4");
/* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count;
* RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte
* residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape:
* one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48
* (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave
* trail two at every count. */
const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC");
const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 &&
((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 &&
hc * n % kChunkCols == 0;
if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) {
const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS");
const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10)
: rows >= 32 ? 2
: 1;
const int mix = hc * (hc + 2), groups = (mix + 4) / 4;
#define MHC_VEC(RR) \
do { \
const long items = (long)count * groups * ((rows + RR - 1) / RR); \
return R4D_EMIT(stream, (mhc_partial_vec_kernel<Out, RR>), \
dim3((unsigned)((items + 3) / 4)), dim3(128), 0, (const uint16_t*)h.data, \
(const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \
(long)fn.stride[0], rows, items); \
} while (0)
if (R == 4) MHC_VEC(4);
if (R == 2) MHC_VEC(2);
MHC_VEC(1);
#undef MHC_VEC
}
const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN");
const bool use_rows4 =
(!rows4 || rows4[0] == '1') &&
rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32);
if (use_rows4 && (!coeff4 || coeff4[0] == '1'))
return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel<Out>),
dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128),
0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n,
hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
if (use_rows4)
return R4D_EMIT(stream, (mhc_partial_rows4_kernel<Out>),
dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0,
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
return R4D_EMIT(stream, (mhc_partial_kernel<Out>),
dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0,
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
chunk0, (long)h.stride[0], (long)fn.stride[0]);
}
// The finishing dispatch. `split` says the partials exist (in `in`); without them
// mhc_pre_kernel projects the residual itself from `fn`.
template <class In>
int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s,
const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c,
int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split,
In in) {
const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP");
/* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time
* at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish
* from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */
const char* form = std::getenv("RADIANCE_MHC_FINISH");
const bool old = form && !std::strcmp(form, "old");
const bool warp_mix = split && (warp ? warp[0] == '1' : true) &&
(old ? rows >= 32 : !(form && !std::strcmp(form, "scalar")));
if (warp_mix && old)
return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel<In>), dim3((unsigned)rows), dim3(32), 0,
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
in);
if (warp_mix)
return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel<In>), dim3((unsigned)rows), dim3(256), 0,
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
in);
if (old)
return R4D_EMIT(stream, (mhc_pre_kernel<In, false>), dim3((unsigned)rows), dim3(256), 0,
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0],
(long)c.stride[0], split ? chunks : 0, in);
return R4D_EMIT(stream, (mhc_pre_kernel<In, true>), dim3((unsigned)rows), dim3(256), 0,
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
split ? chunks : 0, in);
}
bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) {
*iters = r4d_geti_or(a, "iterations", 0);
*eps = (float)r4d_getf(a, "eps", 0);
*heps = (float)r4d_getf(a, "hc_eps", 0);
return *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && std::isfinite(*heps) &&
*eps > 0 && *heps >= 0;
}
// mhc_pre_partial and mhc_pre_finish serve GLM's split geometry only.
bool glm_chunks(const RadArgs* a, int n, int hc) {
return n == 4096 && hc == 4 && r4d_geti_or(a, "chunk", 0) == kChunkCols;
}
int pre_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
long iters;
float eps, heps;
if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE;
const auto &h = a->t[0], &fn = a->t[1], &s = a->t[2], &b = a->t[3];
const auto &x = a->t[4], &p = a->t[5], &c = a->t[6];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > INT_MAX) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) ||
!vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc))
return RAD_E_SHAPE;
const int chunks = (hc * n + kChunkCols - 1) / kChunkCols;
const bool split =
n == 4096 && hc == 4 && rows <= 65535 && (hc * (hc + 2) + 1) * chunks * 4 + 2 <= n * 2;
const InX in{ (uint16_t*)x.data, (long)x.stride[0], chunks };
if (split) {
const int rc = emit_partials(stream, h, fn, in, n, hc, 0, chunks, rows);
if (rc < 0) return rc;
}
return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc,
(int)iters, eps, heps, rows, chunks, split, in);
}
int partial_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE;
const int total = hc * n / kChunkCols;
const long first = r4d_geti_or(a, "first", -1), count = r4d_geti_or(a, "chunks", 0);
if (first < 0 || count < 1 || first + count > total) return RAD_E_SHAPE;
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) ||
!matrix(part, RAD_F32, rows, count * kPartStride))
return RAD_E_SHAPE;
const Dense out{ (float*)part.data, (long)part.stride[0], kPartStride, (int)first };
return emit_partials(stream, h, fn, out, n, hc, (int)first, (int)count, rows);
}
int finish_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 7) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE;
long iters;
float eps, heps;
if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE;
const int chunks = hc * n / kChunkCols;
const auto &part = a->t[0], &h = a->t[1], &s = a->t[2], &b = a->t[3];
const auto &x = a->t[4], &p = a->t[5], &c = a->t[6];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(part, RAD_F32, rows, chunks * kPartStride) || !matrix(h, RAD_BF16, rows, hc * n) ||
!vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc))
return RAD_E_SHAPE;
const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 };
return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows,
chunks, true, in);
}
int post_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 5) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4];
if (x.rank != 2 || x.shape[0] < 1 || x.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = x.shape[0];
if (!matrix(x, RAD_BF16, rows, n) || !matrix(h, RAD_BF16, rows, hc * n) ||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) ||
!matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data)
return RAD_E_SHAPE;
/* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */
const char* vec = std::getenv("RADIANCE_MHC_POST_VEC");
const auto aligned = [](const RadTensor& t) {
return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0;
};
if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows),
dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data,
(const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n,
(long)x.stride[0], (long)h.stride[0], (long)p.stride[0], (long)c.stride[0],
(long)o.stride[0]);
return R4D_EMIT(stream, mhc_post_kernel, dim3((n * hc + 255) / 256, (unsigned)rows), dim3(256),
0, (const uint16_t*)x.data, (const uint16_t*)h.data, (const float*)p.data,
(const float*)c.data, (uint16_t*)o.data, n, hc, (long)x.stride[0],
(long)h.stride[0], (long)p.stride[0], (long)c.stride[0], (long)o.stride[0]);
}
int contract_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 2) return RAD_E_INVAL;
int n, hc;
if (!geometry(a, &n, &hc)) return RAD_E_SHAPE;
const auto &h = a->t[0], &x = a->t[1];
if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE;
const long rows = h.shape[0];
if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(x, RAD_BF16, rows, n)) return RAD_E_SHAPE;
return R4D_EMIT(stream, mhc_contract_kernel, dim3((n + 255) / 256, (unsigned)rows), dim3(256),
0, (const uint16_t*)h.data, (uint16_t*)x.data, n, hc, (long)h.stride[0],
(long)x.stride[0]);
}
}
extern "C" int r4d_rad_mhc_pre(const RadArgs* a, RadStream stream) { return pre_body(a, stream); }
extern "C" int r4d_rad_mhc_pre_partial(const RadArgs* a, RadStream stream) {
return partial_body(a, stream);
}
extern "C" int r4d_rad_mhc_pre_finish(const RadArgs* a, RadStream stream) {
return finish_body(a, stream);
}
extern "C" int r4d_rad_mhc_post(const RadArgs* a, RadStream stream) { return post_body(a, stream); }
extern "C" int r4d_rad_mhc_contract(const RadArgs* a, RadStream stream) {
return contract_body(a, stream);
}
+700
View File
@@ -0,0 +1,700 @@
/* Absorbed MLA keeps a single 512-wide latent per token. Decode splits the
* selected history across waves, then merges FP32 softmax statistics. It never
* materializes per-head K/V in the growing cache. */
#include <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_gdn_wmma.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <atomic>
namespace {
struct ProjectMeta {
long xr, xh, wp, yr, yh;
int rows, heads;
};
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */
__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z;
if (col >= 512) return;
float sum = 0;
for (int j = 0; j < 256; ++j)
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum);
y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
}
__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
r = blockIdx.z;
float sum = 0;
for (int j = lane; j < 512; j += 32)
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum);
#pragma unroll
for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32);
if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
}
/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight
* element is loaded once for R rows. Every row's sum runs over j in the same order, and
* r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels.
* A tail group past the last row reads that row again and stores nothing for it. */
template <int R>
__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
ProjectMeta m) {
const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r0 = blockIdx.z * R;
if (col >= 512) return;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = 0; j < 256; ++j) {
const float wv = bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]);
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]);
}
#pragma unroll
for (int r = 0; r < R; ++r)
if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + head * m.yh + col] = f32_to_bf16(sum[r]);
}
template <int R>
__global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
ProjectMeta m) {
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
r0 = blockIdx.z * R;
const uint16_t* xr[R];
#pragma unroll
for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh;
const uint16_t* const wr = w + ((long)head * 512 + 256 + col) * m.wp;
float sum[R];
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = 0;
for (int j = lane; j < 512; j += 32) {
const float wv = bf16_to_f32(wr[j]);
#pragma unroll
for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]);
}
float mine = 0;
#pragma unroll
for (int r = 0; r < R; ++r) {
sum[r] = r4d_xor_sum<32>(sum[r]);
if (lane == r) mine = sum[r];
}
if (lane < R && r0 + lane < m.rows)
y[(long)(r0 + lane) * m.yr + head * m.yh + col] = f32_to_bf16(mine);
}
int project_body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 3) return RAD_E_INVAL;
RadTensor x = a->t[0], y = a->t[2];
const auto& w = a->t[1];
const char* mode = r4d_gets(a, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
const long h = r4d_geti_or(a, "heads", 0);
auto heads_view = [&](RadTensor& t, long width) {
if (h > 0 && t.rank == 2 && t.shape[1] == h * width) {
t.rank = 3;
t.shape[1] = h;
t.shape[2] = width;
t.stride[2] = t.stride[1];
t.stride[1] *= width;
}
};
heads_view(x, absorb ? 256 : 512);
heads_view(y, absorb ? 512 : 256);
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
if ((!absorb && !expand) || h < 1 || h > 64 || r4d_geti_or(a, "head_dim", 0) != 256 ||
r4d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 ||
x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h ||
x.shape[2] != (absorb ? 256 : 512) || w.shape[0] != h * 512 || w.shape[1] != 512 ||
y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : 256) ||
x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] ||
x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] ||
y.stride[0] < h * y.stride[1])
return RAD_E_SHAPE;
const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0],
y.stride[1], (int)x.shape[0], (int)h };
/* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest
* holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a
* wave (expand). */
const char* form = std::getenv("RADIANCE_MLA_PROJECT");
const auto* xp = (const uint16_t*)x.data;
const auto* wp = (const uint16_t*)w.data;
auto* yp = (uint16_t*)y.data;
if (form && !std::strcmp(form, "old")) {
if (absorb)
return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp,
m);
return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m);
}
const long R = form && *form ? std::strtol(form, nullptr, 10)
: m.rows >= 8 ? 8
: m.rows >= 4 ? 4
: m.rows >= 2 ? 2
: 1;
#define MLA_PROJECT_ROWS(RR) \
do { \
const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \
if (absorb) \
return R4D_EMIT(stream, (project_absorb_rows<RR>), dim3(4, h, groups), dim3(128), 0, \
xp, wp, yp, m); \
return R4D_EMIT(stream, (project_expand_rows<RR>), dim3(64, h, groups), dim3(128), 0, xp, \
wp, yp, m); \
} while (0)
if (R == 8) MLA_PROJECT_ROWS(8);
if (R == 4) MLA_PROJECT_ROWS(4);
if (R == 2) MLA_PROJECT_ROWS(2);
MLA_PROJECT_ROWS(1);
#undef MLA_PROJECT_ROWS
}
constexpr int D = 512, PART = D + 2;
constexpr int64_t scratch_bytes = 512ll * PART * 4;
constexpr int64_t matrix_scratch_bytes = 2048ll * PART * 4;
/* r4d_mla_matrix_pin_form: 0 is the launcher's rule (vector key loads where the cache is
* aligned), 1 the element-wise key load. */
int g_mla_matrix_form = 0;
struct Meta {
long qr, qh, kp, kt, bp, bc, lp, orr, oh;
int rows, heads, blocks, bs, pages, splits;
float scale;
};
/* RADIANCE_MLA_CONFLICT_STATS: per device, the 16-token passes the matrix row ran, how many of them
* were a pair's second pass, and the chunks of the max(length) raster a pass-free pairing would
* run. Read back by r4d_mla_matrix_stats, and printed every 1024th counted launch. */
__device__ unsigned long long g_mla_stats[3];
__device__ void load_latent(const uint16_t* p, float (&v)[16]) {
if (!((uintptr_t)p & 15)) {
const uint4 a = *(const uint4*)p, b = *(const uint4*)(p + 8);
const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w };
#pragma unroll
for (int j = 0; j < 16; ++j)
v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1))));
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32(p[j]);
}
}
__global__ __launch_bounds__(128) void attend(const uint16_t* q, const uint16_t* kv, const int* bt,
const int* len, uint16_t* out, float* scratch,
Meta m) {
const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x,
split = blockIdx.z;
if (head >= m.heads) return;
const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs);
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
float query[16], value[16] = {};
load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query);
float max_score = -INFINITY, den = 0;
for (int token = begin; token < end; ++token) {
const int page = bt[(long)r * m.bp + (token / m.bs) * m.bc];
if (page < 0 || page >= m.pages) continue;
float key[16];
load_latent(kv + (long)page * m.kp + (token % m.bs) * m.kt + lane * 16, key);
float score = 0;
#pragma unroll
for (int j = 0; j < 16; ++j) score += query[j] * key[j];
score = r4d_wave_sum(score) * m.scale;
const bool higher = score > max_score;
const float weight = expf(higher ? max_score - score : score - max_score);
if (higher) {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j];
den = den * weight + 1;
max_score = score;
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += key[j] * weight;
den += weight;
}
}
if (m.splits == 1) {
#pragma unroll
for (int j = 0; j < 16; ++j)
out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] =
f32_to_bf16(den > 0 ? value[j] / den : 0);
} else {
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
#pragma unroll
for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j];
if (!lane) {
dst[D] = max_score;
dst[D + 1] = den;
}
}
}
__global__ __launch_bounds__(128) void merge(const float* scratch, uint16_t* out, Meta m) {
const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x;
if (head >= m.heads) return;
const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART;
float max_score = -INFINITY;
for (int s = 0; s < m.splits; ++s)
if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]);
float value[16] = {}, den = 0;
for (int s = 0; s < m.splits; ++s) {
const float part_den = src[s * PART + D + 1];
if (!(part_den > 0)) continue;
const float w = expf(src[s * PART + D] - max_score);
den += part_den * w;
#pragma unroll
for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w;
}
#pragma unroll
for (int j = 0; j < 16; ++j)
out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] =
f32_to_bf16(den > 0 ? value[j] / den : 0);
}
/* Heads are the matrix rows, so all sixteen share each latent load even when
* each query selected different pages. Splitting P into BF16 high/low parts
* preserves FP32 softmax precision without a materialized per-head KV cache.
*
* PAIR fills the sixteen rows with eight heads of two neighbouring requests
* (rows 0-7 request r, rows 8-15 request r+1). A key is loaded once when both
* requests address the same cache row at that table position, as consecutive
* queries of one sequence do; each half masks columns that are not its own,
* which carries the causal edge. Where the two tables name different rows the
* chunk runs a second pass with the second request's keys.
*
* UNION pairs by page instead of by position: past the DSA budget each request
* selects its own blocks, neighbours share most of them at shifted positions,
* and the positional pairing would run nearly every chunk twice. The walk is
* request r's table in its own order (so r sums exactly as it does unpaired at
* one split), each entry carrying where r+1's table names the same page, then
* the pages only r+1 names, in r+1's order. Every chunk runs once. */
constexpr int kUnionBlocks = 520, kUnionSlots = 1024;
__device__ __forceinline__ unsigned union_slot(int page) {
return ((unsigned)page * 2654435761u) >> 22;
}
/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. */
template <bool PAIR, bool WIDE, bool UNION, bool STATS>
__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const uint16_t* kv,
const int* bt, const int* len, uint16_t* out,
float* scratch, Meta m) {
static_assert(PAIR || !UNION, "the union pairs two requests");
static_assert(16 * 520 * sizeof(uint16_t) >= (2 * kUnionSlots + 2 * kUnionBlocks) * sizeof(int),
"the union's hash lives in the key tile");
__shared__ __align__(16) uint16_t query[16 * 520], keys[16 * 520], prob_hi[16 * 24],
prob_lo[16 * 24];
__shared__ float score[16 * 16], maximum[16], denominator[16], alpha[16];
__shared__ long source[16];
__shared__ long own[PAIR ? 32 : 1];
__shared__ short pair_of[UNION ? kUnionBlocks : 1], only_b[UNION ? kUnionBlocks : 1];
__shared__ int union_count[UNION ? 4 : 1], union_end;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int r = PAIR ? blockIdx.x * 2 : blockIdx.x, h0 = blockIdx.y * (PAIR ? 8 : 16),
split = blockIdx.z;
int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs), live_pair[2] = { live, 0 };
if constexpr (PAIR) {
if (r + 1 < m.rows) live_pair[1] = min(max(len[(long)(r + 1) * m.lp], 0), m.blocks * m.bs);
live = max(live_pair[0], live_pair[1]);
}
for (int j = tid; j < 16 * 512; j += 128) {
if constexpr (PAIR) {
const int row = j / 512, request = r + row / 8;
query[row * 520 + j % 512] =
request < m.rows ? q[(long)request * m.qr + (long)(h0 + row % 8) * m.qh + j % 512]
: 0;
} else
query[(j / 512) * 520 + j % 512] =
q[(long)r * m.qr + (long)(h0 + j / 512) * m.qh + j % 512];
}
if (tid < 16) {
maximum[tid] = -INFINITY;
denominator[tid] = 0;
}
v8f value[8];
#pragma unroll
for (int nt = 0; nt < 8; ++nt) value[nt] = (v8f){ 0 };
const int* const bt_a = bt + (long)r * m.bp;
const int* const bt_b = bt + (long)(r + 1) * m.bp;
int blocks_a = 0;
if constexpr (UNION) {
/* The key tile is free until the first chunk: an open-addressed page -> lowest r entry
* hash, the lowest r+1 entry naming each r entry's page, and each r+1 entry's match. */
int* const slot_page = (int*)keys;
int* const slot_first = slot_page + kUnionSlots;
int* const first_b = slot_first + kUnionSlots;
int* const match = first_b + kUnionBlocks;
blocks_a = (live_pair[0] + m.bs - 1) / m.bs;
const int blocks_b = (live_pair[1] + m.bs - 1) / m.bs;
for (int i = tid; i < kUnionSlots; i += 128) {
slot_page[i] = -1;
slot_first[i] = INT_MAX;
}
for (int i = tid; i < blocks_a; i += 128) first_b[i] = INT_MAX;
if (!tid) union_end = live_pair[0];
__syncthreads();
for (int i = tid; i < blocks_a; i += 128) {
const int page = bt_a[(long)i * m.bc];
if (page < 0 || page >= m.pages) continue;
for (unsigned at = union_slot(page);; at = (at + 1) & (kUnionSlots - 1)) {
const int seen = atomicCAS(&slot_page[at], -1, page);
if (seen == -1 || seen == page) {
atomicMin(&slot_first[at], i);
break;
}
}
}
__syncthreads();
for (int j = tid; j < blocks_b; j += 128) {
const int page = bt_b[(long)j * m.bc];
int found = -1;
if (page >= 0 && page < m.pages)
for (unsigned at = union_slot(page); slot_page[at] != -1;
at = (at + 1) & (kUnionSlots - 1))
if (slot_page[at] == page) {
found = slot_first[at];
break;
}
match[j] = found;
if (found >= 0) atomicMin(&first_b[found], j);
}
__syncthreads();
for (int i = tid; i < blocks_a; i += 128)
pair_of[i] = (short)(first_b[i] == INT_MAX ? -1 : first_b[i]);
/* r+1's own pages in its table order: slots from a ballot prefix, not an atomic, so the
* walk (and the summation order) is the same on every run. */
int appended = 0;
for (int j0 = 0; j0 < blocks_b; j0 += 128) {
const int j = j0 + tid;
bool only = false;
if (j < blocks_b) {
const int page = bt_b[(long)j * m.bc];
only = page >= 0 && page < m.pages && (match[j] < 0 || first_b[match[j]] != j);
}
const unsigned long long ballot = __ballot(only);
if (!lane) union_count[wave] = (int)__popcll(ballot);
__syncthreads();
int before = appended, total = appended;
#pragma unroll
for (int w = 0; w < 4; ++w) {
before += w < wave ? union_count[w] : 0;
total += union_count[w];
}
if (only) {
const int at = before + (int)__popcll(ballot & ((1ull << lane) - 1ull));
only_b[at] = (short)j;
const int seen = min(m.bs, live_pair[1] - j * m.bs);
atomicMax(&union_end, (blocks_a + at) * m.bs + seen);
} else if (j < blocks_b && match[j] >= 0 && first_b[match[j]] == j)
atomicMax(&union_end, match[j] * m.bs + min(m.bs, live_pair[1] - j * m.bs));
appended = total;
__syncthreads();
}
live = union_end;
}
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
__syncthreads();
for (int start = begin; start < end; start += 16) {
bool second = false;
if constexpr (UNION) {
if (tid < 16) {
const int token = start + tid, entry = token / m.bs, offset = token % m.bs;
long row[2] = { -1, -1 };
if (token < end) {
const int at_a = entry < blocks_a ? entry : -1;
const int at_b = entry < blocks_a ? pair_of[entry] : only_b[entry - blocks_a];
const int page = at_a >= 0 ? bt_a[(long)at_a * m.bc] : bt_b[(long)at_b * m.bc];
if (page >= 0 && page < m.pages) {
const long at = (long)page * m.kp + offset * m.kt;
if (at_a >= 0 && at_a * m.bs + offset < live_pair[0]) row[0] = at;
if (at_b >= 0 && at_b * m.bs + offset < live_pair[1]) row[1] = at;
}
}
own[tid] = row[0];
own[16 + tid] = row[1];
source[tid] = row[0] >= 0 ? row[0] : row[1];
}
__syncthreads();
} else if constexpr (PAIR) {
bool conflict = false;
if (tid < 16) {
const int token = start + tid;
long row[2];
#pragma unroll
for (int k = 0; k < 2; ++k) {
const int page = token < end && token < live_pair[k]
? bt[(long)(r + k) * m.bp + (token / m.bs) * m.bc]
: -1;
row[k] = page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt
: -1;
own[k * 16 + tid] = row[k];
}
source[tid] = row[0] >= 0 ? row[0] : row[1];
conflict = row[0] >= 0 && row[1] >= 0 && row[0] != row[1];
}
second = __syncthreads_or(conflict);
if (STATS && second && !tid) {
atomicAdd(&g_mla_stats[0], 1ull);
atomicAdd(&g_mla_stats[1], 1ull);
}
} else {
if (tid < 16) {
const int token = start + tid;
const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1;
source[tid] =
page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt : -1;
}
__syncthreads();
}
for (int pass = 0; pass < (second ? 2 : 1); ++pass) {
if constexpr (PAIR)
if (pass) {
if (tid < 16) {
const long first = own[tid], other = own[16 + tid];
source[tid] = first >= 0 && other >= 0 && first != other ? other : -1;
}
__syncthreads();
}
if constexpr (WIDE) {
/* Unconditional loads (an absent row reads row 0 and is zeroed after) so all
* eight are in flight before the first wait. */
uint4 part[8];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int flat = tid + j * 128;
const long at = source[flat >> 6];
part[j] = *(const uint4*)(kv + (at >= 0 ? at : 0) + (flat & 63) * 8);
if (at < 0) part[j] = make_uint4(0, 0, 0, 0);
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int flat = tid + j * 128;
*(uint4*)(keys + (flat >> 6) * 520 + (flat & 63) * 8) = part[j];
}
} else {
for (int j = tid; j < 16 * 512; j += 128) {
const int token = j / 512, col = j % 512;
keys[token * 520 + col] = source[token] >= 0 ? kv[source[token] + col] : 0;
}
}
__syncthreads();
if (!wave) {
v8f dot = { 0 };
#pragma unroll
for (int d = 0; d < 512; d += 16)
dot = mma(frag(query, 520, 0, d, lane), frag(keys, 520, 0, d, lane), dot);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int head = (lane >> 4) * 8 + j, col = lane & 15;
bool visible = source[col] >= 0;
if constexpr (PAIR)
visible = visible && own[(lane >> 4) * 16 + col] == source[col];
score[head * 16 + col] = visible ? dot[j] * m.scale : -INFINITY;
}
}
__syncthreads();
if (tid < 16) {
float mx = maximum[tid];
for (int j = 0; j < 16; ++j) mx = fmaxf(mx, score[tid * 16 + j]);
const float a = isfinite(mx) ? expf(maximum[tid] - mx) : 1;
float den = denominator[tid] * a;
for (int j = 0; j < 16; ++j) {
const float p =
isfinite(score[tid * 16 + j]) ? expf(score[tid * 16 + j] - mx) : 0;
const uint16_t hi = f32_to_bf16(p);
prob_hi[tid * 24 + j] = hi;
prob_lo[tid * 24 + j] = f32_to_bf16(p - bf16_to_f32(hi));
den += p;
}
maximum[tid] = mx;
denominator[tid] = den;
alpha[tid] = a;
}
// Read before the in-place transpose overwrites keys. Query remains resident.
uint16_t held[64];
#pragma unroll
for (int j = 0; j < 64; ++j) {
const int flat = tid + j * 128;
held[j] = keys[(flat / 512) * 520 + flat % 512];
}
__syncthreads();
#pragma unroll
for (int j = 0; j < 64; ++j) {
const int flat = tid + j * 128;
keys[(flat % 512) * 16 + flat / 512] = held[j];
}
__syncthreads();
const auto hi = frag(prob_hi, 24, 0, 0, lane), lo = frag(prob_lo, 24, 0, 0, lane);
#pragma unroll
for (int nt = 0; nt < 8; ++nt) {
#pragma unroll
for (int j = 0; j < 8; ++j) value[nt][j] *= alpha[(lane >> 4) * 8 + j];
const auto v = frag(keys, 16, wave * 128 + nt * 16, 0, lane);
value[nt] = mma(hi, v, value[nt]);
value[nt] = mma(lo, v, value[nt]);
}
__syncthreads();
}
}
#pragma unroll
for (int nt = 0; nt < 8; ++nt) {
const int col = wave * 128 + nt * 16 + (lane & 15);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int row = (lane >> 4) * 8 + j, request = PAIR ? r + (lane >> 4) : r,
head = PAIR ? h0 + j : h0 + row;
if (PAIR && request >= m.rows) continue;
if (m.splits == 1) {
const float den = denominator[row];
out[(long)request * m.orr + (long)head * m.oh + col] =
f32_to_bf16(den > 0 ? value[nt][j] / den : 0);
} else
scratch[(((long)request * m.heads + head) * m.splits + split) * PART + col] =
value[nt][j];
}
}
if (m.splits > 1 && tid < 16) {
const int request = PAIR ? r + tid / 8 : r, head = PAIR ? h0 + tid % 8 : h0 + tid;
if (!PAIR || request < m.rows) {
float* dst = scratch + (((long)request * m.heads + head) * m.splits + split) * PART;
dst[D] = maximum[tid];
dst[D + 1] = denominator[tid];
}
}
if (STATS && !tid) {
const int whole = max(live_pair[0], live_pair[1]);
const int raster =
(int)((long)whole * (split + 1) / m.splits) - (int)((long)whole * split / m.splits);
const unsigned long long chunks = (unsigned long long)(end - begin + 15) / 16;
atomicAdd(&g_mla_stats[0], chunks);
atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16);
}
}
bool env_on(const char* name) {
const char* e = std::getenv(name);
return e && *e && *e != '0';
}
void read_stats(unsigned long long (&v)[3], bool reset) {
v[0] = v[1] = v[2] = 0;
if (hipMemcpyFromSymbol(v, HIP_SYMBOL(g_mla_stats), sizeof v, 0, hipMemcpyDeviceToHost) !=
hipSuccess)
return;
const unsigned long long zero[3] = {};
if (reset)
(void)hipMemcpyToSymbol(HIP_SYMBOL(g_mla_stats), zero, sizeof zero, 0,
hipMemcpyHostToDevice);
}
/* A server has no point at which to read the counters: running totals every 1024th counted launch.
* Not at exit, where a HIP call meets a runtime that is tearing down; not inside a graph capture,
* which a blocking copy would break. */
void report_stats(RadStream stream) {
static std::atomic<unsigned> launches{ 0 };
if (++launches % 1024) return;
hipStreamCaptureStatus capture = hipStreamCaptureStatusNone;
if (hipStreamIsCapturing((hipStream_t)stream, &capture) != hipSuccess ||
capture != hipStreamCaptureStatusNone)
return;
int device = 0;
if (hipGetDevice(&device) != hipSuccess) return;
unsigned long long v[3];
read_stats(v, false);
if (!v[2]) return;
std::fprintf(stderr,
"r4d mla_attn_matrix device %d: %llu passes over %llu raster chunks, "
"%llu second passes (%.3fx)\n",
device, v[0], v[2], v[1], (double)v[0] / (double)v[2]);
}
template <bool MATRIX>
int body(const RadArgs* a, RadStream stream) {
if (!a || a->n_t < 5) return RAD_E_INVAL;
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4];
if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
len.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 5; ++i)
if (!a->t[i].data) return RAD_E_INVAL;
const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0);
const float scale = (float)r4d_getf(a, "scale", 0);
if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 ||
!std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 ||
q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 ||
q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 ||
kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D ||
kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 ||
bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs ||
bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 ||
len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 ||
o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 ||
o.stride[1] < D || o.stride[0] < heads * o.stride[1])
return RAD_E_SHAPE;
if (MATRIX && heads % 8) return RAD_E_UNSUPPORTED;
const bool pair = MATRIX && heads % 16;
const long jobs = MATRIX ? (pair ? (q.shape[0] + 1) / 2 * (heads / 8) : q.shape[0] * heads / 16)
: q.shape[0] * heads;
int splits = (int)std::min(MATRIX ? 64l : 16l, ((MATRIX ? 64 : 256) + jobs - 1) / jobs);
const long minimum = MATRIX ? 16 : 64;
splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + minimum - 1) / minimum));
if (!a->scratch || a->scratch_bytes < (MATRIX ? matrix_scratch_bytes : scratch_bytes))
splits = 1;
// Vectors need every cache row on a sixteen-byte boundary.
const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
!(kv.stride[2] % 8);
/* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists
* hold a table of at most kUnionBlocks entries. */
const char* pairing = std::getenv("RADIANCE_MLA_PAIR");
const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks;
const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS");
Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2],
bt.stride[0], bt.stride[1], len.stride[0], o.stride[0],
o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1],
(int)bs, (int)kv.shape[0], splits, scale };
int rc;
if constexpr (MATRIX) {
#define MATRIX_EMIT(P, W, U, S, X, Y) \
R4D_EMIT(stream, (attend_matrix<P, W, U, S>), dim3(X, Y, m.splits), dim3(128), 0, \
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, \
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
#define MATRIX_LAUNCH(P, W, U, X, Y) \
(stats ? MATRIX_EMIT(P, W, U, true, X, Y) : MATRIX_EMIT(P, W, U, false, X, Y))
if (pair && by_page)
rc = wide ? MATRIX_LAUNCH(true, true, true, (m.rows + 1) / 2, m.heads / 8)
: MATRIX_LAUNCH(true, false, true, (m.rows + 1) / 2, m.heads / 8);
else if (pair)
rc = wide ? MATRIX_LAUNCH(true, true, false, (m.rows + 1) / 2, m.heads / 8)
: MATRIX_LAUNCH(true, false, false, (m.rows + 1) / 2, m.heads / 8);
else
rc = wide ? MATRIX_LAUNCH(false, true, false, m.rows, m.heads / 16)
: MATRIX_LAUNCH(false, false, false, m.rows, m.heads / 16);
#undef MATRIX_LAUNCH
#undef MATRIX_EMIT
} else
rc = R4D_EMIT(stream, attend, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0,
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data,
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m);
if (rc == RAD_OK && splits > 1)
rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0,
(const float*)a->scratch, (uint16_t*)o.data, m);
if (rc == RAD_OK && stats) report_stats(stream);
return rc;
}
}
extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
return body<false>(a, stream);
}
extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
return body<true>(a, stream);
}
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
return project_body(a, stream);
}
extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; }
extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; }
extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; }
/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes,
* second passes, raster chunks), then zeroed. */
extern "C" void r4d_mla_matrix_stats(unsigned long long* out) {
unsigned long long v[3];
(void)hipDeviceSynchronize();
read_stats(v, true);
if (out) std::memcpy(out, v, sizeof v);
}
+90 -254
View File
@@ -43,6 +43,8 @@
#include "r4d_plugin.h"
#include "r4d_emit.h"
#include "r4d_gemm_args.h"
#include "r4d_moe_sort.h"
#include "r4d_moe_gather.h"
#include <hip/hip_bf16.h>
@@ -57,11 +59,20 @@
namespace {
constexpr uint32_t kWave = 32;
/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in
* registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers
* Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router
* instantiation. */
constexpr uint32_t kMaxExpert = 512;
using r4d_moesort::kMaxExpert;
using r4d_moesort::kMaxProtect;
using r4d_moesort::Protect;
using r4d_moesort::sort_place;
using r4d_moesort::protect_of;
using r4d_moesort::kScatterSmall;
using r4d_moesort::ScatterLds;
using r4d_moesort::wave_incl_scan_i32;
using r4d_moesort::scatter_small_place;
using r4d_moesort::kScatWaves;
using r4d_moesort::scatter_small_kernel;
using r4d_moegather::kGatherSlots;
using r4d_moegather::kGatherSelfT;
using r4d_moegather::gather_kernel;
constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N
/* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must
* be zeroed. Declared here because the GEMM reads it; the map is built further down. */
@@ -152,27 +163,6 @@ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) {
* `router_topk_scatter_kernel` run this same code from a different grid, byte-identically. */
/* In the fused kernel a row also hands its slots to the sort through `e`: each slot's expert
* relative to the slice, or -1 for another rank's. The standalone selection passes a null `e`. */
/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output
* dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort
* places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and
* [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an
* expert's place is itself. */
constexpr uint32_t kMaxProtect = 8;
struct Protect {
uint32_t n;
uint16_t e[kMaxProtect];
};
/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */
__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) {
int32_t below = 0;
for (uint32_t j = 0; j < p.n; ++j) {
if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j);
below += (int32_t)p.e[j] < e;
}
return e - below;
}
struct SlotSink {
int32_t* e;
int32_t base;
@@ -292,123 +282,8 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_kernel(
/* ================================================================== moe_scatter
*
* The small form: one workgroup does the whole sort, for T <= kScatterSmall, which covers every
* decode and verify step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch
* instead of three. Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert
* counts, and each slot placed by its rank inside its expert's run.
*
* On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work:
*
* - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one
* barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts).
* - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its
* expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's
* place is the number of the run's slots with a lower index. That count is as long as the run
* (a row picks an expert at most once), far shorter than counting all earlier slots.
*
* Stable and byte-identical: a slot's place is its position among the same expert's slots in
* ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so
* none waits on or invalidates the vector memory path. */
constexpr uint32_t kScatterSmall = 1024;
constexpr uint32_t kScatWaves = 8; /* the standalone sort: 256 threads */
/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the
* workgroup's wave count, which sizes the scan's exchange. */
template <uint32_t NW>
struct ScatterLds {
static constexpr uint32_t kTiles = (kMaxExpert + NW * kWave - 1) / (NW * kWave);
int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */
int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */
int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */
int32_t cnt[kMaxExpert + 1];
int32_t off[kMaxExpert + 1];
int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */
};
/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then
* the upper row adds the lower row's total. Lanes shifted in from outside the row read zero
* (bound_ctrl). */
__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) {
x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
const int32_t lo = __builtin_amdgcn_readlane(x, 15);
return lane >= 16u ? x + lo : x;
}
/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has
* written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the
* standalone sort and the fused kernel. The workgroup is exactly NW waves. */
template <uint32_t NW>
__device__ __forceinline__ void scatter_small_place(
int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t T, uint32_t n_expert, ScatterLds<NW>& sl) {
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1);
}
lds_barrier();
/* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same
* in every thread. */
int32_t carry = 0;
for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kWave, ++t) {
const uint32_t e = b + tid;
const int32_t v = (e < n_expert) ? sl.cnt[e] : 0;
const int32_t x = wave_incl_scan_i32(v, lane);
if (lane == kWave - 1) sl.wt[t][wave] = x;
lds_barrier();
int32_t below = 0, tot = 0;
#pragma unroll
for (uint32_t k = 0; k < NW; ++k) {
const int32_t c = sl.wt[t][k];
below += (k < wave) ? c : 0;
tot += c;
}
if (e < n_expert) {
const int32_t o = carry + below + x - v; /* inclusive -> exclusive */
sl.off[e] = o;
off[e] = o;
cnt[e] = v;
}
carry += tot;
}
if (tid == 0) off[n_expert] = carry;
lds_barrier();
for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i;
}
lds_barrier();
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e < 0) continue;
const int32_t o = sl.off[e], n = sl.cnt[e];
int32_t rank = 0;
for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i;
sorted[o + rank] = (int32_t)i;
}
}
__global__ __launch_bounds__(kScatWaves * kWave) void scatter_small_kernel(
const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off,
int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
__shared__ ScatterLds<kScatWaves> sl;
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = ids[i] - base;
sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1;
}
lds_barrier();
scatter_small_place(sorted, off, cnt, T, n_expert, sl);
}
* The small form is one workgroup and the sort of r4d_moe_sort.h; the general form below takes
* three passes. */
/* ================================================================== router_topk + moe_scatter
*
* One launch for the pair: at decode each half is a single 256-thread workgroup moving about a
@@ -520,11 +395,12 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel(
/* Placement and tail. Each routed slot goes to its expert's offset plus the expert's count in
* earlier tiles plus its rank in this tile. Sorted rows past the live count are -1; no placement
* lands there (all placed slots are below `off[n_expert]`), so each thread writes its own index
* without races. */
* without races. INV also writes each slot's row, -1 when dropped (scatter_small_place). */
template <bool INV>
__global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt,
const int32_t* __restrict__ off, int32_t* __restrict__ sorted,
uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
uint32_t T, uint32_t n_expert, int32_t base, Protect prot, int32_t* __restrict__ inv) {
__shared__ int32_t s_id[kScatterTile];
const uint32_t tid = threadIdx.x, b = blockIdx.x;
const uint32_t i = b * kScatterTile + tid;
@@ -536,12 +412,15 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const uint32_t live = (uint32_t)off[n_expert];
if (i >= live && i < T) sorted[i] = -1;
__syncthreads();
if constexpr (INV) if (i < T && e < 0) inv[i] = -1;
if (i >= T || e < 0) return;
/* Rank within the tile: earlier slots of this tile with the same expert. A serial scan of at
* most 256 LDS words per thread, the price of stability. */
int32_t rank = 0;
for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e);
sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i;
const int32_t at = off[e] + bcnt[(size_t)b * n_expert + e] + rank;
sorted[at] = (int32_t)i;
if constexpr (INV) inv[i] = at;
}
/* ================================================================== the 4-bit expert weight
@@ -2155,78 +2034,6 @@ __global__ void gather_scatter_kernel(const int32_t* __restrict__ sorted,
if (f >= 0 && f < (int32_t)T) inv[f] = (int32_t)i;
}
/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the
* column, and read inside the column loop each `inv` load would serialise the `ye` load behind it
* (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline.
*
* The column range is also split over blocks, since decode has one token. Neither change touches
* the sum: each column's slots are still summed in ascending order within one block. */
constexpr uint32_t kGatherSlots = 64;
/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not
* launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k),
* giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it
* (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches
* (~2.1 us each) of single-block kernels.
*
* `sorted == nullptr` selects the prepass path, used at prefill. */
constexpr uint32_t kGatherSelfT = 512;
template <uint32_t NTHR>
__global__ __launch_bounds__(NTHR) void gather_kernel(
const uint16_t* __restrict__ ye, const uint16_t* __restrict__ ew,
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const int32_t* __restrict__ sorted, uint32_t T,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
/* The shared arm's scalar, read once per block as scale_rows reads it once per row. */
float gate = 0.0f;
if (sh) {
const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]);
gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
if (sorted) {
/* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the
* prepass is two kernels). */
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1;
__syncthreads();
const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k;
for (uint32_t i = threadIdx.x; i < T; i += NTHR) {
const int32_t f = sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i;
}
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR)
s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]);
__syncthreads();
} else if (cached) {
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) {
s_i[j] = inv[t * top_k + j];
s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]);
}
__syncthreads();
}
for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < top_k; ++j) {
const int32_t i = cached ? s_i[j] : inv[t * top_k + j];
if (i < 0) continue;
const float wj = cached ? s_w[j] : bf16_to_f32(ew[(size_t)t * ew_ld + j]);
acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]);
}
const uint16_t g = f32_to_bf16(acc);
if (!sh) { y[(size_t)t * y_ld + c] = g; continue; }
/* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather
* as bf16 and narrows its own product before adding. */
const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate);
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
/* ---- prefill gather: a wave per token, eight columns per lane ---------------------------------
*
* At prefill this op reads `ye` (105 MB per layer at a 2048 chunk of Qwen3.8-Flash-Next on four
@@ -2397,27 +2204,6 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) {
return RAD_OK;
}
/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most
* kMaxProtect. Absent or empty is none. */
static int protect_of(const RadArgs* a, long long n_local, Protect* p) {
*p = Protect{};
const char* s = r4d_gets(a, "protect");
if (!s) return RAD_OK;
long long prev = -1;
while (*s) {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect)
return R4D_NO(RAD_E_SHAPE);
p->e[p->n++] = (uint16_t)v;
prev = v;
s = end;
if (*s == ',') ++s;
else if (*s) return R4D_NO(RAD_E_SHAPE);
}
return RAD_OK;
}
/* The pair in one launch. Operands are the two ops' own, selection first: logits -> expert_ids,
* expert_w, sorted_tok, expert_offset, expert_count. The checks are the two shims' checks.
*
@@ -2518,7 +2304,8 @@ extern "C" int64_t r4d_rad_moe_scatter_scratch(const RadArgs* a) {
return n_tile * n_expert * (long long)sizeof(int32_t);
}
extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
/* moe_scatter, and with `inv` (moe_scatter_inv's fifth operand) the inverse beside it. */
static int moe_scatter_body(const RadArgs* a, RadStream s, const RadTensor* inv) {
const RadTensor* ids = r4d_opt(a, 0);
const RadTensor* sorted = r4d_opt(a, 1);
const RadTensor* off = r4d_opt(a, 2);
@@ -2543,15 +2330,24 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
const int prc = protect_of(a, n_expert, &prot);
if (prc != RAD_OK) return prc;
if (inv && (inv->dtype != RAD_I32 || !r4d_contig(inv) || r4d_numel(inv) < T))
return R4D_NO(RAD_E_SHAPE);
const int32_t* idp = (const int32_t*)ids->data;
int32_t* sp = (int32_t*)sorted->data;
int32_t* op = (int32_t*)off->data;
int32_t* cp = (int32_t*)cnt->data;
int32_t* ip = inv ? (int32_t*)inv->data : nullptr;
if (T <= (long long)kScatterSmall) {
hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(256), 0, (hipStream_t)s,
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base,
prot);
if (ip)
hipLaunchKernelGGL(scatter_small_kernel<true>, dim3(1), dim3(kScatWaves * kWave), 0,
(hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
else
hipLaunchKernelGGL(scatter_small_kernel<false>, dim3(1), dim3(kScatWaves * kWave), 0,
(hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
R4D_MOE_CHK();
return RAD_OK;
}
@@ -2568,13 +2364,30 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
hipLaunchKernelGGL(scatter_scan_kernel, dim3(1), dim3(kMaxExpert), 0, (hipStream_t)s,
bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert);
R4D_MOE_CHK();
hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), 0,
(hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot);
if (ip)
hipLaunchKernelGGL(scatter_place_kernel<true>, dim3((unsigned)n_tile), dim3(kScatterTile),
0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
else
hipLaunchKernelGGL(scatter_place_kernel<false>, dim3((unsigned)n_tile), dim3(kScatterTile),
0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot, ip);
R4D_MOE_CHK();
return RAD_OK;
}
extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
return moe_scatter_body(a, s, nullptr);
}
/* moe_scatter that also writes, for every slot, its row in `sorted_tok` (-1 when dropped): the
* table moe_gather_inv reads instead of rebuilding it from `sorted_tok`. Same sort, same scratch. */
extern "C" int r4d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) {
const RadTensor* inv = r4d_opt(a, 4);
if (!inv) return R4D_NO(RAD_E_INVAL);
return moe_scatter_body(a, s, inv);
}
/* The weight-table operand from the core's tensor. A zero leading stride marks a pointer array
* (abi/rad_runtime.h, RAD_WTAB); otherwise it is a stacked plane with the stride in elements of the
* weight's dtype (bytes for E4M3). */
@@ -3220,7 +3033,9 @@ extern "C" int64_t r4d_rad_moe_gather_scratch(const RadArgs* a) {
return M * top_k * (long long)sizeof(int32_t);
}
extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
/* moe_gather, or with `given` moe_gather_inv, whose third operand is the inverse moe_scatter_inv
* wrote: no prepass and no self-scan, and the same kernel at the same T, so the same sums. */
static int moe_gather_body(const RadArgs* a, RadStream s, bool given) {
const RadTensor* ye = r4d_opt(a, 0);
const RadTensor* ew = r4d_opt(a, 1);
const RadTensor* sorted = r4d_opt(a, 2);
@@ -3232,7 +3047,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
const long long n = r4d_geti_or(a, "n", 0);
const long long top_k = r4d_geti_or(a, "top_k", 0);
if (n <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE);
if (ye->dtype != RAD_BF16 || ew->dtype != RAD_BF16 || Y->dtype != RAD_BF16)
if (ye->dtype != RAD_BF16 || (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) || Y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
if (sorted->dtype != RAD_I32 || !r4d_contig(sorted)) return R4D_NO(RAD_E_STRIDE);
/* The shared arm is a pair: the plane and its per-row gate, or neither. */
@@ -3253,12 +3068,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
/* SELF: small enough for the gather to build its own slot table, skipping the two prepass
* kernels (see gather_kernel). Bounded on T because each of the M*gy blocks repeats the scan;
* at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. */
const bool self = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots;
* at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. A given
* table replaces both, and `small` keeps the kernel choice the self-scan would make. */
const bool small = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots;
const bool self = small && !given;
const int64_t need = self ? 0 : T * (long long)sizeof(int32_t);
int32_t* inv = nullptr;
if (!self) {
const int64_t need = self || given ? 0 : T * (long long)sizeof(int32_t);
int32_t* inv = given ? (int32_t*)sorted->data : nullptr;
if (!self && !given) {
if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH);
inv = (int32_t*)a->scratch;
const unsigned blocks = (unsigned)((T + 255) / 256);
@@ -3288,7 +3105,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
auto al16 = [](const void* p, long long ld) {
return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0;
};
const bool wide_ok = !self && top_k <= (long long)kGatherWideSlots &&
const bool wide_ok = ew->dtype == RAD_BF16 && !small && top_k <= (long long)kGatherWideSlots &&
n % (long long)kGatherWideCols == 0 && al16(ye->data, ye_ld) &&
al16(Y->data, y_ld) && (!sh || al16(sh->data, sh_ld));
const int gpin = g_moe_gather_pin;
@@ -3310,6 +3127,17 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
}
const unsigned gy = (unsigned)((n + 255) / 256);
if (ew->dtype == RAD_F32) {
hipLaunchKernelGGL(
(gather_kernel<256, true>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n,
(uint32_t)top_k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld,
self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T,
sh ? (const uint16_t*)sh->data : nullptr, sh ? (const uint16_t*)sg->data : nullptr,
(uint32_t)sh_ld, (uint32_t)sg_ld, sig);
R4D_MOE_CHK();
return RAD_OK;
}
hipLaunchKernelGGL((gather_kernel<256>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s,
(const uint16_t*)ye->data, (const uint16_t*)ew->data, inv,
(uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k,
@@ -3322,6 +3150,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
return RAD_OK;
}
extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
return moe_gather_body(a, s, false);
}
extern "C" int r4d_rad_moe_gather_inv(const RadArgs* a, RadStream s) {
return moe_gather_body(a, s, true);
}
extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* sc = r4d_opt(a, 1);
+92
View File
@@ -0,0 +1,92 @@
// r4d_moe_gather.h -- moe_gather's kernel for decode and short passes, beside its launcher in
// r4d_moe.hip; tests/r4d_emu runs it from here against the inverse the sort writes.
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_common.h"
// Internal linkage, as the unit's own definition had.
namespace r4d_moegather {
namespace {
/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the
* column, and read inside the column loop each `inv` load would serialise the `ye` load behind it
* (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline.
*
* The column range is also split over blocks, since decode has one token. Neither change touches
* the sum: each column's slots are still summed in ascending order within one block. */
constexpr uint32_t kGatherSlots = 64;
/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not
* launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k),
* giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it
* (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches
* (~2.1 us each) of single-block kernels.
*
* `sorted == nullptr` selects the prepass path, used at prefill. */
constexpr uint32_t kGatherSelfT = 512;
template <bool F32>
__device__ float gather_weight(const void* ew, size_t i) {
if constexpr (F32) return ((const float*)ew)[i];
else return bf16_to_f32(((const uint16_t*)ew)[i]);
}
template <uint32_t NTHR, bool F32 = false>
__global__ __launch_bounds__(NTHR) void gather_kernel(
const uint16_t* __restrict__ ye, const void* __restrict__ ew,
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const int32_t* __restrict__ sorted, uint32_t T,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig) {
__shared__ int32_t s_i[kGatherSlots];
__shared__ float s_w[kGatherSlots];
const uint32_t t = blockIdx.x;
if (t >= M) return;
const bool cached = top_k <= kGatherSlots;
/* The shared arm's scalar, read once per block as scale_rows reads it once per row. */
float gate = 0.0f;
if (sh) {
const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]);
gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
if (sorted) {
/* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the
* prepass is two kernels). */
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1;
__syncthreads();
const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k;
for (uint32_t i = threadIdx.x; i < T; i += NTHR) {
const int32_t f = sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i;
}
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR)
s_w[j] = gather_weight<F32>(ew, (size_t)t * ew_ld + j);
__syncthreads();
} else if (cached) {
for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) {
s_i[j] = inv[t * top_k + j];
s_w[j] = gather_weight<F32>(ew, (size_t)t * ew_ld + j);
}
__syncthreads();
}
for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) {
float acc = 0.0f;
for (uint32_t j = 0; j < top_k; ++j) {
const int32_t i = cached ? s_i[j] : inv[t * top_k + j];
if (i < 0) continue;
const float wj = cached ? s_w[j] : gather_weight<F32>(ew, (size_t)t * ew_ld + j);
if constexpr (F32) acc = fmaf(wj, bf16_to_f32(ye[(size_t)i * ye_ld + c]), acc);
else acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]);
}
const uint16_t g = f32_to_bf16(acc);
if (!sh) { y[(size_t)t * y_ld + c] = g; continue; }
/* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather
* as bf16 and narrows its own product before adding. */
const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate);
y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g));
}
}
} // namespace
} // namespace r4d_moegather
File diff suppressed because it is too large. Load diff
+198
View File
@@ -0,0 +1,198 @@
// r4d_moe_sort.h -- the routed slots' stable counting sort in one workgroup, shared by every
// kernel that ends in it: moe_scatter's small form and router_topk_scatter (r4d_moe.hip), and
// GLM's router_sigmoid_topk_scatter (r4d_glm.hip). One definition, so a fused selection and the
// standalone sort place every slot alike; tests/r4d_emu runs it from here.
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include <cstdlib>
#include "r4d_args.h"
#include "r4d_common.h"
// Internal linkage, as each unit's own definitions had: the same code generation in every kernel
// that takes the sort.
namespace r4d_moesort {
namespace {
constexpr uint32_t kSortWave = 32;
/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in
* registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers
* Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router
* instantiation. */
constexpr uint32_t kMaxExpert = 512;
/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output
* dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort
* places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and
* [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an
* expert's place is itself. */
constexpr uint32_t kMaxProtect = 8;
struct Protect {
uint32_t n;
uint16_t e[kMaxProtect];
};
/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */
__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) {
int32_t below = 0;
for (uint32_t j = 0; j < p.n; ++j) {
if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j);
below += (int32_t)p.e[j] < e;
}
return e - below;
}
/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most
* kMaxProtect. Absent or empty is none. */
inline int protect_of(const RadArgs* a, long long n_local, Protect* p) {
*p = Protect{};
const char* s = r4d_gets(a, "protect");
if (!s) return RAD_OK;
long long prev = -1;
while (*s) {
char* end = nullptr;
const long long v = std::strtoll(s, &end, 10);
if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect)
return R4D_NO(RAD_E_SHAPE);
p->e[p->n++] = (uint16_t)v;
prev = v;
s = end;
if (*s == ',') ++s;
else if (*s) return R4D_NO(RAD_E_SHAPE);
}
return RAD_OK;
}
/* ================================================================== the small sort
*
* One workgroup does the whole sort, for T <= kScatterSmall, which covers every decode and verify
* step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch instead of three.
* Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert counts, and each slot
* placed by its rank inside its expert's run.
*
* On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work:
*
* - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one
* barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts).
* - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its
* expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's
* place is the number of the run's slots with a lower index. That count is as long as the run
* (a row picks an expert at most once), far shorter than counting all earlier slots.
*
* Stable and byte-identical: a slot's place is its position among the same expert's slots in
* ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so
* none waits on or invalidates the vector memory path. */
constexpr uint32_t kScatterSmall = 1024;
/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the
* workgroup's wave count, which sizes the scan's exchange. */
template <uint32_t NW>
struct ScatterLds {
static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave);
int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */
int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */
int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */
int32_t cnt[kMaxExpert + 1];
int32_t off[kMaxExpert + 1];
int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */
};
/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then
* the upper row adds the lower row's total. Lanes shifted in from outside the row read zero
* (bound_ctrl). */
__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) {
x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
const int32_t lo = __builtin_amdgcn_readlane(x, 15);
return lane >= 16u ? x + lo : x;
}
/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has
* written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the
* standalone sort and the fused kernels. The workgroup is exactly NW waves.
*
* INV also writes the inverse: `inv[i]` is slot i's row in `sorted`, -1 for a dropped slot, the
* table moe_gather would otherwise build from `sorted`. */
template <uint32_t NW, bool INV = false>
__device__ __forceinline__ void scatter_small_place(
int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t T, uint32_t n_expert, ScatterLds<NW>& sl, int32_t* __restrict__ inv = nullptr) {
const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1);
}
lds_barrier();
/* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same
* in every thread. */
int32_t carry = 0;
for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) {
const uint32_t e = b + tid;
const int32_t v = (e < n_expert) ? sl.cnt[e] : 0;
const int32_t x = wave_incl_scan_i32(v, lane);
if (lane == kSortWave - 1) sl.wt[t][wave] = x;
lds_barrier();
int32_t below = 0, tot = 0;
#pragma unroll
for (uint32_t k = 0; k < NW; ++k) {
const int32_t c = sl.wt[t][k];
below += (k < wave) ? c : 0;
tot += c;
}
if (e < n_expert) {
const int32_t o = carry + below + x - v; /* inclusive -> exclusive */
sl.off[e] = o;
off[e] = o;
cnt[e] = v;
}
carry += tot;
}
if (tid == 0) off[n_expert] = carry;
lds_barrier();
for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i;
}
lds_barrier();
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = sl.e[i];
if (e < 0) {
if constexpr (INV) inv[i] = -1;
continue;
}
const int32_t o = sl.off[e], n = sl.cnt[e];
int32_t rank = 0;
for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i;
sorted[o + rank] = (int32_t)i;
if constexpr (INV) inv[i] = o + rank;
}
}
/* moe_scatter's small form: the slot list from `ids`, then the sort. A template only so a unit that
* includes this header and does not launch it compiles no kernel. */
constexpr uint32_t kScatWaves = 8; /* 256 threads */
template <bool INV>
__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel(
const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off,
int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot,
int32_t* __restrict__ inv) {
__shared__ ScatterLds<kScatWaves> sl;
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0;
for (uint32_t i = tid; i < T; i += blockDim.x) {
const int32_t e = ids[i] - base;
sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1;
}
lds_barrier();
scatter_small_place<kScatWaves, INV>(sorted, off, cnt, T, n_expert, sl, inv);
}
} // namespace
} // namespace r4d_moesort
+9
View File
@@ -56,6 +56,15 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
}
// Row d = 0 as immediates, for kernels that fold the E8M0 scale in F32 and need the exact e2m1
// values: no table load, v_perm_b32 takes the two words as literals. tests/r4d_emu/test_moemx
// holds them to row 0 of the table.
#define R4D_MXFP4_MAG0_LO 0x3c383000u
#define R4D_MXFP4_MAG0_HI 0x4c484440u
static __device__ __forceinline__ void r4d_mxfp4_unpack8_exact(unsigned int wv, unsigned int* lo,
unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, R4D_MXFP4_MAG0_LO, R4D_MXFP4_MAG0_HI, lo, hi);
}
// The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the
// last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero
+47
View File
@@ -296,6 +296,15 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream);
/* -- the gated residual (r4d_hc_bf16.hip) -- */
int r4d_rad_hc_enter (const RadArgs*, RadStream);
int r4d_rad_mhc_pre(const RadArgs*, RadStream);
int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream);
int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream);
int r4d_rad_kda_update(const RadArgs*, RadStream);
int r4d_rad_moe_mxfp4(const RadArgs*, RadStream);
int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_mhc_post(const RadArgs*, RadStream);
int r4d_rad_mhc_contract(const RadArgs*, RadStream);
int r4d_rad_mtp_enter (const RadArgs*, RadStream);
int64_t r4d_rad_mtp_enter_scratch(const RadArgs*);
int r4d_rad_hc_read (const RadArgs*, RadStream);
@@ -604,6 +613,35 @@ int r4d_rad_fill (const RadArgs*, RadStream);
int r4d_rad_logit_softcap (const RadArgs*, RadStream);
int r4d_rad_scale (const RadArgs*, RadStream);
int r4d_rad_silu_mul (const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped(const RadArgs*, RadStream);
int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream);
int r4d_rad_dsa_pool(const RadArgs*, RadStream);
int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_dsa_query(const RadArgs*, RadStream);
int r4d_rad_fp8_f32scale(const RadArgs*, RadStream);
int r4d_rad_moe_fp8_f32scale(const RadArgs*, RadStream);
int r4d_layout_fp8_f32scale(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_shape_dsa_query(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gemm_nt_f32(const RadArgs*, RadStream);
int r4d_shape_gemm_nt_f32(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_mla_project(const RadArgs*, RadStream);
int r4d_shape_mla_project(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_dsa_score(const RadArgs*, RadStream);
int r4d_shape_dsa_score(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_mla_attn(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_scratch(const RadArgs*);
int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*);
int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream);
int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk_scatter(const RadArgs*, RadStream);
int r4d_rad_moe_scatter_inv(const RadArgs*, RadStream);
int r4d_shape_moe_scatter_inv(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_moe_gather_inv(const RadArgs*, RadStream);
int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_gelu_mul (const RadArgs*, RadStream);
int r4d_rad_rope (const RadArgs*, RadStream);
/* -- the vision tower's ops (r4d_vit_bf16.hip) -- */
@@ -656,6 +694,13 @@ int r4d_shape_scatter_rows_u8(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_cast (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_enter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_mhc_pre(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*);
int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*);
@@ -750,6 +795,8 @@ int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*);
* Pure host code, like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp. */
int r4d_fuse_rmsnorm_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gated_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
+381
View File
@@ -469,6 +469,50 @@ static const RadParamSpec pHcPlain[] = {
static const RadOperandSpec oHcEnter[] = {
{ "x", RAD_OPD_IN, 0 }, { "h", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pMhcPre[] = {
P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"),
P_F64("hc_eps"), P_STR("dtype"),
};
static const RadOperandSpec oMhcPre[] = {
{"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"scale", RAD_OPD_WEIGHT, 0},
{"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0},
{"comb", RAD_OPD_OUT, 0},
};
static const RadParamSpec pMhcPrePartial[] = {
P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("chunk"), P_INT("first"), P_INT("chunks"),
P_STR("dtype"),
};
static const RadOperandSpec oMhcPrePartial[] = {
{"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"part", RAD_OPD_OUT, 0},
};
static const RadParamSpec pMhcPreFinish[] = {
P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"),
P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype"),
};
static const RadOperandSpec oMhcPreFinish[] = {
{"part", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"scale", RAD_OPD_WEIGHT, 0},
{"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0},
{"comb", RAD_OPD_OUT, 0},
};
static const RadOperandSpec oMhcPost[] = {
{"x", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"post", RAD_OPD_IN, 0},
{"comb", RAD_OPD_IN, 0}, {"out", RAD_OPD_OUT, 0},
};
static const RadOperandSpec oMhcContract[] = {
{"h", RAD_OPD_IN, 0}, {"x", RAD_OPD_OUT, 0},
};
static const RadParamSpec pKdaUpdate[] = {
P_INT("M"), P_INT("heads"), P_INT("head_k"), P_INT("head_v"), P_F64("lower_bound"),
P_F64("scale"), P_F64("l2_eps"), P_STR("mode"), P_STR("dtype"),
P_STRO("state_form"),
};
static const RadOperandSpec oKdaUpdate[] = {
{"q", RAD_OPD_IN, 0}, {"k", RAD_OPD_IN, 0}, {"v", RAD_OPD_IN, 0},
{"a", RAD_OPD_IN, 0}, {"b", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0},
{"dt_bias", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0},
{"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1},
{"o", RAD_OPD_OUT, 0},
};
static const RadOperandSpec oHcWrite[] = {
{ "y", RAD_OPD_IN, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 },
};
@@ -816,6 +860,16 @@ static const RadOperandSpec oMoeScatter[] = {
{ "expert_offset", RAD_OPD_OUT, 0 },
{ "expert_count", RAD_OPD_OUT, 0 },
};
/* moe_scatter with each slot's row in `sorted_tok` beside it: moe_gather_inv reads that table
* instead of rebuilding it. Ops of their own, since the shared vocabulary fixes moe_scatter's and
* moe_gather's operands. */
static const RadOperandSpec oMoeScatterInv[] = {
{ "expert_ids", RAD_OPD_IN, 0 },
{ "sorted_tok", RAD_OPD_OUT, 0 },
{ "expert_offset", RAD_OPD_OUT, 0 },
{ "expert_count", RAD_OPD_OUT, 0 },
{ "inverse", RAD_OPD_OUT, 0 },
};
/* `a_order` ("token" or "sorted") says which rows the activation has: one per token, gathered
* through sorted_tok, or one per (token, slot) already in scatter order. A routed block's two
* grouped GEMMs differ (gate_up reads the block input, down reads gate_up's output), and the row
@@ -902,6 +956,14 @@ static const RadOperandSpec oMoeGather[] = {
{ "shared_gate", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oMoeGatherInv[] = {
{ "y_expert", RAD_OPD_IN, 0 },
{ "expert_w", RAD_OPD_IN, 0 },
{ "inverse", RAD_OPD_IN, 0 },
{ "shared", RAD_OPD_IN, 1 },
{ "shared_gate", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
/* `vocab_off` and `pairs` are the vocab-parallel form, both absent on a single-rank graph (which
* keeps it byte-identical to the unsplit form). With them, `x` is one rank's slice, `idx` carries
@@ -1566,6 +1628,51 @@ static const RadParamSpec pMnDtype[] = {
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"),
P_STR("dtype") };
static const RadParamSpec pSwigluClampedQuant[] = { P_INT("M"), P_INT("n"), P_F64("limit"),
P_INT("group"), P_STR("dtype") };
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"),
P_INTO("block_size") };
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
P_INT("blocks"), P_INT("block_size"), P_F64("scale"),
P_STR("dtype") };
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
static const RadOperandSpec oMlaAttn[] = { { "q", RAD_OPD_IN, 0 },
{ "kv", RAD_OPD_IN, 0 },
{ "bt", RAD_OPD_IN, 0 },
{ "length", RAD_OPD_IN, 0 },
{ "out", RAD_OPD_OUT, 0 } };
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
P_INT("blocks"), P_INT("seqs"), P_STR("dtype") };
static const RadOperandSpec oDsaScore[] = {
{ "q", RAD_OPD_IN, 0 }, { "q_scale", RAD_OPD_IN, 0 }, { "gate", RAD_OPD_IN, 0 },
{ "k", RAD_OPD_IN, 0 }, { "k_scale", RAD_OPD_IN, 1 }, { "bt", RAD_OPD_IN, 0 },
{ "cu", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 }
};
static const RadOperandSpec oDsaPool[] = {
{ "kg", RAD_OPD_IN, 0 }, { "ape", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 }, { "page", RAD_OPD_IN, 1 }, { "cache", RAD_OPD_INOUT, 1 }
};
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
static const RadOperandSpec oRouterSigmoid[] = {
{ "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 },
{ "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 }
};
/* router_sigmoid_topk and moe_scatter as one op, with `ids` named once, and the `fill` of an
* ungated shared arm's gate with 1 as an optional output. */
static const RadParamSpec pRouterSigmoidScatter[] = { P_INT("M"), P_INT("n_expert"),
P_INTO("n_local"), P_INT("top_k"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype"),
P_INTO("expert_base"), P_STRO("protect") };
static const RadOperandSpec oRouterSigmoidScatter[] = {
{ "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 },
{ "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 },
{ "sorted_tok", RAD_OPD_OUT, 0 }, { "expert_offset", RAD_OPD_OUT, 0 },
{ "expert_count", RAD_OPD_OUT, 0 }, { "gate", RAD_OPD_OUT, 1 },
{ "inverse", RAD_OPD_OUT, 1 }
};
/* `logit_softcap`'s, matching ref's `pMnCap` (spec §2.3). `cap` must be > 0; the op refuses a
* non-positive cap (a division by zero in every lane). */
static const RadParamSpec pMnCap[] = {
@@ -2432,6 +2539,23 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("mul_weight", pMulWeight, oMulWeight,
"y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row "
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."),
SCHEMA("mla_attn", pMlaAttn, oMlaAttn,
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths."),
SCHEMA("mla_project", pMlaProject, oGemmNt,
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."),
SCHEMA("dsa_score", pDsaScore, oDsaScore,
"Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf."),
SCHEMA("dsa_pool", pDsaPool, oDsaPool,
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8."),
SCHEMA("dsa_query", pMnDtype, oQuantActFp8,
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head."),
SCHEMA("gemm_nt_f32", pGemmNt, oGemmNt,
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision."),
SCHEMA("swiglu_clamped", pSwigluClamped, oGateUp,
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half."),
SCHEMA("swiglu_clamped_quant_fp8", pSwigluClampedQuant, oGatedQuantFp8,
"`swiglu_clamped` then `quant_act_fp8` over its product, in one pass: the codes are "
"taken over the BF16-ROUNDED product, which `out_bf16` receives when present."),
SCHEMA("silu_mul", pMnDtype, oGateUp,
"y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, "
"which is the order rad-convert fuses gate_proj and up_proj in."),
@@ -2673,6 +2797,22 @@ static const RadOpSchema kSchemas[] = {
"the two ops it replaces."),
SCHEMA("hc_enter", pHcPlain, oHcEnter,
"h[s] = x for each of the hc streams -- the wide residual stream's first value."),
SCHEMA("mhc_pre", pMhcPre, oMhcPre,
"Whole-residual RMS-scaled projection, sigmoid gates and Sinkhorn mixing; coefficients f32."),
SCHEMA("mhc_pre_partial", pMhcPrePartial, oMhcPrePartial,
"mhc_pre's projection over chunks [first, first+chunks) of `chunk` residual columns: "
"per chunk the hc*(hc+2) coefficient partials and the sum of squares, zero-padded to "
"a multiple of four floats; tensor-parallel ranks each take their chunks."),
SCHEMA("mhc_pre_finish", pMhcPreFinish, oMhcPreFinish,
"mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing and the "
"collapse of h; the pair is mhc_pre."),
SCHEMA("mhc_post", pHcPlain, oMhcPost,
"out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]; separate output."),
SCHEMA("mhc_contract", pHcPlain, oMhcContract,
"Mean over the hc residual streams, rounded once to dtype."),
SCHEMA("kda_update", pKdaUpdate, oKdaUpdate,
"Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. "
"Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."),
SCHEMA("hc_read", pHcRead, oHcRead,
"the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and "
"the mean of the gated streams -- plus the per-branch write gains and, optionally, "
@@ -2722,6 +2862,14 @@ static const RadOpSchema kSchemas[] = {
"With `add` present the form is y = bf16(x * act(s)) + add: the product is NARROWED "
"before the sum, which is what makes the fused form bit-identical to the two ops it "
"stands in for rather than merely close to them."),
SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid,
"Single-group sigmoid routing; correction bias selects experts, original scores weight them."),
SCHEMA("router_sigmoid_topk_scatter", pRouterSigmoidScatter, oRouterSigmoidScatter,
"`router_sigmoid_topk` then `moe_scatter` over its ids, in one launch, and with `gate` "
"present the ungated shared arm's `fill` of its gate with 1; with `inverse` the sort is "
"`moe_scatter_inv`. Every output is the bytes the separate launches write, including a "
"row with fewer finite ranks than top_k. Bounded by the sort's single-workgroup form: "
"M * top_k <= 1024, refused above."),
SCHEMA("router_topk", pRouterTopk, oRouterTopk,
"softmax over ALL n_expert logits, then the top_k of them by value with ties to the "
"lower expert id, then -- if `norm` -- the kept weights renormalised to sum to one. The "
@@ -2755,6 +2903,13 @@ static const RadOpSchema kSchemas[] = {
"does not depend on the scheduler. `protect` lists local experts sorted LAST, in that "
"order, the rest closed up: `expert_offset` and `expert_count` are then in sort order, "
"and a layer's protected experts are one trailing run a second grouped GEMM serves."),
SCHEMA("moe_scatter_inv", pMoeScatter, oMoeScatterInv,
"`moe_scatter`, also writing `inverse`: for every slot token*top_k + slot its row in "
"`sorted_tok`, -1 for a dropped slot. That is the table `moe_gather` builds from "
"`sorted_tok` before it sums, so `moe_gather_inv` reads it instead."),
SCHEMA("moe_gather_inv", pMoeGather, oMoeGatherInv,
"`moe_gather` reading the slot table `moe_scatter_inv` wrote instead of rebuilding it "
"from `sorted_tok`: the same sums in ascending slot order, the same bytes."),
SCHEMA("moe_gemm", pMoeGemm, oMoeGemm,
"y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range "
"contains i, both operands unquantised and one accumulator over K. `a_order` picks "
@@ -3662,6 +3817,77 @@ static const RadConstraint cHcReadE4m3[] = {
static const RadConstraint cHcPlain[] = {
C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"),
};
static const RadConstraint cMhcPlain[] = {
C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), C_LE("n", 16384),
C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"),
};
/* GLM's split projection only: eight 2048-column chunks of a 4 x 4096 residual. */
static const RadConstraint cMhcPrePartial[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4), C_EQ("chunk", 2048),
C_GE("first", 0), C_LE("first", 7), C_GE("chunks", 1), C_LE("chunks", 8), C_IN("dtype", "bf16"),
};
static const RadConstraint cMhcPreFinish[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4),
C_EQ("chunk", 2048), C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256),
};
static const RadConstraint cKdaUpdate[] = {
C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535),
C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"),
C_IN("dtype", "bf16"),
};
static const RadConstraint cMhcPre[] = {
C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1),
C_LE("n", 16384), C_GE("hc", 2), C_LE("hc", 8),
C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256),
};
static const RadConstraint cDsaPool[] = { C_GE("M", 1), C_EQ("n", 128), C_EQ("ratio", 4),
C_IN("dtype", "bf16") };
static const RadConstraint cDsaQuery[] = { C_GE("M", 1), C_LE("M", 2147483644), C_EQ("n", 128),
C_IN("dtype", "bf16") };
static const RadConstraint cFp8F32Scale[] = {
C_GE("M", 1), C_GE("N", 128), C_DIV("N", 128), C_GE("K", 128),
C_DIV("K", 128), C_EQ("group", 128), C_IN("dtype", "fp8a8f32")
};
static const RadConstraint cGemmNtF32[] = { C_GE("M", 1), C_LE("M", 65535),
C_GE("N", 1), C_LE("N", 512),
C_GE("K", 1), C_LE("K", 16384),
C_IN("dtype", "bf16") };
static const RadConstraint cDsaScore[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 128), C_EQ("heads", 32),
C_GE("blocks", 1), C_GE("seqs", 1), C_IN("dtype", "fp8_e4m3")
};
static const RadConstraint cMlaAttn[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 1),
C_LE("heads", 64), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16")
};
static const RadConstraint cMlaProject[] = { C_GE("M", 1),
C_LE("M", 65535),
C_GE("heads", 1),
C_LE("heads", 64),
C_EQ("head_dim", 256),
C_EQ("latent_dim", 512),
C_IN("mode", "absorb expand"),
C_IN("dtype", "bf16") };
/* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union
* of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk
* with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the
* positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms.
* RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */
static long long mla_matrix_max_m() {
const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M");
char* end = nullptr;
const long long v = e && *e ? std::strtoll(e, &end, 10) : -1;
return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535;
}
static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
C_LE("M", mla_matrix_max_m()),
C_EQ("latent_dim", 512),
C_GE("heads", 8),
C_LE("heads", 64),
C_DIV("heads", 8),
C_GE("blocks", 1),
C_EQ("block_size", 4),
C_IN("dtype", "bf16") };
/* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase;
* 28672 elements is that budget at hc 4. */
static const RadConstraint cMtpEnter[] = {
@@ -3681,6 +3907,15 @@ static const RadConstraint cRouterTopK[] = {
C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1),
C_LE("top_k", 32), C_IN("dtype", "bf16"),
};
static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_LE("M", 65535),
C_GE("n_expert", 1), C_LE("n_expert", 512),
C_GE("top_k", 1), C_LE("top_k", 32),
C_IN("dtype", "f32") };
/* The sort's single-workgroup form bounds M * top_k at 1024, which the shim checks. */
static const RadConstraint cRouterSigmoidScatter[] = { C_GE("M", 1), C_LE("M", 1024),
C_GE("n_expert", 1), C_LE("n_expert", 512),
C_GE("top_k", 1), C_LE("top_k", 32),
C_IN("dtype", "f32") };
/* The selection's bounds and the skinny GEMM's decode band: four 16-row tiles. */
static const RadConstraint cRouterGemmTopkScatter[] = {
C_GE("M", 1), C_LE("M", 64), C_DIV("K", 16), C_GE("n_expert", 1), C_LE("n_expert", 512),
@@ -3693,6 +3928,11 @@ static const RadConstraint cMoeGemmQ[] = {
C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536),
C_GE("top_k", 1), C_EQ("group", 128), C_IN("dtype", "fp8a8"),
};
static const RadConstraint cMoeMx[] = {
C_GE("M", 1), C_LE("M", 32767), C_GE("N", 1), C_DIV("K", 128),
C_GE("n_expert", 2), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32),
C_EQ("group", 128), C_IN("dtype", "mxfp4a8"),
};
/* The same op at a four-bit expert weight: same band and operands, only the stored weight plane
* and scale grid differ, so the dtype string alone separates the rows.
*
@@ -3916,6 +4156,10 @@ static const RadConstraint cArGatherHcWrite4[] = {
static const RadConstraint cGatedQuantFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
};
static const RadConstraint cSwigluClampedQuant[] = {
C_GE("M", 1), C_LE("M", 65535), C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "bf16"),
};
/* n divisible by the group, as in cHadQuantActFp8. */
static const RadConstraint cGatedHadQuantFp8[] = {
C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
@@ -4805,6 +5049,70 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
r4d_shape_scale },
{ "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax",
"latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4",
"bf16 operands; FP32 probabilities via high/low BF16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 1, ROW(cMlaMatrix), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_matrix, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "mla_attn_bf16", "mla_attn", "attn", "absorbed MLA with a shared latent cache and split history",
"latent_dim=512, heads<=64, block_size=4", "bf16 Q/cache/output, f32 softmax and partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaAttn), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn, r4d_rad_mla_attn_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "gemm_fp8a8_f32scale", "gemm_nt_q", "gemm", "FP8 WMMA with canonical F32 block scales",
"N and K multiples of 128; pitched activations and row-major weights", "E4M3 codes, F32 scales, BF16 output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE,
nullptr, nullptr, r4d_rad_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr,
nullptr },
{ "moe_gemm_fp8a8_f32scale", "moe_gemm_q", "moe", "grouped FP8 WMMA with canonical F32 block scales",
"equal parity widths; token/sorted activations; canonical pointer tables", "E4M3 codes, F32 scales, BF16 output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE,
nullptr, nullptr, r4d_rad_moe_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr,
nullptr },
{ "dsa_score_fp8", "dsa_score", "attn", "32-head FP8 WMMA index scoring over paged keys",
"n=128, heads=32; ragged sequences and pitched tensors", "E4M3 codes, f32 scales and gates",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaScore), NOTUNE,
nullptr, nullptr, r4d_rad_dsa_score, nullptr, nullptr, nullptr,
r4d_shape_dsa_score },
{ "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections",
"head_dim=256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaProject), NOTUNE,
nullptr, nullptr, r4d_rad_mla_project, nullptr, nullptr, nullptr,
r4d_shape_mla_project },
{ "dsa_query_fp8", "dsa_query", "attn", "normalized index queries in wave-local registers",
"n=128; flattened heads and pitched rows", "bf16 input, E4M3 codes and power-of-two f32 scale",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaQuery), NOTUNE,
nullptr, nullptr, r4d_rad_dsa_query, nullptr, nullptr, nullptr,
r4d_shape_dsa_query },
{ "gemm_nt_f32_bf16", "gemm_nt_f32", "gemm", "F32 routing and index gate projection",
"N<=512, K<=16384; pitched rows", "bf16 input, f32 weights and output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmNtF32), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_nt_f32, nullptr, nullptr, nullptr,
r4d_shape_gemm_nt_f32 },
{ "dsa_pool_fp8", "dsa_pool", "attn", "learned compressed index keys in wave-local registers",
"n=128, ratio=4; pitched rows", "bf16 keys/gates, f32 position bias; FP8 codes and f32 scale",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaPool), NOTUNE,
nullptr, nullptr, r4d_rad_dsa_pool, nullptr, nullptr, nullptr,
r4d_shape_dsa_pool },
{ "swiglu_clamped_bf16", "swiglu_clamped", "elem",
"asymmetrically clipped SwiGLU", "positive finite limit; pitched rows",
"bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_swiglu_clamped, nullptr, nullptr, nullptr,
r4d_shape_silu_mul },
{ "swiglu_clamped_quant_fp8", "swiglu_clamped_quant_fp8", "quant",
"asymmetrically clipped SwiGLU and the fp8 activation quantiser in one pass",
"positive finite limit; n a multiple of 4; the gated operand is [M][2n], gate then up; "
"group 128; pitched rows",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes "
"are taken over the BF16-ROUNDED product",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cSwigluClampedQuant), NOTUNE,
nullptr, nullptr, r4d_rad_swiglu_clamped_quant_fp8, nullptr, nullptr, nullptr,
r4d_shape_gated_quant_fp8, nullptr,
/* `swiglu_clamped` + `quant_act_fp8` (r4d_fuse.cpp). */
r4d_fuse_swiglu_clamped_quant_fp8 },
{ "silu_mul_bf16", "silu_mul", "elem",
"silu-gated product over a fused [M, 2n] gate_up",
"any n; the gate is the first half",
@@ -5663,6 +5971,37 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update, nullptr, nullptr, nullptr, nullptr,
nullptr, r4d_fuse_gdn_conv_recurrent_update },
{ "kda_update_k128_v128_bf16", "kda_update", "gdn", "per-channel KDA recurrence and candidate rollback",
"heads 1..65535, K=V=128, prefill and verify", "bf16 activations, f32 gates and state",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKdaUpdate), NOTUNE,
nullptr, nullptr, r4d_rad_kda_update, nullptr, nullptr, nullptr,
r4d_shape_kda_update },
{ "mhc_pre_bf16", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing",
"M 1..65535, n 1..16384, hc 2..8, iterations 1..256", "bf16 activation, f32 weights and coefficients",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPre), NOTUNE,
nullptr, nullptr, r4d_rad_mhc_pre, nullptr, nullptr, nullptr,
r4d_shape_mhc_pre },
{ "mhc_pre_partial_bf16", "mhc_pre_partial", "norm", "mHC projection partials of a chunk range",
"n 4096, hc 4, chunk 2048 (GLM)", "bf16 activation, f32 weights and partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPrePartial), NOTUNE,
nullptr, nullptr, r4d_rad_mhc_pre_partial, nullptr, nullptr, nullptr,
r4d_shape_mhc_pre_partial },
{ "mhc_pre_finish_bf16", "mhc_pre_finish", "norm", "mHC gates and Sinkhorn mixing from gathered partials",
"n 4096, hc 4, chunk 2048 (GLM), iterations 1..256", "bf16 activation, f32 partials and coefficients",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPreFinish), NOTUNE,
nullptr, nullptr, r4d_rad_mhc_pre_finish, nullptr, nullptr, nullptr,
r4d_shape_mhc_pre_finish },
{ "mhc_post_bf16", "mhc_post", "norm", "source-to-destination manifold residual update",
"M 1..65535, n 1..16384, hc 2..8", "bf16 activation, f32 coefficients",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE,
nullptr, nullptr, r4d_rad_mhc_post, nullptr, nullptr, nullptr,
r4d_shape_mhc_post },
{ "mhc_contract_bf16", "mhc_contract", "norm", "mean over manifold residual streams",
"M 1..65535, n 1..16384, hc 2..8", "bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE,
nullptr, nullptr, r4d_rad_mhc_contract, nullptr, nullptr, nullptr,
r4d_shape_mhc_contract },
/* ---------------------------------------------------------------- the gated residual --------
* r4d_hc_bf16.hip. Three rows; the read is two launches behind one entry point, because `x`
* depends on every column of the low-rank waist and the kernel boundary is the grid-wide
@@ -6275,6 +6614,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_scale_rows, nullptr, nullptr, nullptr,
r4d_shape_scale_rows },
{ "router_sigmoid_topk_f32", "router_sigmoid_topk", "moe",
"sigmoid correction-bias routing", "single group, experts <=512, top_k<=32",
"f32 logits, bias and weights; i32 ids", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRouterSigmoid), NOTUNE,
nullptr, nullptr, r4d_rad_router_sigmoid_topk, nullptr, nullptr, nullptr,
r4d_shape_router_sigmoid_topk },
{ "router_sigmoid_topk_scatter_f32", "router_sigmoid_topk_scatter", "moe",
"sigmoid correction-bias routing, the stable counting sort and the ungated shared gate in one "
"launch", "single group, experts <=512, top_k<=32, M*top_k<=1024",
"f32 logits, bias and weights; i32 ids, sorted slots, offsets and counts; bf16 gate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRouterSigmoidScatter), NOTUNE,
nullptr, nullptr, r4d_rad_router_sigmoid_topk_scatter, nullptr, nullptr, nullptr,
r4d_shape_router_sigmoid_topk_scatter, nullptr,
/* `router_sigmoid_topk` + `moe_scatter` (+ `fill` with the gate) (r4d_fuse.cpp). */
r4d_fuse_router_sigmoid_topk_scatter },
{ "router_topk_bf16", "router_topk", "moe",
"softmax over a row of expert logits and the exact top-k of it, one wave a row",
"n_expert <= 512, top_k <= min(n_expert, 32); bf16 logits and weights, i32 ids",
@@ -6317,6 +6672,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_moe_scatter, r4d_rad_moe_scatter_scratch, nullptr, nullptr,
r4d_shape_moe_scatter },
{ "moe_scatter_inv_i32", "moe_scatter_inv", "moe",
"moe_scatter's stable counting sort, also writing every slot's row in the sort",
"n_expert <= 512; one launch at M*top_k <= 1024 and three above it",
"i32 throughout",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cMoeScatter), NOTUNE,
nullptr, nullptr, r4d_rad_moe_scatter_inv, r4d_rad_moe_scatter_scratch, nullptr, nullptr,
r4d_shape_moe_scatter_inv },
{ "moe_gemm_mxfp4a8", "moe_gemm_q", "moe",
"canonical MXFP4 experts decoded in packed words into exact FP8 WMMA tiles, scales folded per 32 values",
"K multiple 128, parity tables, token and sorted order, parts and narrower odd experts",
"E2M1 and E8M0 weights, E4M3 activations and f32 scales, bf16 output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeMx), NOTUNE,
nullptr, nullptr, r4d_rad_moe_mxfp4, nullptr, r4d_rad_layout_moe_mxfp4, nullptr,
r4d_shape_moe_mxfp4 },
{ "moe_gemm_fp8a8", "moe_gemm_q", "moe",
"the grouped block-scaled fp8 GEMM: one contiguous range of expert-sorted rows a block, looping "
"over the experts that range covers",
@@ -6407,6 +6779,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_moe_gather, r4d_rad_moe_gather_scratch, nullptr, nullptr,
r4d_shape_moe_gather },
{ "moe_gather_inv_bf16", "moe_gather_inv", "moe",
"moe_gather over the slot table moe_scatter_inv wrote: no prepass and no scan of the sort",
"any M and n; the decode kernel up to 512 slots, the prefill forms above, as moe_gather",
"bf16 in and out, f32 or bf16 routing weights",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cMoeGather), NOTUNE,
nullptr, nullptr, r4d_rad_moe_gather_inv, nullptr, nullptr, nullptr,
r4d_shape_moe_gather_inv },
{ "rowtopk_bf16", "row_topk", "select",
"exact per-row top-R of a bf16 matrix, descending, ties to the lower column",
"any M, N a multiple of 8, R <= 32; two launches, caller-sized partial buffer",
+4129 -31
View File
File diff suppressed because it is too large. Load diff
+191
View File
@@ -66,6 +66,7 @@
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include "r4d_plugin.h"
#include "rad_sample.h"
@@ -364,6 +365,91 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_mxfp4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const int64_t N1 = rad_param_geti(p, n_p, "N_odd", N), K1 = rad_param_geti(p, n_p, "K_odd", K);
const int64_t ne = pi(p, n_p, "n_expert"), top = pi(p, n_p, "top_k");
const char* order = rad_param_gets(p, n_p, "a_order", "");
const int64_t ar = !std::strcmp(order, "sorted") ? M * top : M;
const int64_t nk = std::max(K, K1), nn = std::max(N, N1);
RadOpdDesc s0 = opd((uint32_t)RAD_U8, (ne + 1) / 2, N, K / 32);
RadOpdDesc s1 = opd((uint32_t)RAD_U8, ne / 2, N1, K1 / 32);
s0.fill = s1.fill = RAD_FILL_INDEX;
s0.idx_const = s1.idx_const = 127;
const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, ar, nk),
opd((uint32_t)RAD_F32, ar, nk / 128),
opd((uint32_t)RAD_FP4E2M1, (ne + 1) / 2, N, K),
s0,
opd_idx(M * top, 0, M * top),
opd_idx(ne + 1, 0, M * top + 1),
opd((uint32_t)RAD_FP4E2M1, ne / 2, N1, K1),
s1,
opd((uint32_t)RAD_BF16, M * top, nn) };
R4D_PICK(l);
}
extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const char* form = rad_param_gets(p, n_p, "state_form", "");
if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED;
const int64_t M = pi(p, n_p, "M"), H = pi(p, n_p, "heads");
const int64_t K = pi(p, n_p, "head_k"), V = pi(p, n_p, "head_v");
const uint32_t D = dt_act(p, n_p, "dtype");
const char* mode = rad_param_gets(p, n_p, "mode", "");
const int64_t history = !std::strcmp(mode, "verify") ? M : 1;
const RadOpdDesc l[] = {
opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H),
opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K),
opd((uint32_t)RAD_F32, history + 1, H, V, K),
opd_idx(1, history, history + 1, -1, RAD_OPD_F_IDX_UNIQUE),
opd_idx(2, 0, M, -1, RAD_OPD_F_IDX_CU),
opd_idx(1, 0, 0, 1), opd_idx(1, 0, 0, 1), opd(D, M, H, V),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_pre(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n),
opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), opd(D, M, n),
opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) };
R4D_PICK(l);
}
/* The partial matrix: per chunk the hc*(hc+2) coefficient partials and the sum of squares, padded to
* a multiple of four floats (docs/OPS.md). */
static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
extern "C" int r4d_shape_mhc_pre_partial(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const int64_t chunks = pi(p, n_p, "chunks");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n),
opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_pre_finish(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const int64_t chunk = pi(p, n_p, "chunk");
const int64_t chunks = chunk > 0 ? hc * n / chunk : 0;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)),
opd(D, M, hc * n), opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)),
opd(D, M, n), opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_post(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, hc * n), opd((uint32_t)RAD_F32, M, hc),
opd((uint32_t)RAD_F32, M, hc * hc), opd(D, M, hc * n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mhc_contract(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, hc * n), opd(D, M, n) };
R4D_PICK(l);
}
/* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` default on, so a
* query naming neither describes what every trunk connection runs; 0 for either describes one of
* the two exceptions: the final mixer, and a read whose consumer wants bf16. */
@@ -496,6 +582,83 @@ extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand,
const RadOpdDesc l[] = { opd(D, M, 2 * n), opd(D, M, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_sigmoid_topk(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k");
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), opd_idx(M, k, ne),
opd(D, M, k) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_sigmoid_topk_scatter(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k");
const int64_t nl = pi(p, n_p, "n_local", ne);
if (ne <= 0 || ne > 512 || k <= 0 || k > ne || nl <= 0 || nl > ne || M * k > 1024)
return RAD_E_UNSUPPORTED;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, ne),
opd((uint32_t)RAD_F32, ne),
opd_idx(M, k, ne),
opd(D, M, k),
opd((uint32_t)RAD_I32, M * k),
opd((uint32_t)RAD_I32, nl + 1),
opd((uint32_t)RAD_I32, nl),
opd((uint32_t)RAD_BF16, M, 1),
opd((uint32_t)RAD_I32, M * k) };
R4D_PICK(l);
}
extern "C" int r4d_shape_dsa_pool(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), ratio = pi(p, n_p, "ratio");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M * ratio, 2 * n),
opd((uint32_t)RAD_F32, ratio, n),
opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, 1),
opd_none(),
opd_none() };
R4D_PICK(l);
}
extern "C" int r4d_shape_dsa_query(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, 1) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), h = pi(p, n_p, "heads"), d = pi(p, n_p, "head_dim"),
l = pi(p, n_p, "latent_dim");
const char* mode = r4d_pgets(p, n_p, "mode");
const bool absorb = mode && !std::strcmp(mode, "absorb"),
expand = mode && !std::strcmp(mode, "expand");
if (!absorb && !expand) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l),
opd((uint32_t)RAD_BF16, h * 2 * d, l),
opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) };
R4D_PICK(list);
}
extern "C" int r4d_shape_dsa_score(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), H = pi(p, n_p, "heads");
const int64_t B = pi(p, n_p, "blocks"), S = pi(p, n_p, "seqs"), pages = S * B;
const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, M, H, n),
opd((uint32_t)RAD_F32, M, H),
opd((uint32_t)RAD_F32, M, H),
opd((uint32_t)RAD_F8E4M3, pages, n),
opd((uint32_t)RAD_F32, pages),
opd_idx(S, B, pages),
opd_idx(S + 1, 0, M, -1, RAD_OPD_F_IDX_CU),
opd_idx(S, 0, 0, B),
opd((uint32_t)RAD_F32, M, B) };
R4D_PICK(l);
}
extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), D = pi(p, n_p, "latent_dim"), H = pi(p, n_p, "heads");
const int64_t B = pi(p, n_p, "blocks"), bs = pi(p, n_p, "block_size"),
pages = std::max((int64_t)2, B * M);
const uint32_t dt = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(dt, M, H, D), opd(dt, pages, 1, bs, D), opd_idx(M, B, pages),
opd_idx(M, 0, 0, B * bs), opd(dt, M, H, D) };
R4D_PICK(l);
}
extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
@@ -1020,6 +1183,12 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op
* r4d_rowtopk_bf16.hip).
* ========================================================================================= */
extern "C" int r4d_shape_gemm_nt_f32(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K),
opd((uint32_t)RAD_F32, M, N) };
R4D_PICK(l);
}
extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
@@ -1243,6 +1412,22 @@ extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, Ra
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_scatter_inv(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t ne = pi(p, n_p, "n_expert");
const int64_t k = pi(p, n_p, "top_k");
if (ne <= 0 || ne > 512 || k <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = {
opd_idx(M, k, ne, -1),
opd((uint32_t)RAD_I32, M * k),
opd((uint32_t)RAD_I32, ne + 1),
opd((uint32_t)RAD_I32, ne),
opd((uint32_t)RAD_I32, M * k),
};
R4D_PICK(l);
}
extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t N0 = pi(p, n_p, "N"), K0 = pi(p, n_p, "K");
@@ -1339,6 +1524,12 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad
R4D_PICK(l);
}
/* moe_gather's list with the slot table in place of `sorted_tok`: the same draw, since a valid
* table, like a valid sort, holds distinct rows of `y_expert` (and -1 for a dropped slot). */
extern "C" int r4d_shape_moe_gather_inv(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return r4d_shape_moe_gather(p, n_p, operand, out);
}
/* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_rowtopk_bf16.hip). R is at
* most 32, stage 2's PT. */
extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand,