ops: givens_quant_act_fp8; gemm_nt_q pb1/pb2 for activation copies per weight part

libref implements both (and is the oracle); libavx refuses a call that names a part.
This commit is contained in:
Malic Zilyas committed 2026-10-08 23:35:43 +02:00
1 parent 3402acf82d
commit 1213c05cd8
9 files changed
+329 -5

No files matched your search

+47
View File
@@ -17,6 +17,7 @@
* thousands in every GEMM a transformer issues. Each thread owns whole output elements, so the
* summation order does not depend on the thread count.
*/
#include <algorithm>
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
@@ -253,6 +254,52 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
/* PARTS (`pb1`, `pb2`): the weight's rows are [0, pb1), [pb1, pb2) and [pb2, N), each against
* its own copy of the activation -- a fused projection whose pieces were rotated separately
* (ParoQuant). The copies sit side by side in a row of `a`, so `a` is [M, parts * K] and its
* scale [M, parts * K / 128]; a part is the plain product over its rows, which is how it is
* computed. 0 leaves a bound out: no `pb1` is one part, no `pb2` ends the second at N. */
const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0);
if (pb1 > 0 || pb2 > 0) {
if (bias_operand || B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED;
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t bound[4] = { 0, e1, e2, N };
const int64_t acols = A->shape[A->rank - 1];
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
if (acols != parts * K || (e1 % 16) || (e2 % 16)) return RAD_E_SHAPE;
const bool sa_row = as_ && as_->data && as_->rank >= 2;
if (!sa_row) return RAD_E_INVAL;
const int64_t sa_cols = as_->shape[as_->rank - 1];
if (sa_cols % parts) return RAD_E_SHAPE;
const int64_t sa_part = sa_cols / parts; /* K / 128 */
for (int p = 0; p < 3; ++p) {
const int64_t n0 = bound[p], n1 = bound[p + 1];
if (n1 <= n0) continue;
RadTensor Ap = *A, Sp = *as_, Bp = *B, Bsp = *bs_, Yp = *Y;
Ap.data = (uint8_t*)A->data + rad_dtype_bytes(A->dtype, p * K);
Ap.rank = 2; Ap.shape[0] = M; Ap.shape[1] = K;
Ap.stride[0] = row_stride(A, acols); Ap.stride[1] = 1;
Sp.data = (uint8_t*)as_->data + rad_dtype_bytes(as_->dtype, p * sa_part);
Sp.shape[Sp.rank - 1] = sa_part;
Bp.data = (uint8_t*)B->data + rad_dtype_bytes(B->dtype, n0 * K);
Bp.rank = 2; Bp.shape[0] = n1 - n0; Bp.shape[1] = K; Bp.stride[0] = K; Bp.stride[1] = 1;
const int64_t bs_cols = bs_->shape[bs_->rank - 1];
Bsp.data = (uint8_t*)bs_->data + rad_dtype_bytes(bs_->dtype, n0 * bs_cols);
Bsp.rank = 2; Bsp.shape[0] = n1 - n0; Bsp.shape[1] = bs_cols;
Bsp.stride[0] = bs_cols; Bsp.stride[1] = 1;
const int64_t ys = row_stride(Y, N);
Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0);
Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = 1;
Scales SAp = make_scales(&Sp, M, K, false), SBp = make_scales(&Bsp, n1 - n0, K, true);
const Mat map_ = as_mat(&Ap, M, K), mbp = as_mat(&Bp, n1 - n0, K);
QuantFn fn = pick_quant(Ap.dtype, Bp.dtype);
if (fn) fn(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f);
else gemm_quant_generic(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f);
}
return RAD_OK;
}
const bool mx = B->dtype == RAD_FP4E2M1;
Scales SA = make_scales(as_, M, K, false);
Scales SB = make_scales(bs_, N, K, mx);
+2
View File
@@ -100,6 +100,7 @@ int ref_quant_act_i8 (const RadArgs*, RadStream);
int ref_had_quant_act_i8 (const RadArgs*, RadStream);
int ref_quant_act_fp8 (const RadArgs*, RadStream);
int ref_had_quant_act_fp8 (const RadArgs*, RadStream);
int ref_givens_quant_act_fp8(const RadArgs*, RadStream);
int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
int ref_gated_quant_fp8 (const RadArgs*, RadStream);
int ref_gemm_nt_q_gated (const RadArgs*, RadStream);
@@ -228,6 +229,7 @@ REF_SHAPE_FN(ref_quant_act_i8);
REF_SHAPE_FN(ref_had_quant_act_i8);
REF_SHAPE_FN(ref_quant_act_fp8);
REF_SHAPE_FN(ref_had_quant_act_fp8);
REF_SHAPE_FN(ref_givens_quant_act_fp8);
REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
REF_SHAPE_FN(ref_gated_quant_fp8);
REF_SHAPE_FN(ref_gemm_nt_q_gated);
+76
View File
@@ -410,6 +410,82 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------- givens_quant_act_fp8 */
/* ParoQuant's activation side: every row scaled by its channel factors, rotated by `stages`
* rounds of disjoint Givens pairs, then the same symmetric block-scaled E4M3 quantiser. A weight
* stored as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens") meets the activation
* x . D^-1 . G_1 ... G_S, because <v, x D^-1 G_1..G_S> = <w, x> and each G is orthogonal.
*
* PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated
* copies, written side by side: q is [rows, parts * n] and scale [rows, parts * n/group], part p at
* columns [p*n, (p+1)*n). The tables stack the parts: pairs and angle `stages` rows each, scale one
* row, per part. A part's pairs address columns of the row, and a pair must stay inside one scale
* group (the checkpoint's are within groups of 128): the quantiser reads each group's rotated
* values after the stages and the device kernel rotates a group at a time.
*
* The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each
* stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32, then amax/448 per group. Not
* bit-identical to the device on the angle: cos and sin of an f32 differ by an ulp between libm
* and the GPU's. */
int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) {
if (!have(a, 6)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3];
const RadTensor *q = &a->t[4], *s = &a->t[5];
const int64_t n = p_int(a, "n", 0), S = p_int(a, "stages", 0), P = p_int(a, "parts", 1);
int64_t g = p_int(a, "group", 0);
if (n <= 0 || S <= 0 || P <= 0 || (n & 1)) return RAD_E_SHAPE;
if (g <= 0 || g > n || n % g != 0) return RAD_E_SHAPE;
if (numel(pr) < P * S * n || numel(an) < P * S * (n / 2) || numel(sc) < P * n) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
const int64_t ngrp = n / g;
if (rows <= 0 || numel(q) < rows * P * n || numel(s) < rows * P * ngrp) return RAD_E_SHAPE;
// validated before the loop, because an OpenMP body cannot return
for (int64_t i = 0; i < P * S * n; ++i) {
const int64_t c = ld_int(pr->dtype, pr->data, i);
if (c < 0 || c >= n) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> buf((size_t)n);
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
const int64_t xs = laststride(x), qs = laststride(q);
for (int64_t p = 0; p < P; ++p) {
for (int64_t k = 0; k < n; ++k) buf[(size_t)k] = ldt(x, xb + k * xs) / ldt(sc, p * n + k);
for (int64_t st = 0; st < S; ++st) {
const int64_t t0 = (p * S + st) * n, a0 = (p * S + st) * (n / 2);
for (int64_t j = 0; j < n / 2; ++j) {
const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j);
const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1);
const float th = ldt(an, a0 + j), c = std::cos(th), sn = std::sin(th);
const float va = buf[(size_t)ia], vb = buf[(size_t)ib];
buf[(size_t)ia] = va * c + vb * sn;
buf[(size_t)ib] = vb * c - va * sn;
}
}
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g;
float amax = 0.0f;
for (int64_t i = 0; i < g; ++i) {
const float m = std::fabs(buf[(size_t)(k0 + i)]);
if (m > amax) amax = m;
}
const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / scl;
for (int64_t i = 0; i < g; ++i) {
float v = buf[(size_t)(k0 + i)] * inv;
if (v > 448.0f) v = 448.0f;
if (v < -448.0f) v = -448.0f;
st_dt(q->dtype, q->data, qb + (p * n + k0 + i) * qs, v);
}
stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl);
}
}
}
return RAD_OK;
}
/* ---------------------------------------------------------------- the Gram accumulator
*
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or
+25 -2
View File
@@ -201,6 +201,13 @@ static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") };
/* No `asum`: that output exists for the asymmetric integer grids and an fp8 grid is symmetric by
* construction (libr4d/r4d_rows.cpp says the same). */
static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") };
/* ParoQuant's activation quantiser: a rotation per part in front of quant_act_fp8's. The three
* tables are the "givens" encoding's (abi/rad_encoding.h) and are WEIGHT operands, so they are
* resolved, moved and placed with the weight they belong to. */
static const RadParamSpec pGivensQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
P_INT("stages"), P_INT("parts") };
static const RadOperandSpec oGivensQuant[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"),
OUT("q"), OUT("scale") };
/* ---- the fp8 fusions ----------------------------------------------------------------------
* A fused op's operands are the unfused pair's minus the tensor between them, and `out_bf16`
@@ -264,7 +271,10 @@ static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD
OUT("y") };
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype") };
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") };
/* The bias form has no parts: a fused projection rotated apart is the plain product's. */
static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype") };
/* `a_sum` and `b_ref` are libr4d's, appended AFTER `y` so docs/OPS.md's list stays a positional
* prefix: the asymmetric 4-bit and 2-bit grids subtract the activation's per-group code sums, and
* mxfp4 folds a per-output-row reference exponent. Neither is expressible as a weight aux stream,
@@ -790,6 +800,15 @@ static const RadOpSchema kSchemas[] = {
"previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank "
"bigram. Serial in l by construction -- the predecessor is not known until the previous step "
"has been decided." },
{ "givens_quant_act_fp8", ARR(pGivensQuant), ARR(oGivensQuant),
"ParoQuant's activation quantiser: x is divided by the channel scale `rscale`, rotated by "
"`stages` rounds of disjoint Givens pairs (a' = a cos t + b sin t, b' = b cos t - a sin t, pairs "
"as column indices of the row, each inside one scale group), then quantised as quant_act_fp8 "
"does: scale = amax / 448 per `group`. `parts` rotated copies are written side by side -- q is "
"[M, parts * n], scale [M, parts * n / group] -- part p from table rows [p * stages, (p + 1) * "
"stages) of `pairs` and `angle` and row p of `rscale`: a fused projection's pieces were each "
"rotated on their own. Only a weight stored with the \"givens\" transform reads the result; "
"it is NOT quant_act_fp8's output in either direction." },
{ "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8),
"A Walsh-Hadamard rotation of width `group` along n, then symmetric E4M3 per group: scale = "
"amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation "
@@ -831,7 +850,7 @@ static const RadOpSchema kSchemas[] = {
"gemm_nt with quantised operands. The group sub-sum is accumulated from the raw codes and "
"scaled once per group, which is what an int8 or fp8 WMMA kernel does. Scale streams are "
"[rows, groups] or [rows]; an mxfp4 weight's u8 scale stream is read as OCP e8m0." },
{ "gemm_nt_q_bias", ARR(pGemmQ), ARR(oGemmQBias), "gemm_nt_q with a per-column bias." },
{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "gemm_nt_q with a per-column bias." },
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
"Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per "
@@ -1152,6 +1171,10 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
SIMPLE("ref_dflash_select", "dflash_select", "draft",
"DFlash2's greedy walk over the candidate lattice",
"i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select),
SIMPLE("ref_givens_quant_act_fp8", "givens_quant_act_fp8", "quant",
"channel scale and Givens rotations per part, then the block-scaled E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale per group; int32 pairs, f32 angles and channel scales",
ref_givens_quant_act_fp8),
SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant",
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
+8
View File
@@ -828,6 +828,14 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("gram_accum", operand, out);
}
/* DECLINED, on purpose: `pairs` must be a pairing of each group's columns (every column once a
* stage, the partner inside the group), and a described operand can only be drawn, not constructed
* -- an index draw has repeats, and a Givens stage over a repeated column is not a rotation. A case
* built from one would compare two implementations of nothing. r4d_selftest builds real pairings. */
int ref_givens_quant_act_fp8_shape(const RadParam*, int, int, RadOpdDesc*) {
return RAD_E_UNSUPPORTED;
}
int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);