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

+88
View File
@@ -15,8 +15,12 @@
#define __device__
#define __host__
#define __shared__ static
#define __constant__
#define __forceinline__ inline
#define __launch_bounds__(n)
/* R4D_WAVES (r4d_common.h) names a kernel attribute; on the host it becomes an empty attribute */
#define amdgpu_waves_per_eu(lo, hi)
#define __align__(n) __attribute__((aligned(n)))
struct dim3 {
unsigned x, y, z;
@@ -29,6 +33,25 @@ inline hipError_t hipGetLastError() { return 0; }
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
struct hipDeviceProp_t { size_t sharedMemPerBlock; };
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
/* no graphs: a stream never captures */
enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 };
inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) {
*s = hipStreamCaptureStatusNone;
return hipSuccess;
}
/* every launch runs to completion before it returns */
inline hipError_t hipDeviceSynchronize() { return hipSuccess; }
/* __device__ variables are host globals, so a symbol copy is a memcpy */
enum hipMemcpyKind { hipMemcpyHostToDevice = 1, hipMemcpyDeviceToHost = 2 };
#define HIP_SYMBOL(s) (&(s))
inline hipError_t hipMemcpyFromSymbol(void* dst, const void* sym, size_t n, size_t off, hipMemcpyKind) {
std::memcpy(dst, (const char*)sym + off, n);
return hipSuccess;
}
inline hipError_t hipMemcpyToSymbol(const void* sym, const void* src, size_t n, size_t off, hipMemcpyKind) {
std::memcpy((char*)sym + off, src, n);
return hipSuccess;
}
inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
*p = hipDeviceProp_t{};
p->sharedMemPerBlock = 64 * 1024;
@@ -38,9 +61,15 @@ inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
struct EmuIdx { unsigned x, y, z; };
EmuIdx& emu_thread_idx();
EmuIdx& emu_block_idx();
EmuIdx& emu_block_dim();
EmuIdx& emu_grid_dim();
#define threadIdx (emu_thread_idx())
#define blockIdx (emu_block_idx())
#define blockDim (emu_block_dim())
#define gridDim (emu_grid_dim())
void __syncthreads();
/* the block barrier, returning whether any thread passed a nonzero predicate */
int __syncthreads_or(int p);
int emu_bpermute(int addr, int v);
int emu_readlane(int v, int lane);
#define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v))
@@ -73,6 +102,14 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
return r;
}
#define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s))
/* HIP's __byte_perm: result byte i is the byte of {y, x} (x low) that the low three bits of
* nibble i of s name; only the low four nibbles are read */
inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) {
const unsigned long long d = ((unsigned long long)y << 32) | x;
unsigned r = 0;
for (int i = 0; i < 4; ++i) r |= (unsigned)((d >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i);
return r;
}
/* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a
* fence or a scheduling barrier orders nothing more. */
#define __builtin_amdgcn_s_barrier() __syncthreads()
@@ -81,15 +118,38 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
/* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */
template <class T>
inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; }
template <class T>
inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; }
template <class T>
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
template <class T>
inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; }
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
typedef short emu_v8s __attribute__((ext_vector_type(8)));
typedef float emu_v8f __attribute__((ext_vector_type(8)));
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
/* the __bf16 fragments of r4d_gdn_wmma.h, the same bits */
typedef __bf16 emu_v8bf __attribute__((ext_vector_type(8)));
inline emu_v8f emu_wmma_bf16(emu_v8bf a, emu_v8bf b, emu_v8f c) {
return emu_wmma_bf16(__builtin_bit_cast(emu_v8s, a), __builtin_bit_cast(emu_v8s, b), c);
}
#define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c))
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
/* v_wmma_f32_16x16x16_fp8_fp8 (gfx12, wave32): the bf16 form's layout with eight E4M3 bytes a
* lane, element e in byte e. Each output is c plus its 16 products in k order: not the hardware's
* internal order, but a function of the output's own row, column and c alone, as the hardware's
* is, which is what a comparison of two kernels over the same fragments relies on. */
typedef int emu_v2i __attribute__((ext_vector_type(2)));
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c);
#define __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c) emu_wmma_fp8((a), (b), (c))
/* v_wmma_i32_16x16x16_iu8: not emulated; reported when reached */
typedef int emu_v8i __attribute__((ext_vector_type(8)));
emu_v8i emu_wmma_iu8(bool sa, emu_v2i a, bool sb, emu_v2i b, emu_v8i c, bool clamp);
#define __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(sa, a, sb, b, c, cl) \
emu_wmma_iu8((sa), (a), (sb), (b), (c), (cl))
/* global_load_tr_b128: not emulated; reported when reached */
emu_v8s emu_load_tr_b128(const void* p);
#define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p))
@@ -120,9 +180,34 @@ inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; }
inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; }
inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; }
inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */
/* The device's fast exponential is not bit-exact to expf; here it is expf, so a test compares two
* kernels that both take it, never a kernel against a host value of it. */
inline float __expf(float x) { return std::exp(x); }
inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; }
inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; }
inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; }
/* The float shuffles over ds_bpermute, for one-dimensional blocks, within groups of `width`
* lanes: __shfl_xor reads lane L ^ mask, __shfl lane `src`, __shfl_down lane L + delta (its own
* value past the group's end) */
inline float emu_shfl_from(float v, int src) {
return __int_as_float(emu_bpermute(src << 2, __float_as_int(v)));
}
inline float __shfl_xor(float v, int mask, int width = 32) {
const int lane = (int)threadIdx.x & 31;
return emu_shfl_from(v, (lane & ~(width - 1)) | ((lane ^ mask) & (width - 1)));
}
inline float __shfl(float v, int src, int width = 32) {
const int lane = (int)threadIdx.x & 31;
return emu_shfl_from(v, (lane & ~(width - 1)) | (src & (width - 1)));
}
inline float __shfl_down(float v, unsigned delta, int width = 32) {
const int lane = (int)threadIdx.x & 31, in_group = lane & (width - 1);
return emu_shfl_from(v, in_group + (int)delta < width ? lane + (int)delta : lane);
}
/* HIP declares the classification functions in the global namespace */
using std::isfinite;
inline int min(int a, int b) { return a < b ? a : b; }
inline int max(int a, int b) { return a > b ? a : b; }
/* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0);
@@ -154,6 +239,9 @@ int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, cons
}
#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \
emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)
/* hipLaunchKernelGGL, for units that launch with it directly: the same call as R4D_EMIT. */
#define hipLaunchKernelGGL(kernel, grid, block, lds, stream, ...) \
((void)(stream), (void)emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__))
/* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending
* at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one
* past the end faults */