libr4d: rmsnorm_quant_i8 -- rmsnorm and the w4a8 activation quantiser in one pass

A w4a8 linear is fed by rmsnorm then quant_act_i8, two single-row
dispatches at a decode batch; in a sandwich-norm model (Gemma 2/3/4) the
residual junction in front adds a post-norm, the add and a layer scalar,
five dispatches at every junction. rmsnorm_quant_i8 is that chain in one
pass over the row, with the junction optional (w_post, scalar and the
residual operand).

Byte-identical to the chain it replaces: the same row partition
(r4d_act_threads) and a bf16 rounding wherever the chain stores. The
selftest compares it against the chain at three forms x M 1/8/40.
This commit is contained in:
keptn42 committed 2026-10-11 02:23:39 +00:00
1 parent 8bde9f9c16
commit dd6a7071a8
6 files changed
+387

No files matched your search

+8
View File
@@ -387,6 +387,14 @@ spelling of `act`, not the vocabulary's.
| `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? | | `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? |
| `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
`rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass — fragment-order int8
codes and one f32 scale per row, the grid `gemm_nt_q` reads at `dtype=w4a8`. With `residual` the
norm is of `residual + x`, stored back; `w_post` normalises `x` before that add and `scalar` (`[1]`)
multiplies the sum after it, which together are a sandwich-norm model's residual junction
(`rmsnorm` → `add` → `scale` → `rmsnorm` → `quant_act_i8`). Byte-identical to that chain: every
intermediate the chain stores is rounded to bf16, and both sums of squares take `rmsnorm`'s partition.
`gemm_nt_q_gated` is the row above pulled into the projection that feeds it: `gemm_nt_q` over a `gemm_nt_q_gated` is the row above pulled into the projection that feeds it: `gemm_nt_q` over a
`[N, K]` gate_up plane — `N` is the WEIGHT's rows, twice the fused width, gate half first — with `[N, K]` gate_up plane — `N` is the WEIGHT's rows, twice the fused width, gate half first — with
+1
View File
@@ -141,6 +141,7 @@ set(R4D_UNITS
"r4d_model_bf16|" "r4d_model_bf16|"
"r4d_sample_stages_f32|" "r4d_sample_stages_f32|"
"r4d_quant_act_i8|" "r4d_quant_act_i8|"
"r4d_rmsnorm_quant_i8|"
"r4d_had_quant_act_i8|" "r4d_had_quant_act_i8|"
"r4d_rmsnorm_had_quant_i8|" "r4d_rmsnorm_had_quant_i8|"
"r4d_ar_ln_had_quant_i8|" "r4d_ar_ln_had_quant_i8|"
+2
View File
@@ -301,6 +301,8 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*);
/* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */
int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream);
+213
View File
@@ -0,0 +1,213 @@
// r4d_rmsnorm_quant_i8.hip - r4d_rmsnorm_quant_i8: the RMS norm and the per-row int8 quantiser
// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row -- optionally with the residual junction
// in front of it: a post-norm on the branch output, the residual add and a scalar on the sum.
//
// WHY. A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32
// scale per row (r4d_quant_act_i8), and the producer of that activation is a norm. Unfused, a
// model whose linears take that grid issues the norm and the quantiser as two dispatches, and a
// sandwich-norm model (Gemma 2/3/4) issues four or five at every residual junction:
//
// rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant_act_i8
//
// each one a single workgroup over one row at a decode batch, so the step pays the dispatch, not
// the bytes. This is that chain as one dispatch.
//
// BYTE-IDENTICAL TO THE CHAIN IT REPLACES, not merely close, because the engine's greedy output is
// compared byte for byte across builds. What makes that hold:
//
// * every intermediate the chain stores in bf16 is rounded to bf16 here too, and the next stage
// reads the rounded value: the post-norm output, the residual sum, the scaled residual and the
// norm output the quantiser takes its absmax and codes over;
// * both sums of squares are taken by the same partition the standalone norm uses -- the width
// r4d_act_threads(M, n) picks, thread t folding columns t, t+THR, ... in ascending order, then
// r4d_wave_sum and the waves in order through LDS (r4d_model_bf16.hip's rmsnorm_kernel and
// block_sum, which this copies rather than shares only because that one lives in another unit);
// * the arithmetic of every element is written the way the standalone kernels write it --
// `x * s * (g + wadd)`, `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f` -- and the library is
// built with -ffp-contract=off, so no stage picks up an fma the chain does not have.
//
// THE RESIDUAL IS READ AND WRITTEN, and nothing else reads it before this kernel is done: each
// thread rewrites only the columns it read, so the second pass reads its own writes back.
//
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include <cstdint>
namespace {
constexpr uint32_t kWave = 32;
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
// The standalone norm's reduction, verbatim (r4d_model_bf16.hip): the wave butterfly, then the
// waves summed IN ORDER by every thread out of LDS. `lds` must not be reused by a second
// reduction without a barrier between them -- the kernel below gives each its own array.
template <uint32_t NW>
__device__ __forceinline__ float block_sum(float v, float* lds) {
v = r4d_wave_sum(v);
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
if (lane == 0) lds[wave] = v;
__syncthreads();
float s = 0.0f;
#pragma unroll
for (uint32_t w = 0; w < NW; ++w) s += lds[w];
return s;
}
__device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) {
return f32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
}
// RES: a residual is present; the norm is taken of `res + d` (stored back into `res`), where d is
// the branch `x` itself or, with POST, rmsnorm(x; w_post). Without RES the norm is of `x`.
// SCL: the sum is multiplied by the [1] scalar before it is stored and normalised.
// `ybuf` holds the row's norm output for the fragment-order store, which reads across threads.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo,
uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) {
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr;
signed char* __restrict__ qr = q + (size_t)row * n;
// ---- the post-norm's sum of squares, over the branch output
float s1 = 0.0f;
if (POST) {
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
ss = block_sum<THR / kWave>(ss, l1);
s1 = rsqrtf(ss / (float)n + eps);
}
// ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it
float sv = 1.0f;
if (SCL) sv = sc_f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]);
float ss2 = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
uint16_t v = xr[i];
if (RES) {
if (POST) v = f32_to_bf16(bf2f(v) * s1 * (gain(wp, i, WF32) + wadd));
v = f32_to_bf16(bf2f(rr[i]) + bf2f(v));
if (SCL) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
}
const float f = bf2f(v);
ss2 += f * f;
}
ss2 = block_sum<THR / kWave>(ss2, l2);
const float s2 = rsqrtf(ss2 / (float)n + eps);
// ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax
const uint16_t* __restrict__ nr = RES ? rr : xr;
float m = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t y = f32_to_bf16(bf2f(nr[i]) * s2 * (gain(w, i, WF32) + wadd));
ybuf[i] = y;
if (yo) yo[(size_t)row * y_ld + i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
m = r4d_wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
m = lm[0];
#pragma unroll
for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]);
const float scale = fmaxf(m, 1e-8f) / 127.f;
const float inv = 1.f / scale;
if (threadIdx.x == 0) S[row] = scale;
// ---- the codes, in r4d_quant_act_i8's fragment order: byte j of a k step comes from
// lane-half j>>3 and element j&7, i.e. source 8*((j&7)>>2) + 4*(j>>3) + (j&3) inside the step.
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint32_t s = i >> 4, j = i & 15;
const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3);
const int t = __float2int_rn(bf2f(ybuf[src]) * inv);
qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t));
}
}
} // namespace
// ============================================================== the plugin ABI entry point
//
// Operands, in the schema's order (r4d_rows.cpp, oRmsNormQuantI8):
// 0 x [M][n] bf16 the norm's input, or the branch output with a residual
// 1 residual [M][n] bf16, optional READ AND WRITTEN
// 2 w [n] bf16 or f32 the norm's gain
// 3 q [M][n] int8 fragment order, unpitched
// 4 scale [M][1] f32 one per row
// 5 out_bf16 [M][n] bf16, optional the norm output the unfused norm would have stored
// 6 w_post [n] optional a post-norm on x before the add; needs the residual
// 7 scalar [1] optional multiplies the sum; needs the residual
enum { RQ_X = 0, RQ_RES, RQ_W, RQ_Q, RQ_S, RQ_Y, RQ_WP, RQ_SC };
static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) {
int emit_rc = RAD_OK;
const RadTensor* x = r4d_opt(a, RQ_X);
const RadTensor* rs = r4d_opt(a, RQ_RES);
const RadTensor* w = r4d_opt(a, RQ_W);
const RadTensor* q = r4d_opt(a, RQ_Q);
const RadTensor* s = r4d_opt(a, RQ_S);
const RadTensor* y = r4d_opt(a, RQ_Y);
const RadTensor* wp = r4d_opt(a, RQ_WP);
const RadTensor* sc = r4d_opt(a, RQ_SC);
if (!x || !w || !q || !s) return R4D_NO(RAD_E_INVAL);
if ((wp || sc) && !rs) return R4D_NO(RAD_E_INVAL); // a junction without a stream to add into
if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
long long M = 0, n = 0;
if (r4d_rows_of(x, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
if (n % 16) return R4D_NO(RAD_E_SHAPE); // a k step is sixteen bytes of one row
if (r4d_numel(w) != n) return R4D_NO(RAD_E_SHAPE);
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (wp && (r4d_numel(wp) != n || wp->dtype != w->dtype)) return R4D_NO(RAD_E_SHAPE);
if (sc && (r4d_numel(sc) != 1 || (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16)))
return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(q) != M * n || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE);
if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE);
if (rs && r4d_numel(rs) != M * n) return R4D_NO(RAD_E_SHAPE);
const long long xp = r4d_row_pitch(x), rp = rs ? r4d_row_pitch(rs) : n, yp = y ? r4d_row_pitch(y) : n;
if (xp < 0 || rp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
// The row's norm output is staged in LDS for the cross-thread fragment-order store.
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
// THE SAME WIDTH AS rmsnorm_bf16 AND quant_act_i8 PICK, from the same function: it decides
// which columns a thread folds into each sum of squares, which is the byte-identity.
const int thr = r4d_act_threads((int)M, (int)n);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u;
#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(sk, \
(rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \
(signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \
(uint32_t)xp, (uint32_t)rp, (uint32_t)yp)
#define R4D_RQI8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \
else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \
else return R4D_NO(RAD_E_INVAL); } while (0)
#define R4D_RQI8_W(WF) \
do { if (!rs) R4D_RQI8(WF, false, false, false); \
else if (!wp && !sc) R4D_RQI8(WF, true, false, false); \
else if (wp && !sc) R4D_RQI8(WF, true, true, false); \
else if (wp && sc) R4D_RQI8(WF, true, true, true); \
else R4D_RQI8(WF, true, false, true); } while (0)
if (w->dtype == RAD_F32) R4D_RQI8_W(true);
else R4D_RQI8_W(false);
#undef R4D_RQI8_W
#undef R4D_RQI8
#undef R4D_RQI8_T
return emit_rc;
}
R4D_ENTRY(r4d_rad_rmsnorm_quant_i8, rad_rmsnorm_quant_i8_body)
+46
View File
@@ -1314,6 +1314,32 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = {
{ "out_bf16", RAD_OPD_OUT, 1 }, { "out_bf16", RAD_OPD_OUT, 1 },
}; };
/* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's own activation producer on its pass:
* int8 codes in the GEMM's fragment order and ONE f32 scale per row -- quant_act_i8's grid, not
* quant_act_i8g's per-group one and not the rotated rmsnorm_had_quant_i8's. Its first six operands
* are rmsnorm_quant_fp8's, so the residual is the fused_add_rms_norm form; two optional weights
* after them make it a sandwich-norm model's whole residual junction: `w_post` normalises the
* branch output BEFORE the add and `scalar` multiplies the sum after it (Gemma's per-layer
* scalar). Every stage rounds to bf16 where the chain it replaces stores bf16, so the op is
* byte-identical to that chain. */
static const RadParamSpec pRmsNormQuantI8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("eps"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
};
static const RadOperandSpec oRmsNormQuantI8[] = {
{ "x", RAD_OPD_IN, 0 },
{ "residual", RAD_OPD_INOUT, 1 }, /* present = the norm is of residual + (post-normed) x */
{ "w", RAD_OPD_WEIGHT, 0 },
{ "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 },
{ "out_bf16", RAD_OPD_OUT, 1 },
{ "w_post", RAD_OPD_WEIGHT, 1 }, /* rmsnorm(x; w_post) before the add; needs the residual */
{ "scalar", RAD_OPD_WEIGHT, 1 }, /* [1], multiplies the sum; needs the residual */
};
static const RadParamSpec pGatedQuantFp8[] = { static const RadParamSpec pGatedQuantFp8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED }, { "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED },
@@ -2304,6 +2330,9 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm_quant_fp8", pRmsNormQuantFp8, oRmsNormQuantFp8, SCHEMA("rmsnorm_quant_fp8", pRmsNormQuantFp8, oRmsNormQuantFp8,
"RMS norm and the fp8 activation quantiser in one pass over the row. The bf16 norm " "RMS norm and the fp8 activation quantiser in one pass over the row. The bf16 norm "
"output the unfused pair wrote is still written, and the codes are taken over it."), "output the unfused pair wrote is still written, and the codes are taken over it."),
SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8,
"RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with "
"a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."),
SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."), "silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."),
SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
@@ -3158,6 +3187,11 @@ static const RadConstraint cSampleChain[] = {
static const RadConstraint cQuantActI8[] = { static const RadConstraint cQuantActI8[] = {
C_DIV("n", 16), C_IN("dtype", "bf16"), C_DIV("n", 16), C_IN("dtype", "bf16"),
}; };
/* `n DIV 16`: a k step of the fragment order is sixteen bytes of one row. The row is staged in LDS
* as bf16 for the cross-thread fragment store, which the shim bounds. */
static const RadConstraint cRmsNormQuantI8[] = {
C_DIV("n", 16), C_IN("dtype", "bf16"),
};
static const RadConstraint cHadQuantActI8[] = { static const RadConstraint cHadQuantActI8[] = {
C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"),
}; };
@@ -5542,6 +5576,18 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_quant_act_i8, nullptr, nullptr, nullptr, nullptr, nullptr, r4d_rad_quant_act_i8, nullptr, nullptr, nullptr,
r4d_shape_quant_act_i8 , nullptr, nullptr, r4d_rad_quant_act_i8_describe }, r4d_shape_quant_act_i8 , nullptr, nullptr, r4d_rad_quant_act_i8_describe },
{ "rmsnorm_quant_i8", "rmsnorm_quant_i8", "quant",
"RMS norm and quant_act_i8's quantiser in one pass over the row; optionally the residual "
"junction in front of it -- a post-norm on x, the add into the residual and a scalar on the sum",
"n a multiple of 16 and n*2 bytes within LDS; one workgroup per row at rmsnorm_bf16's width; "
"the gains f32 or bf16, read off the operand; w_post and scalar need the residual",
"bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 "
"out; every stored intermediate rounded to bf16 as the unfused chain stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRmsNormQuantI8), NOTUNE,
nullptr, nullptr, r4d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8_describe },
{ "had_quant_act_i8", "had_quant_act_i8", "quant", { "had_quant_act_i8", "had_quant_act_i8", "quant",
"block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes "
"int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels " "int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels "
+117
View File
@@ -4922,6 +4922,119 @@ static void fused_quant_fp8_numeric(const Plugin& pl) {
} }
} }
/* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------
*
* Byte-identical, for the reason the fp8 fusions above give, in all three forms a sandwich-norm
* model issues: the plain norm + quantiser (a first block's entry), the junction without a scalar
* (attention -> feed-forward) and with one (feed-forward -> the next layer). The unfused chain is
* rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8, run here
* kernel by kernel. bf16 gains, which is what Gemma's checkpoint stores, and two batch heights so
* both of r4d_act_threads' widths a decode step meets are covered (1024 at M <= 32, 512 above). */
static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16");
const RadKernelInfo* ad = find(pl, "add_bf16");
const RadKernelInfo* scl = find(pl, "scale_bf16");
const RadKernelInfo* qz = find(pl, "quant_act_i8");
const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8");
if (!nrm || !ad || !scl || !qz || !rq) { ok("rmsnorm_quant_i8 vs its chain", false, "rows absent"); return; }
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)40 }) {
const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps, not a power of two */
std::vector<uint16_t> hx((size_t)M * K), hr((size_t)M * K), hw((size_t)K), hp((size_t)K);
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < K; ++c) {
const float m = std::ldexp(1.0f, (int)((c / 384) % 6) - 3);
const float v = m * (0.037f * (float)((r * 29 + c * 13) % 71) - 1.3f);
hx[(size_t)r * K + c] = h_to_bf16(c == (r * 37) % K ? v * 19.0f : v);
hr[(size_t)r * K + c] = h_to_bf16(0.019f * (float)((r * 13 + c * 29) % 67) - 0.6f);
}
for (int64_t c = 0; c < K; ++c) {
hw[(size_t)c] = h_to_bf16(0.004f * (float)((c * 19) % 51) - 0.1f);
hp[(size_t)c] = h_to_bf16(0.9f + 0.003f * (float)((c * 7) % 41));
}
const uint16_t hs = h_to_bf16(0.373f);
void* d_x = dalloc((size_t)M * K * 2);
void* d_w = dalloc((size_t)K * 2);
void* d_p = dalloc((size_t)K * 2);
void* d_sc = dalloc(4);
void* d_t = dalloc((size_t)M * K * 2);
void* d_r[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) };
void* d_y[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) };
void* d_q[2] = { dalloc((size_t)M * K), dalloc((size_t)M * K) };
void* d_s[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) };
if (!d_x || !d_w || !d_p || !d_sc || !d_t || !d_r[1] || !d_y[1] || !d_q[1] || !d_s[1]) {
ok("rmsnorm_quant_i8 alloc", false, "hipMalloc failed");
return;
}
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_w, hw.data(), hw.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_p, hp.data(), hp.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_sc, &hs, 2, hipMemcpyHostToDevice);
const double eps = 1e-6, wadd = 0.0;
const std::vector<RadParam> pn = { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) };
const std::vector<RadParam> pe = { PI("M", M), PI("n", K), PS("dtype", "bf16") };
const std::vector<RadParam> pq = { PI("M", M), PI("n", K), PI("group", K), PS("dtype", "bf16") };
auto compare = [&](const std::string& what, bool res) {
std::vector<uint16_t> y0((size_t)M * K), y1((size_t)M * K), r0((size_t)M * K), r1((size_t)M * K);
std::vector<uint8_t> q0((size_t)M * K), q1((size_t)M * K);
std::vector<float> s0((size_t)M), s1((size_t)M);
st_memcpy(y0.data(), d_y[0], y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), d_y[1], y1.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(q0.data(), d_q[0], q0.size(), hipMemcpyDeviceToHost);
st_memcpy(q1.data(), d_q[1], q1.size(), hipMemcpyDeviceToHost);
st_memcpy(s0.data(), d_s[0], s0.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(s1.data(), d_s[1], s1.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(r0.data(), d_r[0], r0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(r1.data(), d_r[1], r1.size() * 2, hipMemcpyDeviceToHost);
int ny = 0, nq = 0, ns = 0, nr = 0, nz = 0;
for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i];
for (size_t i = 0; i < q0.size(); ++i) nq += q0[i] != q1[i];
for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0;
if (res) for (size_t i = 0; i < r0.size(); ++i) nr += r0[i] != r1[i];
for (size_t i = 0; i < q1.size(); ++i) nz += q1[i] != 0;
ok((what + " M=" + std::to_string(M)).c_str(), ny == 0 && nq == 0 && ns == 0 && nr == 0 && nz > (int)q1.size() / 2,
"bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " +
std::to_string(ns) + ", residual " + std::to_string(nr) + ", nonzero codes " + std::to_string(nz));
};
auto norm_quant = [&](void* src) { /* rmsnorm(src; w) -> quant_act_i8, into slot 0 */
int rc = launch_row(nrm, { T(src, RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }), T(d_y[0], RAD_BF16, { M, K }) }, pn);
if (rc == RAD_OK)
rc = launch_row(qz, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }),
T(d_s[0], RAD_F32, { M }), T(nullptr, RAD_F32, {}) }, pq);
return rc;
};
/* --- the plain form --- */
int rc = norm_quant(d_x);
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), T(d_w, RAD_BF16, { K }),
T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }),
T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, pn);
if (rc != RAD_OK) ok("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8", false, "rc=" + std::to_string(rc));
else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8", false);
/* --- the junction, without and with the scalar --- */
for (const bool with_sc : { false, true }) {
st_memcpy(d_r[0], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_r[1], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
rc = launch_row(nrm, { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_BF16, { K }), T(d_t, RAD_BF16, { M, K }) }, pn);
if (rc == RAD_OK)
rc = launch_row(ad, { T(d_r[0], RAD_BF16, { M, K }), T(d_t, RAD_BF16, { M, K }), T(d_r[0], RAD_BF16, { M, K }) }, pe);
if (rc == RAD_OK && with_sc)
rc = launch_row(scl, { T(d_r[0], RAD_BF16, { M, K }), T(d_sc, RAD_BF16, { 1 }), T(d_r[0], RAD_BF16, { M, K }) }, pe);
if (rc == RAD_OK) rc = norm_quant(d_r[0]);
if (rc == RAD_OK)
rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(d_r[1], RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }),
T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }),
T(d_p, RAD_BF16, { K }),
with_sc ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, pn);
const std::string what = with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction";
if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc));
else compare(what + " is byte-identical to its chain", true);
}
}
}
/* THE fp8 lm_head, end to end through its OWN hooks. /* THE fp8 lm_head, end to end through its OWN hooks.
* *
* The arrangement is the odd one in this library -- E4M3 codes with the row's own bf16 scales in * The arrangement is the odd one in this library -- E4M3 codes with the row's own bf16 scales in
@@ -13360,6 +13473,10 @@ static void device_phase(const Plugin& pl) {
if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n"); if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n");
fused_quant_fp8_numeric(pl); fused_quant_fp8_numeric(pl);
} }
if (sel("rmsnorm_quant_i8")) {
if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n");
rmsnorm_quant_i8_numeric(pl);
}
/* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape in /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape in
* the tree asks these kernels for. * the tree asks these kernels for.