libr4d: rmsnorm_quant_i8g, gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g -- the junctions at quant_act_i8g's grid

The norm junction (post-norm, residual add, scalar, norm), the gelu product and the two-rank
all-reduce junction with quant_act_i8g's quantiser in place of quant_act_i8's: row-major int8
codes and an f32 scale per (row, 128 columns), what gemm_nt_q reads at i8a8, w4a8i8_asym and
w5a8i8. The kernels are rmsnorm_quant_i8's and gelu_mul_quant_i8's; only the epilogue over the
staged bf16 row differs (r4d_q8.h, q8_row_i8g: quant_act_i8g's mapping and rule), so each is
byte-identical to its chain ending in quant_act_i8g. out_bf16 may be x's own buffer. No
four-rank form: a four-rank caller finds no row and issues the all-reduce apart.

r4d_selftest: rmsnorm_quant_i8g, gelu_mul_quant_i8g and ar_rmsnorm_quant_i8g (two cards) against
their chains, the junction also with out_bf16 over x.
This commit is contained in:
keptn42 authored and StillDeadcode committed 2026-11-01 21:00:22 +01:00
1 parent 141212dd88
commit b55791b398
9 files changed
+387 -133

No files matched your search

+13
View File
@@ -707,7 +707,9 @@ the wrong copy.
| `rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `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_i8g` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gelu_mul_quant_i8g` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
`gelu_mul_quant_i8` is `gelu_mul` with `rmsnorm_quant_i8`'s quantiser on its pass, byte-identical
to the pair.
@@ -728,6 +730,14 @@ multiplies the sum after it, together a sandwich-norm model's residual junction
→ `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.
`rmsnorm_quant_i8g` and `gelu_mul_quant_i8g` are `rmsnorm_quant_i8` and `gelu_mul_quant_i8` with
`quant_act_i8g`'s quantiser instead: row-major int8 codes and an f32 scale per (row, 128 columns),
`scale` `[M, n / 128]`, what `gemm_nt_q` reads at `dtype=i8a8`, `w4a8i8_asym` and `w5a8i8`.
Byte-identical to the same chains ending in `quant_act_i8g`. `n` is a multiple of 128. On
`rmsnorm_quant_i8g`, `out_bf16` may be `x`'s own buffer: a junction whose next linear reads bf16 at
decode heights (`w4a16_asym`, `w5a16`) writes the norm output where the unfused norm would, in
place of the branch output it has consumed.
### `dequant_w4` (device-only)
| op | params | operands |
@@ -2453,6 +2463,7 @@ device code.
| `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w |
| `ar_rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt `sp`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `ar_rmsnorm_quant_i8g` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout |
| `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout |
| `ar_ln_had_quant_i8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
@@ -2463,6 +2474,8 @@ parameter for the same reason as `min_bytes`. `x` is inout on `ar_rmsnorm_quant_
the message and the input, and the reduced sum lands in it.
`ar_rmsnorm_had_quant_i8g` is `ar_rmsnorm_quant_fp8` with `rmsnorm_had_quant_i8g`'s quantiser:
`x` and the residual are the same bytes, and the codes are int8 for a weight at `i8a8h`.
`ar_rmsnorm_quant_i8g` is `ar_rmsnorm_quant_i8` with `rmsnorm_quant_i8g`'s quantiser, at two
ranks, with no `sp`; `out_bf16` may be `x`'s buffer, which then ends holding the norm output.
`sp` on `ar_rmsnorm_quant_i8` (0 when absent) lets a row split the all-reduce around the
junction: reduce-scatter, the junction on the rows this rank owns (`M` split evenly over the
+3 -2
View File
@@ -867,12 +867,13 @@ int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_
// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of
// the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8
// GEMM's per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch.
// GEMM's per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch. `grp`
// takes quant_act_i8g's quantiser instead (ar_rmsnorm_quant_i8g): `s` [M][n / 128], n % 128 == 0.
int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long x, long res, long w, long wp,
long sc, int sc_f32, long y, long q, long s, int M, int n, float eps,
float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq, long stage = 0);
int drain, int acq, int grp, long stage = 0);
// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC
// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the
// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with
+18 -7
View File
@@ -1448,14 +1448,15 @@ extern "C" int r4d_rad_ar_rmsnorm_had_quant_i8g(const RadArgs* a, RadStream s) {
* all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */
enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC };
/* The operands and their rules, the same at every width. */
/* The operands and their rules, the same at every width. `grp`: quant_act_i8g's grid
* (ar_rmsnorm_quant_i8g), a scale per (row, 128 columns) and K in whole groups. */
struct ArQ8Args {
const RadTensor *x = nullptr, *rs = nullptr, *w = nullptr, *q = nullptr, *sc = nullptr;
const RadTensor *ob = nullptr, *wp = nullptr, *sl = nullptr;
long long M = 0, K = 0, yp = 0, rp = 0;
};
static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) {
static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o, bool grp = false) {
const RadTensor* x = o->x = r4d_opt(a, AQ8_X);
const RadTensor* rs = o->rs = r4d_opt(a, AQ8_RES);
const RadTensor* w = o->w = r4d_opt(a, AQ8_W);
@@ -1471,12 +1472,12 @@ static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) {
long long M = 0, K = 0;
if (r4d_rows_of(x, &M, &K) != RAD_OK) return RAD_E_SHAPE;
if (M * K > in->max_numel) return RAD_E_SHAPE;
if (K % 16) return RAD_E_SHAPE;
if (K % 16 || (grp && K % 128)) return RAD_E_SHAPE;
if (r4d_numel(w) != K || (w->dtype != RAD_F32 && w->dtype != RAD_BF16)) return RAD_E_DTYPE;
if (wp && (r4d_numel(wp) != K || wp->dtype != w->dtype)) return RAD_E_SHAPE;
if (sl && (r4d_numel(sl) != 1 || (sl->dtype != RAD_F32 && sl->dtype != RAD_BF16))) return RAD_E_SHAPE;
if (r4d_numel(q) != M * K || !r4d_contig(q)) return RAD_E_SHAPE;
if (r4d_numel(sc) != M || !r4d_contig(sc)) return RAD_E_SHAPE;
if (r4d_numel(sc) != M * (grp ? K / 128 : 1) || !r4d_contig(sc)) return RAD_E_SHAPE;
if (ob && r4d_numel(ob) != M * K) return RAD_E_SHAPE;
if (rs && r4d_numel(rs) != M * K) return RAD_E_SHAPE;
const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0;
@@ -1486,12 +1487,12 @@ static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) {
return RAD_OK;
}
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
static int rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s, bool grp) {
const ArInst* in = (const ArInst*)(a ? a->instance : nullptr);
if (!in) return RAD_E_STATE;
if (in->world != 2) return RAD_E_SHAPE;
ArQ8Args v;
const int arc = ar_q8_args(a, in, &v);
const int arc = ar_q8_args(a, in, &v, grp);
if (arc != RAD_OK) return arc;
const long long M = v.M, K = v.K;
@@ -1508,10 +1509,20 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M,
(int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0),
v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain,
cfgv.acq, in->my_stage);
cfgv.acq, grp ? 1 : 0, in->my_stage);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) {
return rad_ar_rmsnorm_quant_i8(a, s, false);
}
/* The same at quant_act_i8g's grid (rmsnorm_quant_i8g's junction): two ranks only. A four-rank
* deployment declares it, finds no row, and issues the all-reduce apart. */
extern "C" int r4d_rad_ar_rmsnorm_quant_i8g(const RadArgs* a, RadStream s) {
return rad_ar_rmsnorm_quant_i8(a, s, true);
}
/* The same at four ranks, on the wide family's one-shot transport (r4d_rmsnorm_quant_i8.hip's
* ar_rmsnorm_quant_i8_wide_kernel), the one ar_hc_write_4rank rides, with the junction as its
* epilogue. The operands and the norm's width are the two-rank form's. The block count is one per
+36 -12
View File
@@ -5,18 +5,24 @@
// gelu_mul + quant_act_i8 pair and byte-identical to it: the product is formed as gelu_mul_kernel
// forms it (tanh form, same constants, rounded to bf16), and the absmax, scale and codes are
// quant_act_i8's over those bf16 values. The absmax is a max, so partitioning does not change it.
//
// `gelu_mul_quant_i8g` is the same product with quant_act_i8g's quantiser instead (GRP): row-major
// codes and an f32 scale per (row, 128 columns), for a down projection at i8a8, w4a8i8_asym or
// w5a8i8; byte-identical to gelu_mul + quant_act_i8g.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_chain.h"
#include "r4d_q8.h"
#include <cstdint>
namespace {
// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs
// to the end. The plain kernel and the chained one (r4dchain*) follow.
template <uint32_t THR, bool CHAIN>
// to the end. The plain kernel and the chained one (r4dchain*) follow. GRP: quant_act_i8g's codes
// and n / 128 scales a row (r4d_q8.h's q8_row_i8g) instead of quant_act_i8's.
template <uint32_t THR, bool CHAIN, bool GRP = false>
__device__ __forceinline__ void gelu_mul_quant_i8_body(
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
@@ -37,6 +43,12 @@ __device__ __forceinline__ void gelu_mul_quant_i8_body(
if (yo) yo[(size_t)row * y_ld + i] = y;
m = fmaxf(m, fabsf(bf16_to_f32(y)));
}
if constexpr (GRP) {
__syncthreads(); // publishes ybuf to every thread
q8_row_i8g<THR>(ybuf, qr, S + (size_t)row * (n / 128u), n);
if (CHAIN) r4d_chain_done();
return;
}
m = r4d_wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
@@ -56,26 +68,27 @@ __device__ __forceinline__ void gelu_mul_quant_i8_body(
if (CHAIN) r4d_chain_done();
}
template <uint32_t THR>
template <uint32_t THR, bool GRP = false>
__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel(
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
gelu_mul_quant_i8_body<THR, false>(gu, q, S, yo, n, gu_ld, y_ld);
gelu_mul_quant_i8_body<THR, false, GRP>(gu, q, S, yo, n, gu_ld, y_ld);
}
template <uint32_t THR>
template <uint32_t THR, bool GRP = false>
__global__ __launch_bounds__(THR) void r4dchain_gelu_mul_quant_i8(
const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S,
uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
gelu_mul_quant_i8_body<THR, true>(gu, q, S, yo, n, gu_ld, y_ld);
gelu_mul_quant_i8_body<THR, true, GRP>(gu, q, S, yo, n, gu_ld, y_ld);
}
} // namespace
// Operands (r4d_rows.cpp, oGeluMulQuantI8): gate_up [M][2n] bf16 (gate first), q [M][n] int8 in the
// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional.
// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional. gelu_mul_quant_i8g (`grp`): q
// row-major, scale [M][n / 128], n a multiple of 128.
enum { GM_GU = 0, GM_Q, GM_S, GM_Y };
extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
static int rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream, bool grp) {
int emit_rc = RAD_OK;
const RadTensor* gu = r4d_opt(a, GM_GU);
const RadTensor* q = r4d_opt(a, GM_Q);
@@ -85,12 +98,12 @@ extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
if (gu->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(q, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE);
if (n % 16 || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE);
if (n % 16 || (grp && n % 128) || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE);
long long Mg = 0;
const long long gp = r4d_rows_pitch(gu, 2 * n, &Mg);
if (gp < 0) return R4D_NO(RAD_E_STRIDE);
if (Mg < M) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(s) != M * (grp ? n / 128 : 1) || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE);
if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE);
const long long yp = y ? r4d_row_pitch(y) : n;
if (yp < 0) return R4D_NO(RAD_E_STRIDE);
@@ -98,16 +111,27 @@ extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
const int thr = r4d_act_threads((int)M, (int)n);
const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */
#define R4D_GMQ_C(T, C) R4D_EMIT(stream, (C ? r4dchain_gelu_mul_quant_i8<T> : gelu_mul_quant_i8_kernel<T>), \
#define R4D_GMQ_C(T, C, G) R4D_EMIT(stream, (C ? r4dchain_gelu_mul_quant_i8<T, G> : gelu_mul_quant_i8_kernel<T, G>), \
dim3((uint32_t)M), dim3(T), lds, \
(const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \
(uint32_t)n, (uint32_t)gp, (uint32_t)yp)
#define R4D_GMQ_T(T) emit_rc = chain ? R4D_GMQ_C(T, true) : R4D_GMQ_C(T, false)
#define R4D_GMQ_G(T, G) emit_rc = chain ? R4D_GMQ_C(T, true, G) : R4D_GMQ_C(T, false, G)
#define R4D_GMQ_T(T) do { if (grp) R4D_GMQ_G(T, true); else R4D_GMQ_G(T, false); } while (0)
if (thr == 1024) R4D_GMQ_T(1024);
else if (thr == 512) R4D_GMQ_T(512);
else if (thr == 256) R4D_GMQ_T(256);
else return R4D_NO(RAD_E_INVAL);
#undef R4D_GMQ_T
#undef R4D_GMQ_G
#undef R4D_GMQ_C
return emit_rc;
}
extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) {
return rad_gelu_mul_quant_i8(a, stream, false);
}
/* quant_act_i8g's grid: its own op, as quant_act_i8g is beside quant_act_i8. */
extern "C" int r4d_rad_gelu_mul_quant_i8g(const RadArgs* a, RadStream stream) {
return rad_gelu_mul_quant_i8(a, stream, true);
}
+3
View File
@@ -567,9 +567,12 @@ int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*
const RadTensor*, int, RadLayout*);
int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_gelu_mul_quant_i8g (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8g (const RadArgs*, RadStream);
int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream);
int r4d_rad_rmsnorm_quant_i8g (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_gated_had_quant_i8 (const RadArgs*, RadStream);
+28
View File
@@ -11,6 +11,7 @@
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
#include "r4d_common.h" // r4d_wave_max, for q8_row_i8g
template <bool I8>
__device__ __forceinline__ constexpr float q8_top() {
@@ -37,3 +38,30 @@ __device__ __forceinline__ uint32_t q8_pack4(float a, float b, float c, float d,
return (uint32_t)pk;
}
}
// The int8 codes of a whole bf16 row as quant_act_i8g writes them, for a producer whose row is
// staged in LDS (`row`, n values, n % 128 == 0) because it crossed threads on the way: the norm and
// gelu junctions of a Gemma trunk on an int8-per-(row, 128) grid (rmsnorm_quant_i8g,
// gelu_mul_quant_i8g). A wave takes a 128-column group and a lane four consecutive columns, as
// r4d_quant_act_fp8.hip's I8 form maps them; the absmax is a max, which any partition gives, and
// the scale (1 for an all-zero group), rounding and clamp are that form's. Codes row-major into `q`,
// the n / 128 scales into `s`. The caller publishes `row` behind a barrier first.
template <uint32_t THR>
__device__ __forceinline__ void q8_row_i8g(const uint16_t* row, signed char* __restrict__ q,
float* __restrict__ s, uint32_t n) {
const uint32_t lane = threadIdx.x & 31u, wave = threadIdx.x >> 5;
for (uint32_t kb = wave; kb < n / 128u; kb += THR / 32u) {
const uint32_t c0 = kb * 128u + lane * 4u;
float v[4];
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 4; ++j) {
v[j] = __uint_as_float((uint32_t)row[c0 + j] << 16);
m = fmaxf(m, fabsf(v[j]));
}
m = r4d_wave_max(m);
const float sc = m > 0.0f ? m * (1.0f / q8_top<true>()) : 1.0f;
if (lane == 0) s[kb] = sc;
*(uint32_t*)(q + c0) = q8_pack4<true>(v[0], v[1], v[2], v[3], 1.0f / sc);
}
}
+110 -58
View File
@@ -28,6 +28,11 @@
// The residual is read and written; each thread rewrites only the columns it read, so the second
// pass reads its own writes back.
//
// `rmsnorm_quant_i8g` and its two-rank all-reduce form are the same junction with quant_act_i8g's
// quantiser instead (GRP): row-major codes and an f32 scale per (row, 128 columns), what gemm_nt_q
// reads at i8a8, w4a8i8_asym and w5a8i8. Only the epilogue differs; it reads the same bf16 norm
// output from LDS, so the codes are the norm + quant_act_i8g pair's bytes.
//
// Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip.
#include "r4d_chain.h"
#include "r4d.h"
@@ -36,6 +41,7 @@
#include "r4d_common.h"
#include "r4d_ar_seq.h"
#include "r4d_ar_wide.h"
#include "r4d_q8.h"
#include <cstdint>
namespace {
@@ -71,15 +77,20 @@ __device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) {
return f32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
}
// quant_act_i8g's group, the width of one scale (r4d_quant_act_fp8.hip's kGroup).
constexpr uint32_t kGroupI8g = 128;
// 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.
// GRP: quant_act_i8g's codes and scales (r4d_q8.h's q8_row_i8g) instead of quant_act_i8's; `Sr`
// then holds n / 128 scales.
// `ybuf` holds the row's norm output for the code store, which reads across threads.
//
// The row body from the junction on: `s1` is the post-norm's factor, already reduced over `xr` by
// the caller (the plain kernel takes it off the row; the all-reduce form off the reduced sum it has
// just stored). l2 and lm are this function's own reduction planes.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, bool GRP = false>
__device__ __forceinline__ void junction_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
const void* __restrict__ wp, float sv, signed char* __restrict__ qr, float* __restrict__ Sr,
@@ -111,6 +122,11 @@ __device__ __forceinline__ void junction_row(
if (yr) yr[i] = y;
m = fmaxf(m, fabsf(bf2f(y)));
}
if constexpr (GRP) {
__syncthreads(); // publishes ybuf to every thread
q8_row_i8g<THR>(ybuf, qr, Sr, n);
return;
}
m = r4d_wave_max(m);
if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
@@ -159,7 +175,13 @@ __device__ __forceinline__ int4 fold_word8(const int4* const* src4, size_t k) {
return a;
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
// A row's scales: one, or n / 128 at quant_act_i8g's grid.
template <bool GRP>
__device__ __forceinline__ uint32_t scales_a_row(uint32_t n) {
return GRP ? n / kGroupI8g : 1u;
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, bool GRP = false>
__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,
@@ -181,10 +203,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
ss = block_sum<THR / kWave>(ss, l1);
s1 = rsqrtf(ss / (float)n + eps);
}
junction_row<WF32, RES, POST, SCL, THR>(
junction_row<WF32, RES, POST, SCL, THR, GRP>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, SCL ? scalar_of(sc, sc_f32) : 1.0f,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1,
ybuf, l2, lm);
q + (size_t)row * n, S + (size_t)row * scales_a_row<GRP>(n),
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm);
}
// The same kernel at decode heights (THR 1024, n <= 1024 * EPT), with every operand of the row
@@ -195,8 +217,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
// own columns in registers; the sums and the fragment-order store cross threads through `ybuf`,
// which holds the row each sum folds in the standalone norm's partition. The sums, their order and
// every element's arithmetic are junction_row's, so the output bytes are the same. One row of it, for this kernel and for the all-reduce's tail
// (ar_rmsnorm_quant_i8_tail_kernel).
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
// (ar_rmsnorm_quant_i8_tail_kernel). GRP as in junction_row.
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT, bool GRP = false>
__device__ __forceinline__ void junction_reg_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
@@ -265,6 +287,11 @@ __device__ __forceinline__ void junction_reg_row(
m = fmaxf(m, fabsf(bf2f(y)));
}
}
if constexpr (GRP) {
__syncthreads(); // publishes ybuf to every thread
q8_row_i8g<THR>(ybuf, qr, Sr, n);
return;
}
m = r4d_wave_max(m);
if ((tid & 31) == 0) lm[tid >> 5] = m;
__syncthreads(); // also publishes ybuf to every thread
@@ -284,7 +311,7 @@ __device__ __forceinline__ void junction_reg_row(
}
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT, bool GRP = false>
__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_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,
@@ -293,10 +320,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel(
extern __shared__ uint16_t ybuf[];
__shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave];
const uint32_t row = blockIdx.x;
junction_reg_row<WF32, RES, POST, SCL, THR, EPT>(
junction_reg_row<WF32, RES, POST, SCL, THR, EPT, GRP>(
x + (size_t)row * x_ld, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32,
q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf,
l1, l2, lm);
q + (size_t)row * n, S + (size_t)row * scales_a_row<GRP>(n),
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf, l1, l2, lm);
}
// ---------------------------------------------------------------------------------------------
@@ -319,7 +346,7 @@ __device__ __forceinline__ unsigned int arq8_load_acq(const unsigned int* p) {
return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM);
}
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR>
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, bool GRP = false>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32,
@@ -387,9 +414,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
if (POST) { __syncthreads(); ss = lanes_sumsq(ybuf, n); }
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
junction_row<WF32, RES, POST, SCL, THR>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row,
yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm);
junction_row<WF32, RES, POST, SCL, THR, GRP>(
xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n,
S + (size_t)row * scales_a_row<GRP>(n), yo ? yo + (size_t)row * y_ld : nullptr, n, eps,
wadd, s1, ybuf, l2, lm);
__syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */
}
}
@@ -873,9 +901,11 @@ __global__ __launch_bounds__(THR) void r4dchain_ar_rmsnorm_quant_i8_sp(R4D_ARQ8S
// 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
// rmsnorm_quant_i8g (`grp`) takes the same operands with quant_act_i8g's grid: q row-major, scale
// [M][n / 128], n a multiple of 128.
enum { RQ_X = 0, RQ_RES, RQ_W, RQ_Q, RQ_S, RQ_Y, RQ_WP, RQ_SC };
extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
static int rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream, bool grp) {
int emit_rc = RAD_OK;
const RadTensor* x = r4d_opt(a, RQ_X);
const RadTensor* rs = r4d_opt(a, RQ_RES);
@@ -896,13 +926,14 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
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 (grp && n % kGroupI8g) return R4D_NO(RAD_E_SHAPE); // whole scale groups
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 (r4d_numel(s) != M * (grp ? n / kGroupI8g : 1) || !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.
// The row's norm output is staged in LDS for the cross-thread code store.
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
@@ -923,35 +954,40 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
: thr == 512 ? (n <= 4096 ? 8 : n <= 6144 ? 12 : n <= 8192 ? 16 : 0)
: 0;
#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)M), dim3(T), lds, \
#define R4D_RQI8_T(WF, RS, PO, SC, T, G) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T, G>), 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_R(WF, RS, PO, SC, T, E) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_reg_kernel<WF, RS, PO, SC, T, E>), dim3((uint32_t)M), dim3(T), lds, \
#define R4D_RQI8_R(WF, RS, PO, SC, T, E, G) emit_rc = R4D_EMIT(stream, \
(rmsnorm_quant_i8_reg_kernel<WF, RS, PO, SC, T, E, G>), 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 && ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 1024, 4); \
else if (thr == 1024 && ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 1024, 6); \
else if (thr == 1024 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 1024, 8); \
else if (thr == 512 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 512, 8); \
else if (thr == 512 && ept == 12) R4D_RQI8_R(WF, RS, PO, SC, 512, 12); \
else if (thr == 512 && ept == 16) R4D_RQI8_R(WF, RS, PO, SC, 512, 16); \
else 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); \
#define R4D_RQI8(WF, RS, PO, SC, G) \
do { if (thr == 1024 && ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 1024, 4, G); \
else if (thr == 1024 && ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 1024, 6, G); \
else if (thr == 1024 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 1024, 8, G); \
else if (thr == 512 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 512, 8, G); \
else if (thr == 512 && ept == 12) R4D_RQI8_R(WF, RS, PO, SC, 512, 12, G); \
else if (thr == 512 && ept == 16) R4D_RQI8_R(WF, RS, PO, SC, 512, 16, G); \
else if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024, G); \
else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512, G); \
else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256, G); \
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);
#define R4D_RQI8_W(WF, G) \
do { if (!rs) R4D_RQI8(WF, false, false, false, G); \
else if (!wp && !sc) R4D_RQI8(WF, true, false, false, G); \
else if (wp && !sc) R4D_RQI8(WF, true, true, false, G); \
else if (wp && sc) R4D_RQI8(WF, true, true, true, G); \
else R4D_RQI8(WF, true, false, true, G); } while (0)
if (grp) {
if (w->dtype == RAD_F32) R4D_RQI8_W(true, true);
else R4D_RQI8_W(false, true);
} else {
if (w->dtype == RAD_F32) R4D_RQI8_W(true, false);
else R4D_RQI8_W(false, false);
}
#undef R4D_RQI8_W
#undef R4D_RQI8
#undef R4D_RQI8_R
@@ -959,20 +995,31 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
return emit_rc;
}
extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
return rad_rmsnorm_quant_i8(a, stream, false);
}
/* quant_act_i8g's grid: a separate op, not a parameter, since its scale plane has another shape and
* its codes another order (as quant_act_i8 and quant_act_i8g are two ops). */
extern "C" int r4d_rad_rmsnorm_quant_i8g(const RadArgs* a, RadStream stream) {
return rad_rmsnorm_quant_i8(a, stream, true);
}
// The fused all-reduce form's launch. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the
// double-buffered scratch, the per-block flags and the device-resident sequence counters -- and the
// rest is the junction's. `x` is the message and takes no pitch; `nblocks` is clamped to M (a block
// owns whole rows). Returns 0, or a negative code for a shape it does not serve.
// owns whole rows). `grp` takes quant_act_i8g's grid (ar_rmsnorm_quant_i8g): `s` is [M][n / 128]
// and n a multiple of 128. Returns 0, or a negative code for a shape it does not serve.
extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16,
long x, long res, long w, long wp, long sc, int sc_f32,
long y, long q, long s, int M, int n, float eps, float wadd,
int w_f32, int r_ld, int y_ld, long stream, int nblocks,
int drain, int acq, long stage) {
int drain, int acq, int grp, long stage) {
if (!x || !w || !q || !s) return -1;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 16) return -3;
if (n % 16 || (grp && n % (int)kGroupI8g)) return -3;
if ((wp || sc) && !res) return -5;
if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6;
if (!r_ld) r_ld = n;
@@ -983,8 +1030,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
if (nb > nbw) nb = nbw;
const int thr = r4d_act_threads(M, n);
const size_t lds = (size_t)n * sizeof(uint16_t);
#define R4D_ARQ8_T(WF, RS, PO, SC, T) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T>), dim3((uint32_t)nb), \
#define R4D_ARQ8_T(WF, RS, PO, SC, T, G) \
hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel<WF, RS, PO, SC, T, G>), dim3((uint32_t)nb), \
dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \
(const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \
(signed char*)q, (float*)s, (uint16_t*)y, (int4*)peer_scratch, \
@@ -992,18 +1039,23 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long
(unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \
wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \
(unsigned)nbw, stage)
#define R4D_ARQ8(WF, RS, PO, SC) \
do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512); \
else R4D_ARQ8_T(WF, RS, PO, SC, 256); } while (0)
#define R4D_ARQ8_W(WF) \
do { if (!res) R4D_ARQ8(WF, false, false, false); \
else if (!wp && !sc) R4D_ARQ8(WF, true, false, false); \
else if (wp && !sc) R4D_ARQ8(WF, true, true, false); \
else if (wp && sc) R4D_ARQ8(WF, true, true, true); \
else R4D_ARQ8(WF, true, false, true); } while (0)
if (w_f32) R4D_ARQ8_W(true);
else R4D_ARQ8_W(false);
#define R4D_ARQ8(WF, RS, PO, SC, G) \
do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024, G); \
else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512, G); \
else R4D_ARQ8_T(WF, RS, PO, SC, 256, G); } while (0)
#define R4D_ARQ8_W(WF, G) \
do { if (!res) R4D_ARQ8(WF, false, false, false, G); \
else if (!wp && !sc) R4D_ARQ8(WF, true, false, false, G); \
else if (wp && !sc) R4D_ARQ8(WF, true, true, false, G); \
else if (wp && sc) R4D_ARQ8(WF, true, true, true, G); \
else R4D_ARQ8(WF, true, false, true, G); } while (0)
if (grp) {
if (w_f32) R4D_ARQ8_W(true, true);
else R4D_ARQ8_W(false, true);
} else {
if (w_f32) R4D_ARQ8_W(true, false);
else R4D_ARQ8_W(false, false);
}
#undef R4D_ARQ8_W
#undef R4D_ARQ8
#undef R4D_ARQ8_T
+71 -1
View File
@@ -1523,6 +1523,11 @@ static const RadOperandSpec oRmsNormQuantI8[] = {
{ "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 */
};
/* `rmsnorm_quant_i8g` is the same junction with quant_act_i8g's quantiser on its pass: row-major
* int8 codes and an f32 scale per (row, 128 columns), what gemm_nt_q reads at i8a8, w4a8i8_asym and
* w5a8i8. Same parameters and operands, `scale` [M, n / 128]; `out_bf16` may be x's own buffer,
* which a caller whose next linear reads bf16 at decode heights uses (every thread writes it only
* after every read of x). */
/* `qkv_norm_rope` is `qk_norm_rope` over separate q, k and v projections: the per-head q and k
* norms, the weightless value norm and the rotary of q and k in one dispatch (Gemma 4's attention
@@ -1627,6 +1632,17 @@ static const RadOperandSpec oArRmsNormQuantI8[] = {
{ "w_post", RAD_OPD_WEIGHT, 1 },
{ "scalar", RAD_OPD_WEIGHT, 1 },
};
/* `ar_rmsnorm_quant_i8g` is rmsnorm_quant_i8g with the exact all-reduce of `x` in front: the same
* operands as ar_rmsnorm_quant_i8 with `scale` [M, n / 128]. No `sp`: the split form gathers one
* scale a row. */
static const RadParamSpec pArRmsNormQuantI8g[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("eps"),
{ "world_size", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
};
static const RadParamSpec pGatedQuantFp8[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
@@ -3474,6 +3490,10 @@ static const RadOpSchema kSchemas[] = {
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("rmsnorm_quant_i8g", pRmsNormQuantI8, oRmsNormQuantI8,
"rmsnorm_quant_i8 with quant_act_i8g's quantiser on its pass: row-major int8 codes and "
"an f32 scale per (row, 128 columns); byte-identical to the chain ending in "
"quant_act_i8g. out_bf16 may be x's own buffer."),
SCHEMA("add_rmsnorm", pAddRmsNorm, oAddRmsNorm,
"x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add "
"and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken "
@@ -3495,8 +3515,13 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("gelu_mul_quant_i8", pGeluMulQuantI8, oGeluMulQuantI8,
"gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in "
"one pass."),
SCHEMA("gelu_mul_quant_i8g", pGeluMulQuantI8, oGeluMulQuantI8,
"gelu(gate) * up (tanh form) and quant_act_i8g's quantiser (row-major int8, an f32 scale "
"per (row, 128 columns)), in one pass; byte-identical to gelu_mul + quant_act_i8g."),
SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8,
"the two- or four-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."),
SCHEMA("ar_rmsnorm_quant_i8g", pArRmsNormQuantI8g, oArRmsNormQuantI8,
"the two-rank exact all-reduce of x and rmsnorm_quant_i8g after it, in one kernel."),
SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
"silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."),
SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8,
@@ -5093,6 +5118,10 @@ static const RadConstraint cQuantActI8[] = {
static const RadConstraint cRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
/* The same at quant_act_i8g's grid: whole 128-column scale groups. */
static const RadConstraint cRmsNormQuantI8g[] = {
C_DIV("n", 128), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
static const RadConstraint cAddRmsNorm[] = {
C_GE("n", 1), C_IN("dtype", "bf16"),
};
@@ -5125,10 +5154,16 @@ static const RadConstraint cQkvNormRopeKvH128Bf16[] = {
static const RadConstraint cGeluMulQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
static const RadConstraint cGeluMulQuantI8g[] = {
C_DIV("n", 128), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
/* x is the message, pushed as 16B words, and the row is staged in LDS for the fragment store. */
static const RadConstraint cArRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P,
};
static const RadConstraint cArRmsNormQuantI8g[] = {
C_DIV("n", 128), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P,
};
/* The same at four ranks, on the wide family's transport. */
static const RadConstraint cArRmsNormQuantI84[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 4), C_P2P,
@@ -8997,6 +9032,19 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
ROW(cRmsNormQuantI8), ROW(tRmsQ8), nullptr,
nullptr, nullptr, r4d_rad_rmsnorm_quant_i8 },
/* Its quant_act_i8g twin: the same kernels with q8_row_i8g as their epilogue (r4d_q8.h). */
{ "rmsnorm_quant_i8g", "rmsnorm_quant_i8g", "quant",
"RMS norm and quant_act_i8g'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 128 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; out_bf16 may "
"be x's own buffer",
"bf16 in, int8 out row-major with an f32 scale per (row, 128 columns), optional bf16 out; every "
"stored intermediate rounded to bf16 as the unfused chain stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cRmsNormQuantI8g), ROW(tRmsQ8), nullptr,
nullptr, nullptr, r4d_rad_rmsnorm_quant_i8g },
{ "qkv_norm_rope_bf16", "qkv_norm_rope", "attn",
"per-head RMS norms of separate q and k projections, the weightless norm of v (or of the raw k), "
"and the rotary of q and k, in place, in one dispatch",
@@ -9093,6 +9141,15 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
ROW(cGeluMulQuantI8), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_mul_quant_i8 },
{ "gelu_mul_quant_i8g", "gelu_mul_quant_i8g", "quant",
"gelu(gate) * up, the tanh form, and quant_act_i8g's quantiser in one pass over the row",
"n a multiple of 128 and n*2 bytes within LDS; one workgroup per row",
"bf16 gate_up in, int8 out row-major with an f32 scale per (row, 128 columns), optional bf16 "
"out; the codes taken over the bf16-rounded product",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGeluMulQuantI8g), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_mul_quant_i8g },
{ "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8", "quant",
"the two-rank exact all-reduce and the junction after it -- post-norm of the reduced sum, residual "
"add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel",
@@ -9103,6 +9160,19 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
ROW(cArRmsNormQuantI8), ROW(tAr), nullptr,
r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 },
/* Its quant_act_i8g twin: the two-rank kernel with rmsnorm_quant_i8g's epilogue. No four-rank
* form yet; a four-rank caller finds no row and issues the all-reduce apart. */
{ "ar_rmsnorm_quant_i8g", "ar_rmsnorm_quant_i8g", "quant",
"the two-rank exact all-reduce and the junction after it -- post-norm of the reduced sum, residual "
"add, scalar, RMS norm and quant_act_i8g's quantiser -- in one kernel",
"exactly 2 ranks; n a multiple of 128, x unpitched (it is the message); one block a row; exact "
"wire; out_bf16 may be x's own buffer",
"bf16 in, int8 out row-major with an f32 scale per (row, 128 columns); the reduced sum rounded "
"to bf16 as the standalone exact all-reduce stores it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cArRmsNormQuantI8g), ROW(tAr), nullptr,
r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8g },
/* Its arithmetic is the four-rank exact all-reduce's fold followed by the two-rank form's
* junction, each the code those two run, in every form (one-shot, tail, split). r4d_selftest's
* case of the same name holds each form byte for byte to all_reduce + rmsnorm_quant_i8 on a
@@ -10440,7 +10510,7 @@ extern "C" int rad_kernel_chain(int i) {
const RadKernelInfo* k = rad_kernel_at(i);
if (!k) return 0;
static const char* const kChained[] = {
"gemm_w4a8_nt_m64", "gelu_mul_quant_i8", "qkv_norm_rope_bf16",
"gemm_w4a8_nt_m64", "gelu_mul_quant_i8", "gelu_mul_quant_i8g", "qkv_norm_rope_bf16",
"qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store_bf16",
/* the split-KV decode and its merge (r4d_decode_launch_win); their prefill kernel stays
* plain, and the backend chains only the kernels named r4dchain* */
+105 -53
View File
@@ -14164,38 +14164,49 @@ static void fused_quant_fp8_numeric(const Plugin& pl) {
}
/* ---- gelu_mul_quant_i8, against gelu_mul + quant_act_i8 -------------------------------------
* Gemma 4 31B's per-rank feed-forward width (10752 of 21504 at two ranks), both batch widths. */
static void gelu_mul_quant_i8_numeric(const Plugin& pl) {
* Gemma 4 31B's per-rank feed-forward width (10752 of 21504 at two ranks), both batch widths.
* `grp`: gelu_mul_quant_i8g against gelu_mul + quant_act_i8g, a scale per (row, 128), and a
* prefill height (the 256-thread width) besides. */
static void gelu_mul_quant_i8_numeric(const Plugin& pl, bool grp = false) {
const char* const fzn = grp ? "gelu_mul_quant_i8g" : "gelu_mul_quant_i8";
const char* const qzn = grp ? "quant_act_i8g" : "quant_act_i8";
const RadKernelInfo* gm = find(pl, "gelu_mul_bf16");
const RadKernelInfo* qz = find(pl, "quant_act_i8");
const RadKernelInfo* fz = find(pl, "gelu_mul_quant_i8");
if (!gm || !qz || !fz) { ok("gelu_mul_quant_i8 vs its pair", false, "rows absent"); return; }
for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) {
const RadKernelInfo* qz = find(pl, qzn);
const RadKernelInfo* fz = find(pl, fzn);
const std::string pair = std::string("gelu_mul + ") + qzn;
if (!gm || !qz || !fz) { ok((std::string(fzn) + " vs its pair").c_str(), false, "rows absent"); return; }
for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40, (int64_t)200 }) {
if (M == 200 && !grp) continue;
const int64_t n = 10752;
const int64_t sn = grp ? n / 128 : 1; /* scales a row */
std::vector<uint16_t> hgu((size_t)M * 2 * n);
for (size_t i = 0; i < hgu.size(); ++i)
hgu[i] = h_to_bf16(std::ldexp(1.0f, (int)((i / 512) % 5) - 2) * (0.029f * (float)((i * 41) % 103) - 1.5f));
void* dgu = dalloc(hgu.size() * 2);
void* dy[2] = { dalloc((size_t)M * n * 2), dalloc((size_t)M * n * 2) };
void* dq[2] = { dalloc((size_t)M * n), dalloc((size_t)M * n) };
void* ds[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) };
if (!dgu || !dy[1] || !dq[1] || !ds[1]) { ok("gelu_mul_quant_i8 alloc", false, "hipMalloc failed"); return; }
void* ds[2] = { dalloc((size_t)(M * sn) * 4), dalloc((size_t)(M * sn) * 4) };
if (!dgu || !dy[1] || !dq[1] || !ds[1]) { ok((std::string(fzn) + " alloc").c_str(), false, "hipMalloc failed"); return; }
st_memcpy(dgu, hgu.data(), hgu.size() * 2, hipMemcpyHostToDevice);
int rc = launch_row(gm, { T(dgu, RAD_BF16, { M, 2 * n }), T(dy[0], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
if (rc == RAD_OK)
if (rc == RAD_OK && grp)
rc = launch_row(qz, { T(dy[0], RAD_BF16, { M, n }), T(dq[0], RAD_I8, { M, n }), T(ds[0], RAD_F32, { M, sn }) },
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16") });
else if (rc == RAD_OK)
rc = launch_row(qz, { T(dy[0], RAD_BF16, { M, n }), T(dq[0], RAD_I8, { M, n }), T(ds[0], RAD_F32, { M }),
T(nullptr, RAD_F32, {}) },
{ PI("M", M), PI("n", n), PI("group", n), PS("dtype", "bf16") });
if (rc == RAD_OK)
rc = launch_row(fz, { T(dgu, RAD_BF16, { M, 2 * n }), T(dq[1], RAD_I8, { M, n }), T(ds[1], RAD_F32, { M }),
rc = launch_row(fz, { T(dgu, RAD_BF16, { M, 2 * n }), T(dq[1], RAD_I8, { M, n }),
grp ? T(ds[1], RAD_F32, { M, sn }) : T(ds[1], RAD_F32, { M }),
T(dy[1], RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
const std::string what = "gelu_mul_quant_i8 M=" + std::to_string(M);
if (rc != RAD_OK) { ok((what + " vs gelu_mul + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc)); continue; }
const std::string what = std::string(fzn) + " M=" + std::to_string(M);
if (rc != RAD_OK) { ok((what + " vs " + pair).c_str(), false, "rc=" + std::to_string(rc)); continue; }
std::vector<uint16_t> y0((size_t)M * n), y1((size_t)M * n);
std::vector<uint8_t> q0((size_t)M * n), q1((size_t)M * n);
std::vector<float> s0((size_t)M), s1((size_t)M);
std::vector<float> s0((size_t)(M * sn)), s1((size_t)(M * sn));
st_memcpy(y0.data(), dy[0], y0.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(y1.data(), dy[1], y1.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(q0.data(), dq[0], q0.size(), hipMemcpyDeviceToHost);
@@ -14206,7 +14217,7 @@ static void gelu_mul_quant_i8_numeric(const Plugin& pl) {
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]; nz += q1[i] != 0; }
for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0;
ok((what + " is byte-identical to gelu_mul + quant_act_i8").c_str(), ny == 0 && nq == 0 && ns == 0 && nz > (int)q1.size() / 2,
ok((what + " is byte-identical to " + pair).c_str(), ny == 0 && nq == 0 && ns == 0 && nz > (int)q1.size() / 2,
"bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " + std::to_string(ns) +
", nonzero codes " + std::to_string(nz));
}
@@ -14471,23 +14482,29 @@ static void add_rmsnorm_numeric(const Plugin& pl) {
* feed-forward) and with one (feed-forward -> next layer). The unfused chain, kernel by kernel, is
* rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8. bf16 gains
* (as Gemma's checkpoint stores), and two batch heights covering both r4d_act_threads widths a
* decode step meets (1024 at M <= 32, 512 above), the first in both of its forms. */
static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
* decode step meets (1024 at M <= 32, 512 above), the first in both of its forms. `grp`:
* rmsnorm_quant_i8g against the same chain ending in quant_act_i8g. */
static void rmsnorm_quant_i8_numeric(const Plugin& pl, bool grp = false) {
const char* const rqn = grp ? "rmsnorm_quant_i8g" : "rmsnorm_quant_i8";
const char* const qzn = grp ? "quant_act_i8g" : "quant_act_i8";
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; }
const RadKernelInfo* qz = find(pl, qzn);
const RadKernelInfo* rq = find(pl, rqn);
if (!nrm || !ad || !scl || !qz || !rq) { ok((std::string(rqn) + " vs its chain").c_str(), false, "rows absent"); return; }
/* The row's reg axis at 1024 threads: 1 (the default) holds a thread's columns in registers,
* 0 re-reads the row each pass; both must leave the chain's bytes. */
struct RqCase { int64_t M; int reg; };
/* 40 and 64 rows: the 512-thread width, its register form and its re-read form */
/* ...and at quant_act_i8g's grid a prefill height besides (the 256-thread width) */
for (const RqCase rqc : { RqCase{ 1, 1 }, RqCase{ 8, 1 }, RqCase{ 8, 0 }, RqCase{ 40, 1 },
RqCase{ 40, 0 }, RqCase{ 64, 1 } }) {
RqCase{ 40, 0 }, RqCase{ 64, 1 }, RqCase{ 200, 1 } }) {
if (rqc.M == 200 && !grp) continue;
const int64_t M = rqc.M;
const std::string form = rqc.reg ? "" : " (re-read form)";
const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps */
const int64_t SK = grp ? K / 128 : 1; /* scales a row */
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) {
@@ -14509,9 +14526,9 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
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) };
void* d_s[2] = { dalloc((size_t)(M * SK) * 4), dalloc((size_t)(M * SK) * 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");
ok((std::string(rqn) + " alloc").c_str(), false, "hipMalloc failed");
return;
}
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
@@ -14521,14 +14538,17 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
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") };
const std::vector<RadParam> pq = { PI("M", M), PI("n", K), PI("group", grp ? 128 : K), PS("dtype", "bf16") };
const RadTensor ts0 = grp ? T(d_s[0], RAD_F32, { M, SK }) : T(d_s[0], RAD_F32, { M });
const RadTensor ts1 = grp ? T(d_s[1], RAD_F32, { M, SK }) : T(d_s[1], RAD_F32, { M });
const std::string chain_q = std::string(" + ") + qzn;
std::vector<RadParam> prq = pn;
prq.push_back(PI("reg", rqc.reg));
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);
std::vector<float> s0((size_t)(M * SK)), s1((size_t)(M * SK));
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);
@@ -14547,11 +14567,13 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
"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 */
auto norm_quant = [&](void* src) { /* rmsnorm(src; w) -> the quantiser, 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)
if (rc == RAD_OK && grp)
rc = launch_row(qz, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }), ts0 }, pq);
else 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);
ts0, T(nullptr, RAD_F32, {}) }, pq);
return rc;
};
@@ -14559,15 +14581,21 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
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(d_q[1], RAD_I8, { M, K }), ts1, T(d_y[1], RAD_BF16, { M, K }),
T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, prq);
if (rc != RAD_OK) ok(("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8" + form).c_str(), false, "rc=" + std::to_string(rc));
else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8" + form, false);
if (rc != RAD_OK) ok((rqn + std::string(" vs rmsnorm") + chain_q + form).c_str(), false, "rc=" + std::to_string(rc));
else compare(rqn + std::string(" is byte-identical to rmsnorm") + chain_q + form, false);
/* --- the junction, without and with the scalar --- */
for (const bool with_sc : { false, true }) {
/* --- the junction, without and with the scalar; at quant_act_i8g's grid also with the
* norm output written over the branch output (out_bf16 on x's own buffer), as Gemma 4's
* junction writes it before an a4 linear's decode band --- */
for (const int jf : { 0, 1, 2 }) {
const bool with_sc = jf > 0, alias = jf == 2;
if (alias && !grp) continue;
st_memcpy(d_r[0], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_r[1], hr.data(), hr.size() * 2, hipMemcpyHostToDevice);
if (alias) st_memcpy(d_y[1], hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
void* const fx = alias ? d_y[1] : d_x;
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);
@@ -14575,12 +14603,13 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
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 }),
rc = launch_row(rq, { T(fx, 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 }), ts1, 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, {}) }, prq);
const std::string what = (with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction") + form;
if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc));
const std::string what = rqn + std::string(with_sc ? " junction with scalar" : " junction") +
(alias ? ", out_bf16 over x" : "") + form;
if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm" + chain_q).c_str(), false, "rc=" + std::to_string(rc));
else compare(what + " is byte-identical to its chain", true);
}
}
@@ -28712,6 +28741,8 @@ struct ArQ8 {
long long gate_after = -1; /* ...and what the launch left in it */
int tail = -1; /* the `tail` axis pinned, or -1: the default */
int sp = 0; /* `sp`: the all-reduce split around the junction */
bool grp = false; /* quant_act_i8g's grid (ar_rmsnorm_quant_i8g) */
bool alias = false; /* out_bf16 on x's own buffer */
void* inst = nullptr;
int rc_init = RAD_E_STATE, rc_launch = RAD_OK;
const std::vector<uint16_t>* r_in = nullptr; /* the replicated residual, w and w_post */
@@ -28739,10 +28770,11 @@ static void ar_q8_worker(ArQ8* t) {
void* x = nullptr; void* r = nullptr; void* w = nullptr; void* wp = nullptr; void* sc = nullptr;
void* q = nullptr; void* s = nullptr; void* y = nullptr; void* gw = nullptr;
const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2;
const int64_t SK = t->grp ? K / 128 : 1; /* scales a row */
const bool mem = hipMalloc(&x, xb) == hipSuccess && hipMalloc(&r, xb) == hipSuccess &&
hipMalloc(&w, wb) == hipSuccess && hipMalloc(&wp, wb) == hipSuccess &&
hipMalloc(&sc, 4) == hipSuccess && hipMalloc(&q, (size_t)(M * K)) == hipSuccess &&
hipMalloc(&s, (size_t)M * 4) == hipSuccess && hipMalloc(&y, xb) == hipSuccess &&
hipMalloc(&s, (size_t)(M * SK) * 4) == hipSuccess && hipMalloc(&y, xb) == hipSuccess &&
(!t->gated || hipMalloc(&gw, 8) == hipSuccess);
if (!mem) {
t->rc_launch = RAD_E_NOMEM;
@@ -28760,8 +28792,8 @@ static void ar_q8_worker(ArQ8* t) {
st_memcpy(sc, &t->sc, 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(x, RAD_BF16, { M, K }), T(r, RAD_BF16, { M, K }), T(w, RAD_BF16, { K }),
T(q, RAD_I8, { M, K }), T(s, RAD_F32, { M }), T(y, RAD_BF16, { M, K }),
T(wp, RAD_BF16, { K }), T(sc, RAD_BF16, { 1 }) };
T(q, RAD_I8, { M, K }), t->grp ? T(s, RAD_F32, { M, SK }) : T(s, RAD_F32, { M }),
T(t->alias ? x : y, RAD_BF16, { M, K }), T(wp, RAD_BF16, { K }), T(sc, RAD_BF16, { 1 }) };
if (!t->res) { absent(ts[1]); absent(ts[6]); }
if (!t->scal) absent(ts[7]);
if (t->sp) absent(ts[5]); /* the split form leaves no bf16 output */
@@ -28778,12 +28810,12 @@ static void ar_q8_worker(ArQ8* t) {
t->r_out.resize((size_t)(M * K));
t->y_out.resize((size_t)(M * K));
t->q_out.resize((size_t)(M * K));
t->s_out.resize((size_t)M);
t->s_out.resize((size_t)(M * SK));
st_memcpy(t->x_out.data(), x, xb, hipMemcpyDeviceToHost);
st_memcpy(t->r_out.data(), r, xb, hipMemcpyDeviceToHost);
st_memcpy(t->y_out.data(), y, xb, hipMemcpyDeviceToHost);
st_memcpy(t->y_out.data(), t->alias ? x : y, xb, hipMemcpyDeviceToHost);
st_memcpy(t->q_out.data(), q, (size_t)(M * K), hipMemcpyDeviceToHost);
st_memcpy(t->s_out.data(), s, (size_t)M * 4, hipMemcpyDeviceToHost);
st_memcpy(t->s_out.data(), s, (size_t)(M * SK) * 4, hipMemcpyDeviceToHost);
if (gw) st_memcpy(&t->gate_after, gw, 8, hipMemcpyDeviceToHost);
}
for (void* p : { x, r, w, wp, sc, q, s, y, gw }) if (p) st_free(p);
@@ -28796,8 +28828,10 @@ static bool nm_ends_with(const char* s, const char* tail) {
static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<int>& devs,
const char* name) {
/* ar_rmsnorm_quant_i8g: quant_act_i8g's grid, two ranks, held to rmsnorm_quant_i8g */
const bool grp = std::strstr(name, "_i8g") != nullptr;
const RadKernelInfo* row = find(pl, name);
const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8");
const RadKernelInfo* rq = find(pl, grp ? "rmsnorm_quant_i8g" : "rmsnorm_quant_i8");
if (!row || !rq) { ok(name, false, "row absent"); return; }
const int world = std::strstr(name, "_4rank") ? 4 : 2;
if ((int)devs.size() < world) {
@@ -28825,7 +28859,9 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
const std::string nm(name);
for (const Shape& sh : shapes) {
if (world == 2 && (sh.tail || sh.sp)) continue;
if (grp && sh.K % 128) continue;
const int64_t M = sh.M, K = sh.K;
const int64_t SK = grp ? K / 128 : 1; /* scales a row */
std::vector<uint16_t> hr((size_t)(M * K)), hw((size_t)K), hp((size_t)K);
for (int64_t i = 0; i < M; ++i)
for (int64_t c = 0; c < K; ++c)
@@ -28854,11 +28890,15 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
xsum[(size_t)i] = h_to_bf16(acc);
}
for (const int form : { 0, 1, 2 }) { /* the plain norm, the junction, with the scalar */
const bool res = form > 0, scal = form == 2;
/* the plain norm, the junction, with the scalar; at quant_act_i8g's grid that last with
* the norm output written over x (out_bf16 on x's buffer) besides */
for (const int form : { 0, 1, 2, 3 }) {
if (form == 3 && !grp) continue;
const bool res = form > 0, scal = form >= 2, alias = form == 3;
const std::string at = " M=" + std::to_string(M) + " n=" + std::to_string(K) +
(form == 0 ? ", plain" : form == 1 ? ", junction"
: ", junction with scalar") +
: form == 2 ? ", junction with scalar"
: ", junction with scalar, out_bf16 over x") +
(sh.sp == 2 ? ", split around the junction, residual gathered"
: sh.sp ? ", split around the junction"
: sh.tail ? ", two-shot with the junction as its tail" : ", one-shot");
@@ -28868,7 +28908,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2;
void* d_x = dalloc(xb); void* d_r = dalloc(xb); void* d_w = dalloc(wb);
void* d_p = dalloc(wb); void* d_sc = dalloc(4); void* d_q = dalloc((size_t)(M * K));
void* d_s = dalloc((size_t)M * 4); void* d_y = dalloc(xb);
void* d_s = dalloc((size_t)(M * SK) * 4); void* d_y = dalloc(xb);
if (!d_x || !d_r || !d_w || !d_p || !d_sc || !d_q || !d_s || !d_y) {
ok((nm + at + " alloc").c_str(), false, "hipMalloc failed");
return;
@@ -28883,7 +28923,8 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
const int rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }),
res ? T(d_r, RAD_BF16, { M, K }) : T(nullptr, RAD_BF16, {}),
T(d_w, RAD_BF16, { K }), T(d_q, RAD_I8, { M, K }),
T(d_s, RAD_F32, { M }), T(d_y, RAD_BF16, { M, K }),
grp ? T(d_s, RAD_F32, { M, SK }) : T(d_s, RAD_F32, { M }),
T(d_y, RAD_BF16, { M, K }),
res ? T(d_p, RAD_BF16, { K }) : T(nullptr, RAD_BF16, {}),
scal ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) },
pn);
@@ -28893,11 +28934,11 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
}
std::vector<uint16_t> want_r((size_t)(M * K)), want_y((size_t)(M * K));
std::vector<uint8_t> want_q((size_t)(M * K));
std::vector<float> want_s((size_t)M);
std::vector<float> want_s((size_t)(M * SK));
st_memcpy(want_r.data(), d_r, xb, hipMemcpyDeviceToHost);
st_memcpy(want_y.data(), d_y, xb, hipMemcpyDeviceToHost);
st_memcpy(want_q.data(), d_q, (size_t)(M * K), hipMemcpyDeviceToHost);
st_memcpy(want_s.data(), d_s, (size_t)M * 4, hipMemcpyDeviceToHost);
st_memcpy(want_s.data(), d_s, (size_t)(M * SK) * 4, hipMemcpyDeviceToHost);
std::vector<ArQ8> t((size_t)world);
std::vector<std::thread> th;
@@ -28907,6 +28948,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
x.M = M; x.K = K; x.res = res; x.scal = scal; x.gated = scal;
x.tail = sh.tail;
x.sp = sh.sp;
x.grp = grp; x.alias = alias;
x.r_in = &hr; x.w = &hw; x.wp = &hp; x.sc = hs;
x.x_in = hx[(size_t)r];
th.emplace_back(ar_q8_worker, &x);
@@ -28945,13 +28987,14 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
const int64_t na = base + (x.rank < rem ? 1 : 0);
for (int64_t i = 0; i < M * K; ++i) {
const int64_t row = i / K;
if (!sh.sp) bx += x.x_out[(size_t)i] != xsum[(size_t)i];
/* with out_bf16 over x, x ends holding the norm output */
if (!sh.sp) bx += x.x_out[(size_t)i] != (alias ? want_y : xsum)[(size_t)i];
if (res && (sh.sp != 1 || (row >= a && row < a + na)))
br += x.r_out[(size_t)i] != want_r[(size_t)i];
if (!sh.sp) by += x.y_out[(size_t)i] != want_y[(size_t)i];
bq += x.q_out[(size_t)i] != want_q[(size_t)i];
}
for (int64_t i = 0; i < M; ++i)
for (int64_t i = 0; i < M * SK; ++i)
bs += std::memcmp(&x.s_out[(size_t)i], &want_s[(size_t)i], 4) != 0;
}
for (int64_t i = 0; i < M * K; ++i) nz += want_q[(size_t)i] != 0;
@@ -32545,6 +32588,10 @@ static void device_phase(const Plugin& pl) {
if (!g_case) std::printf("\ngelu_mul_quant_i8, against the pair it replaces\n");
gelu_mul_quant_i8_numeric(pl);
}
if (sel("gelu_mul_quant_i8g")) {
if (!g_case) std::printf("\ngelu_mul_quant_i8g, against the pair it replaces\n");
gelu_mul_quant_i8_numeric(pl, true);
}
if (sel("qkv_norm_rope_bf16") || sel("qkv_norm_rope_kv_store_fp8") ||
sel("qkv_norm_rope_kv_store_bf16") || sel("qkv_norm_rope_kv_store_h128_bf16")) {
if (!g_case) std::printf("\nqkv_norm_rope, and with kv_store folded in, against the ops it "
@@ -32555,6 +32602,10 @@ static void device_phase(const Plugin& pl) {
if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n");
rmsnorm_quant_i8_numeric(pl);
}
if (sel("rmsnorm_quant_i8g")) {
if (!g_case) std::printf("\nrmsnorm_quant_i8g, against the chain it replaces\n");
rmsnorm_quant_i8_numeric(pl, true);
}
if (sel("add_rmsnorm_bf16")) {
if (!g_case) std::printf("\nadd_rmsnorm, against add then rmsnorm\n");
add_rmsnorm_numeric(pl);
@@ -32669,7 +32720,8 @@ static void device_phase(const Plugin& pl) {
* they need, on a box with fewer cards. */
/* The junction's fused all-reduce at two and four ranks, and their host twins. */
for (const char* n : { "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8_host",
"ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8_4rank_host" }) {
"ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8_4rank_host",
"ar_rmsnorm_quant_i8g", "ar_rmsnorm_quant_i8g_host" }) {
if (!sel(n)) continue;
if (!g_case) std::printf("\ncross-rank, fused with the sandwich-norm junction\n");
std::printf(" %s\n", n);