Archived
A self-contained HIP kernel plugin for gfx11 (RDNA3) that exposes the
libref-declared ops as device rows the engine can tune and dispatch:
* GEMMs (bf16, f16, int8-activation, vocab) retiled to 16x128 on the
wave-matrix (WMMA) builtins. The retile removes the 8x wave
redundancy of the naive tile and stages the activation once per
16x128 block; the 16-row and 64-row forms share the stage. The k-walk
double-buffers the 128-deep tile (the next tile stages while the
current one multiplies), on the m64 and tiled forms.
* Quantised GEMMs: fp8-e4m3 x e4m3 (tiled and ALU), mxfp4 x a8, w2a8,
w4a16, w5a16, w8a8 (the prefill heights 17..127 on the wave matrix),
and the gated (swiglu) form. E4M3 decodes exactly to f16 through a
256-entry LDS table; the WMMA fragments bit-cast the staged halfs
(a uint16-to-_Float16 assignment is a value conversion, not a
reinterpret).
* Half-precision-accumulate arms (acc = 1) on the m64 wave matrix:
the f16/bf16 16x16x16 builtins with the compile-time opsel half
select.
* Grouped MoE GEMMs (bf16, e4m3 with F32 block scales, mxfp4a8, w4a8),
retiled the same way, over the run-walk / gather structure.
* Normalisation (layernorm / rmsnorm) and the quantisation ops.
* GDN linear-attention, the QSA/KV state ops, and the MoE
router/scatter/gather family (router_topk_scatter, router_sigmoid_topk
with the correction bias, moe_gather, moe_gather_inv; the top-k
router runs to n_expert 512).
Every row implements an op libref declares; the selector (tune) picks
the implementation and the NOTUNE rows carry the untuned default.
Selftest-clean (121 rows, schema + finiteness); values verified against
CPU references per op.
257 lines
10 KiB
Plaintext
257 lines
10 KiB
Plaintext
/* r3d_moe_scatter.hip -- moe_scatter: the routed slots' stable counting sort.
|
|
*
|
|
* One workgroup does the whole sort (the "small" form, T <= 1024, which covers every decode and
|
|
* verify step): histogram in LDS, offsets an exclusive prefix over n_expert <= 512 counts, and
|
|
* each slot placed by its rank inside its expert's run. Stable and byte-identical to the
|
|
* reference: a slot's place is its position among the same expert's slots in ascending i.
|
|
*
|
|
* expert_ids [T] -> sorted_tok [T], expert_offset [n_expert+1], expert_count [n_expert]
|
|
*
|
|
* `expert_base` is this rank's first expert, subtracted from every routed id so the offsets,
|
|
* counts and (downstream) weight table are indexed locally; an id outside the slice is dropped
|
|
* (sorted to the tail as -1). `protect` is a comma list of local expert indices placed last.
|
|
*
|
|
* gfx1102 note: the prefix scan's per-wave inclusive sum goes through LDS, not the DPP row-shift
|
|
* butterfly (a DPP exchange inside the scan's tile loop miscompiles here). Each wave writes its
|
|
* lane's count to LDS, barriers, and takes the serial prefix of its 32 lanes.
|
|
*
|
|
* The general (three-pass) form for T > 1024 is not implemented here; the shim declines it.
|
|
*/
|
|
#include <hip/hip_runtime.h>
|
|
|
|
#include <cstdint>
|
|
#include <cstdlib>
|
|
|
|
#include "r3d.h"
|
|
#include "r3d_args.h"
|
|
#include "r3d_launch.h"
|
|
|
|
#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0)
|
|
|
|
namespace {
|
|
|
|
constexpr uint32_t kSortWave = 32;
|
|
constexpr uint32_t kMaxExpert = 512;
|
|
constexpr uint32_t kMaxProtect = 8;
|
|
constexpr uint32_t kScatterSmall = 1024;
|
|
constexpr uint32_t kScatWaves = 8; // 256 threads
|
|
|
|
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;
|
|
}
|
|
|
|
template <uint32_t NW>
|
|
struct ScatterLds {
|
|
static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave);
|
|
int32_t e[kScatterSmall];
|
|
int32_t tk[kScatterSmall];
|
|
int32_t run[kScatterSmall];
|
|
int32_t cnt[kMaxExpert + 1];
|
|
int32_t off[kMaxExpert + 1];
|
|
int32_t wt[kTiles][NW];
|
|
int32_t scan[NW * kSortWave]; // the LDS inclusive-scan scratch (gfx1102: no DPP here)
|
|
};
|
|
|
|
/* 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. */
|
|
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) {
|
|
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);
|
|
}
|
|
R3D_BARRIER();
|
|
|
|
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;
|
|
// Inclusive wave scan through LDS (a DPP row-shift miscompiles on gfx1102).
|
|
sl.scan[wave * kSortWave + lane] = v;
|
|
R3D_BARRIER();
|
|
int32_t x = 0;
|
|
for (int i = 0; i <= (int)lane; ++i) x += sl.scan[wave * kSortWave + i];
|
|
if (lane == kSortWave - 1) sl.wt[t][wave] = x;
|
|
R3D_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;
|
|
R3D_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;
|
|
}
|
|
R3D_BARRIER();
|
|
for (uint32_t i = tid; i < T; i += blockDim.x) {
|
|
const int32_t e = sl.e[i];
|
|
if (e < 0) {
|
|
if (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 (INV) inv[i] = o + rank;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
R3D_BARRIER();
|
|
scatter_small_place<kScatWaves, INV>(sorted, off, cnt, T, n_expert, sl, inv);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
extern "C" {
|
|
|
|
int r3d_rad_moe_scatter(const RadArgs* a, RadStream s)
|
|
{
|
|
if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL);
|
|
const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2),
|
|
*cnt = r3d_opt(a, 3);
|
|
if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt))
|
|
return R3D_NO(RAD_E_INVAL);
|
|
if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
|
|
cnt->dtype != RAD_I32)
|
|
return R3D_NO(RAD_E_DTYPE);
|
|
if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt))
|
|
return R3D_NO(RAD_E_STRIDE);
|
|
|
|
const long long n_expert = r3d_geti_or(a, "n_expert", 0);
|
|
if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE);
|
|
const long long T = r3d_numel(ids);
|
|
if (T <= 0) return R3D_NO(RAD_E_SHAPE);
|
|
if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only
|
|
if (r3d_numel(sorted) < T) return R3D_NO(RAD_E_SHAPE);
|
|
if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE);
|
|
|
|
const long long base = r3d_geti_or(a, "expert_base", 0);
|
|
if (base < 0) return R3D_NO(RAD_E_SHAPE);
|
|
|
|
// protect: a comma list of local expert indices, strictly ascending, at most kMaxProtect.
|
|
Protect prot{};
|
|
if (const char* str = r3d_gets(a, "protect")) {
|
|
const char* p = str;
|
|
long long prev = -1;
|
|
while (*p) {
|
|
char* end = nullptr;
|
|
const long long v = std::strtoll(p, &end, 10);
|
|
if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect)
|
|
return R3D_NO(RAD_E_SHAPE);
|
|
prot.e[prot.n++] = (uint16_t)v;
|
|
prev = v;
|
|
p = end;
|
|
if (*p == ',') ++p;
|
|
else if (*p) return R3D_NO(RAD_E_SHAPE);
|
|
}
|
|
}
|
|
|
|
const int32_t* idp = (const int32_t*)r3d_p(ids);
|
|
int32_t* sp = (int32_t*)r3d_wp(sorted);
|
|
int32_t* op = (int32_t*)r3d_wp(off);
|
|
int32_t* cp = (int32_t*)r3d_wp(cnt);
|
|
|
|
R3D_KLAUNCH(scatter_small_kernel<false>, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s,
|
|
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot,
|
|
(int32_t*)nullptr);
|
|
return (int)hipGetLastError();
|
|
}
|
|
|
|
/* moe_scatter_inv: the same sort, plus the inverse permutation (each slot's row in sorted_tok). */
|
|
int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s)
|
|
{
|
|
if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL);
|
|
const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2),
|
|
*cnt = r3d_opt(a, 3), *inv = r3d_opt(a, 4);
|
|
if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt) || !r3d_wp(inv))
|
|
return R3D_NO(RAD_E_INVAL);
|
|
if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 ||
|
|
cnt->dtype != RAD_I32 || inv->dtype != RAD_I32)
|
|
return R3D_NO(RAD_E_DTYPE);
|
|
if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt) ||
|
|
!r3d_contig(inv))
|
|
return R3D_NO(RAD_E_STRIDE);
|
|
|
|
const long long n_expert = r3d_geti_or(a, "n_expert", 0);
|
|
if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE);
|
|
const long long T = r3d_numel(ids);
|
|
if (T <= 0) return R3D_NO(RAD_E_SHAPE);
|
|
if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only
|
|
if (r3d_numel(sorted) < T || r3d_numel(inv) < T) return R3D_NO(RAD_E_SHAPE);
|
|
if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE);
|
|
|
|
const long long base = r3d_geti_or(a, "expert_base", 0);
|
|
if (base < 0) return R3D_NO(RAD_E_SHAPE);
|
|
|
|
Protect prot{};
|
|
if (const char* str = r3d_gets(a, "protect")) {
|
|
const char* p = str;
|
|
long long prev = -1;
|
|
while (*p) {
|
|
char* end = nullptr;
|
|
const long long v = std::strtoll(p, &end, 10);
|
|
if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect)
|
|
return R3D_NO(RAD_E_SHAPE);
|
|
prot.e[prot.n++] = (uint16_t)v;
|
|
prev = v;
|
|
p = end;
|
|
if (*p == ',') ++p;
|
|
else if (*p) return R3D_NO(RAD_E_SHAPE);
|
|
}
|
|
}
|
|
|
|
const int32_t* idp = (const int32_t*)r3d_p(ids);
|
|
int32_t* sp = (int32_t*)r3d_wp(sorted);
|
|
int32_t* op = (int32_t*)r3d_wp(off);
|
|
int32_t* cp = (int32_t*)r3d_wp(cnt);
|
|
int32_t* ip = (int32_t*)r3d_wp(inv);
|
|
|
|
R3D_KLAUNCH(scatter_small_kernel<true>, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s,
|
|
idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, ip);
|
|
return (int)hipGetLastError();
|
|
}
|
|
|
|
} // extern "C"
|