This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libr3d/r3d_dequant_w4_bf16.hip
Asim Siddiqui 87c604370d libr3d: add 8 kernels — MoE GEMM (w4a8, w4a4, mod4), dequant_w4, row_topk_merge, ngram_ids, gemm_nt_q_bias, gemm_nt_q_short
moe_gemm_q w4a8: the 2-class MoE GEMM with bf16 weight scale and bf16
output. E4M3 activation codes, bf16 weight scale (not f32), single
16x128-block i32 wave-matrix config. The w4a8 dtype row is folded into
the existing moe_gemm_q op as a dtype variant, not a separate op.

moe_gemm_w4a4: the 2-class MoE GEMM with int4 activation codes and
int4 weight codes. i32 wave-matrix core (no E4M3 decode table),
symmetric int4 x int4 multiply-accumulate. Single fixed 16x128-block
config.

moe_gemm_q_mod4: the 4-class MoE GEMM. Experts route to class e%4
(entry e/4 within the class). Same E4M3 wave-matrix core as
moe_gemm_q_e4m3, with 8 individual R3dTab parameters (4 weight + 4
scale tables) to stay within the gfx1102 kernel parameter limit.

dequant_w4: packed int4 weight to row-major bf16. Each 32-bit word
holds 8 int4 codes; the scale is f16 in the low 16 bits, the zero
point is -(1024+zero) as f16 in the high 16 bits. One warp per 32
output elements.

row_topk_merge: top-R of gathered per-rank candidate sets. Each rank
contributes a sorted candidate list; the merge selects the top-R
global candidates by score. int32 ids are bit patterns in an f32
plane (memcpy, not cast).

ngram_ids: hashed n-gram row ids for PLE (Per-Layer Embedding).
Computes the row index for each n-gram in the sequence using a
FNV-1a hash folded into the embedding table size.

gemm_nt_q_bias: narrow fp8 GEMM (M <= 16) with per-column bf16 bias
fused into the epilogue. The bias is added to the f32 accumulator
before the single bf16 narrowing at the store. Extends
r3d_gemm_nt_q_fp8_ex with a bias parameter.

gemm_nt_q_short: narrow fp8 GEMM (M <= 16) for short-prompt decode,
unsplit K. Forces sk=1 (no K-split) in r3d_gemm_nt_q_fp8_ex. The
short-prompt path avoids the K-split overhead when K is small.

The two narrow fp8 rows carry the tGemmM16 tune matrix (sk 0/1/2/4/8/16,
wv 1/2/4/8, nt, the two E4M3 decode impls, 16-row tiles) like the other
gemm_nt_q rows, measured per card by rad-tune.

The six new ops adopt the canonical op schemas. The engine enforces
schema identity across kernel libraries: the first library to declare
an op fixes its schema, and a disagreeing plugin is refused whole at
load. libavx loads first, so the specs match the canonical registries:
- moe_gemm_q_mod4: 15 params / 13 operands (the eight weight tables at
  the RAD_OPD_WTAB role); the launcher reads a_order (token/sorted),
  requires group = 128, checks the activation's row count against the
  output, and refuses unequal class shapes (N_1..K_3 differ from N/K)
  as moe_gemm_q does with N_odd/K_odd.
- ngram_ids: 4 params / 11 operands under the canonical names; state
  required; per, W and the ids pitch derive from the operand shapes.
- row_topk_merge: 4 params (+dtype) / 3 operands.
- gemm_nt_q_short: the family's four optional params (pb1, pb2,
  split_n, w_rb) and two optional operands (a_sum, b_ref).
- gemm_nt_q_bias: a_scale required, not optional.
- dequant_w4: the dtype param, twos required, the scale operand named
  ws; the launcher refuses zero rows with RAD_E_SHAPE like every
  other op.

A kernel audit found five launcher param reads the engine can never
populate (the spec's params plus the row's tune axes are the only
sources): pb1/pb2 in the gemm_nt_q_bias launcher, splits in the decode
attention path, and nt/kb/sk in the tiled rows that tune only impl.
Each always took its default; the reads are deleted, behavior-
identical.

All 8 verified bit-exact on gfx1102 (RX 7600, box card 2).
Selftest: 117 rows clean, 0 failed. rad-schemas over libavx, libr3d,
libr4d and libref: 244 shared ops, 0 disagree.
2026-11-05 09:49:06 +01:00

91 lines
4.3 KiB
Plaintext

// r3d_dequant_w4_bf16.hip -- dequant_w4: the packed 4-bit weight back to a plain row-major
// bf16 [N, K].
//
// Used at prefill. W4A8 gains nothing there (iu8 and fp8 matrix rates are within a few percent
// and the shape is compute-bound), and the skinny W4A8 GEMM re-reads the whole weight slice once
// per 64 output rows, so its rate is flat in M. Dequantising one layer into scratch and running
// the tuned bf16 GEMM costs one extra write and read of the bf16 weight, a few percent of the GEMM.
//
// Two encodings share these bytes and differ by bit 3, so the caller must say which. The
// symmetric grid stores a two's complement code, value (n^8)-8, so the int8 GEMM can read the
// high-nibble byte signed and get 16*q. The asymmetric grid stores an unsigned nibble minus a
// per-group zero, corrected in the GEMM by an activation row-sum. Mixing them up agrees for n<8
// and is off by 16 above.
//
// Nearly lossless: a 4-bit code times an f16 scale fits bf16's 8-bit mantissa to within a ULP.
//
// Fragment order: radiance_w4.pack lays a dword out as [t][kb][lh][r][s] with eight nibbles along
// i, where t = n/16, r = n%16, kb = k/64, s = (k%64)/16, and the k inside the step is
// 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. One thread per dword scatters its eight
// nibbles. The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high, so one
// routine serves the symmetric grid (zero == 8) and the asymmetric one.
#include <hip/hip_runtime.h>
#include <hip/hip_bf16.h>
#include <hip/hip_fp16.h>
#include <cstdint>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_launch.h"
#define R3D_DQ_KPB 64
#define R3D_DQ_THREADS 256
static const int r3d_dq_koff[8] = {0, 8, 1, 9, 2, 10, 3, 11};
__global__ __launch_bounds__(R3D_DQ_THREADS) void r3d_dequant_w4_bf16_kernel(
const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws,
__hip_bfloat16* __restrict__ Out, int N, int K, int group, int twos)
{
const long total = (long)N * K / 8; // one thread per packed dword
const int nkb = K / R3D_DQ_KPB, ng = K / group;
for (long idx = blockIdx.x * (long)blockDim.x + threadIdx.x; idx < total;
idx += (long)gridDim.x * blockDim.x) {
// [t][kb][lh][r][s]
const int s = (int)(idx & 3);
const int r = (int)((idx >> 2) & 15);
const int lh = (int)((idx >> 6) & 1);
const int kb = (int)((idx >> 7) % nkb);
const int t = (int)((idx >> 7) / nkb);
const int row_n = t * 16 + r;
const unsigned w = Wq[idx];
const int kbase = kb * R3D_DQ_KPB + s * 16 + 4 * lh;
const unsigned sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r];
const float sc = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
const float nz = __half2float(__ushort_as_half((unsigned short)(sz >> 16)));
const float zero = -nz - 1024.f; // exact for zero in 0..15
#pragma unroll
for (int i = 0; i < 8; i++) {
const int n = (int)((w >> (4 * i)) & 0xF);
const float q = twos ? (float)((n ^ 8) - 8) : (float)n;
const int k = kbase + r3d_dq_koff[i];
Out[(size_t)row_n * K + k] = __float2bfloat16((q - (twos ? 0.f : zero)) * sc);
}
}
}
extern "C" int r3d_rad_dequant_w4(const RadArgs* a, RadStream s)
{
const RadTensor* wq = r3d_opt(a, 0), *ws = r3d_opt(a, 1), *y = r3d_opt(a, 2);
if (!r3d_p(wq) || !r3d_p(ws) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL);
if (y->rank != 2 || y->stride[1] != 1) return R3D_NO(RAD_E_STRIDE);
const long long N = y->shape[0];
const long long K = y->shape[1];
const long long group = r3d_geti_or(a, "group", 128);
const long long twos = r3d_geti_or(a, "twos", 1);
if (N <= 0 || K <= 0 || N % 16 || K % 64) return R3D_NO(RAD_E_SHAPE);
if (group < 1 || K % group) return R3D_NO(RAD_E_SHAPE);
if (twos != 0 && twos != 1) return R3D_NO(RAD_E_INVAL);
const long long total = N * K / 8;
const int blocks = (int)((total + R3D_DQ_THREADS - 1) / R3D_DQ_THREADS);
dim3 grid(blocks < 65535 ? blocks : 65535), blk(R3D_DQ_THREADS);
R3D_KLAUNCH(r3d_dequant_w4_bf16_kernel, grid, blk, (hipStream_t)s,
(const unsigned*)r3d_p(wq), (const unsigned*)r3d_p(ws),
(__hip_bfloat16*)r3d_wp(y), (int)N, (int)K, (int)group, (int)twos);
return (int)hipGetLastError();
}