diff --git a/docs/OPS.md b/docs/OPS.md index 28d74441..31cfd85a 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -362,10 +362,33 @@ spelling of `act`, not the vocabulary's. |---|---|---| | `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | +| `givens_quant_act_fp8` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +### `givens_quant_act_fp8`: ParoQuant's rotated activation + +A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: the +channel scale `D` and `S` stages of disjoint pairwise rotations were applied to each row BEFORE it +was quantised (ParoQuant, z-lab), so the product the GEMM contracts is `` with +`x' = x . D^-1 . G_1 ... G_S` -- the activation takes the same rotation, forward, once a token. +`givens_quant_act_fp8` is that: `x / rscale`, then for each stage `a' = a cos t + b sin t, +b' = b cos t - a sin t` over its pairs, then `quant_act_fp8`'s quantiser (scale `amax / 448` per +`group` columns). The pairs are column indices of the row and each pair lies inside ONE scale group +(ParoQuant's are within groups of 128), so the kernel rotates a group at a time and the quantiser +sees the rotated group. The consumer is the plain `gemm_nt_q` at `mxfp4a8`; nothing in the weight's +codes or exponents changed. + +A fused projection (gate|up, qkv|z) was rotated PER CHECKPOINT TENSOR, so it has `parts` rotated +copies of the activation, written side by side -- `q` is `[M, parts * n]`, `scale` +`[M, parts * n / group]` -- and `pairs` and `angle` stack the parts' `stages` rows each, `rscale` +one row a part. `gemm_nt_q` then takes `pb1` and `pb2`, the row bounds of the weight's parts: its +rows `[0, pb1)`, `[pb1, pb2)` and `[pb2, N)` meet copy 0, 1 and 2, and `a`/`a_scale` are the wide +planes. `pb1` absent is one part; `pb2` absent ends the second part at `N`. Only the `mxfp4a8` rows +read them, and the host rows that do not (`libavx`) refuse a call that names one rather than +contract against the wrong copy. + ### The int8 and gated fp8 fusions — device-only | op | params | operands | @@ -410,7 +433,7 @@ waiting on the mover's event — a read of weight bytes that may not have arrive |---|---|---| | `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | -| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | +| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | `nt` is A row-major `[M,K]` times B **transposed** `[N,K]`, giving `[M,N]` — the layout every diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index ca9855ad..0969d2db 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -755,6 +755,10 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const RadTensor* bs_ = rad_arg_in(a, 3); const RadTensor* bias = bias_operand ? rad_arg_in(a, 4) : nullptr; + /* `pb1`/`pb2` split the weight's rows into parts that meet separate copies of the activation + * (ParoQuant); this driver reads one. Refused rather than computed against the wrong copy. */ + if (p_int(a, "pb1", 0) || p_int(a, "pb2", 0)) return RAD_E_UNSUPPORTED; + const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 96137405..03cef4bf 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -210,6 +210,8 @@ 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_INTO("pb1"), P_INTO("pb2") }; +static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"), OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") }; @@ -567,7 +569,7 @@ static const RadOpSchema kSchemas[] = { { "gemm_nt_q", ARR(pGemmQ), ARR(oGemmQ), "C = A B^T with group-scaled quantised operands. `a_sum` and `b_ref` are libr4d's asymmetric and " "mxfp4 forms and are ignored here, as they are in libref." }, -{ "gemm_nt_q_bias", ARR(pGemmQ), ARR(oGemmQBias), "quantised C = A B^T + bias." }, +{ "gemm_nt_q_bias", ARR(pGemmQBias), ARR(oGemmQBias), "quantised C = A B^T + bias." }, { "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated), "gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for " "byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." }, diff --git a/libref/ref_gemm.cpp b/libref/ref_gemm.cpp index 2c0c66da..bf642575 100644 --- a/libref/ref_gemm.cpp +++ b/libref/ref_gemm.cpp @@ -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 #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(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(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); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 276f0209..1c91d3eb 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -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); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index f01559b0..666126f9 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -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 = 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 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 diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index abc3ba3c..17b4d554 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -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", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 684aa57a..f06563bb 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -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); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index ec553ff0..40cad408 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,8 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "had_quant_act_i8", "gram_accum", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "had_quant_act_i8", + "gram_accum", /* The fused fp8 forms. A host run needs EVERY op covered, so these are what stands * between a host-backend run and "site 'host' is unavailable for this band". */ "rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select", @@ -1456,6 +1457,144 @@ TEST(op_gemm_nt_q) { CHECK_EQ(y3.at(1), (3 * 2.0f + 4 * 4.0f) * 1.0f); } +/* A weight whose row PARTS meet their own copy of the activation: parts = 2 rows [0, 16) and + * [16, 32) over K = 128, the copies side by side in one row of `a`. The parted product must be the + * plain product of each part's rows against its own copy -- computed here as two plain calls. */ +TEST(op_gemm_nt_q_parts_read_their_own_activation_copy) { + const int64_t M = 3, N = 32, K = 128, P = 2; + uint32_t rng = 7; + auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 9; }; + T a2(RAD_F8E4M3, {M, P * K}); + std::vector av((size_t)(M * P * K)); + for (auto& v : av) v = (float)((int)(nxt() % 15) - 7) * 0.25f; + a2.f(av); + T as2(RAD_F32, {M, P}); + std::vector asv((size_t)(M * P)); + for (auto& v : asv) v = 0.01f * (float)(1 + nxt() % 9); + as2.f(asv); + T b_(RAD_FP4E2M1, {N, K}); + for (int64_t i = 0; i < N * K / 2; ++i) b_.mem[(size_t)i] = (uint8_t)nxt(); + T bs(RAD_U8, {N, K / 32}); + for (int64_t i = 0; i < N * K / 32; ++i) bs.mem[(size_t)i] = (uint8_t)(124 + nxt() % 5); + + T y(RAD_BF16, {M, N}); + A a; a.t(a2).t(as2).t(b_).t(bs).t(y).tnull().tnull() + .i("M", M).i("N", N).i("K", K).i("group", 32).s("dtype", "mxfp4a8").i("pb1", 16); + CHECK_OK(run("gemm_nt_q", a)); + + for (int64_t p = 0; p < P; ++p) { + T ap(RAD_F8E4M3, {M, K}), asp(RAD_F32, {M, 1}); + std::vector v1((size_t)(M * K)), v2((size_t)M); + for (int64_t m = 0; m < M; ++m) { + for (int64_t k = 0; k < K; ++k) v1[(size_t)(m * K + k)] = av[(size_t)(m * P * K + p * K + k)]; + v2[(size_t)m] = asv[(size_t)(m * P + p)]; + } + ap.f(v1); + asp.f(v2); + T bp(RAD_FP4E2M1, {N / P, K}), bsp(RAD_U8, {N / P, K / 32}); + std::memcpy(bp.mem.data(), b_.mem.data() + p * (N / P) * K / 2, (size_t)((N / P) * K / 2)); + std::memcpy(bsp.mem.data(), bs.mem.data() + p * (N / P) * K / 32, (size_t)((N / P) * K / 32)); + T yp(RAD_BF16, {M, N / P}); + A c; c.t(ap).t(asp).t(bp).t(bsp).t(yp).tnull().tnull() + .i("M", M).i("N", N / P).i("K", K).i("group", 32).s("dtype", "mxfp4a8"); + CHECK_OK(run("gemm_nt_q", c)); + int bad = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N / P; ++n) + if (y.at(m * N + p * (N / P) + n) != yp.at(m * (N / P) + n)) ++bad; + CHECK_EQ(bad, 0); + } +} + +/* ParoQuant's activation quantiser. With zero angles and unit channel scales it IS quant_act_fp8; + * with real rotations the dequantised row is the rotated row to within the fp8 grid, and the + * rotation preserves the row's norm -- checked per part, against a double-precision rotation. */ +TEST(op_givens_quant_act_fp8) { + const int64_t M = 3, n = 256, S = 3, P = 2, G = 128; + uint32_t rng = 99; + auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; }; + auto frand = [&](float lo, float hi) { return lo + (hi - lo) * (float)(nxt() % 10000) / 10000.0f; }; + T x(RAD_BF16, {M, n}); + std::vector xv((size_t)(M * n)); + for (auto& v : xv) v = frand(-3.0f, 3.0f); + x.f(xv); + for (int64_t m = 0; m < M; ++m) xv[(size_t)(m * n + 7)] = 0; // a zero in the mix + // a pairing of each group of 128 per stage per part + T pr(RAD_I32, {P * S, n}), an(RAD_F32, {P * S, n / 2}), rs(RAD_F32, {P, n}); + for (int64_t ps = 0; ps < P * S; ++ps) + for (int64_t g = 0; g < n / G; ++g) { + std::vector perm((size_t)G); + for (int i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)(g * G + i); + for (int i = (int)G - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[nxt() % (i + 1)]); + for (int i = 0; i < G; ++i) st_int(RAD_I32, pr.t.data, ps * n + g * G + i, perm[(size_t)i]); + } + std::vector av((size_t)(P * S * n / 2)), sv((size_t)(P * n)); + for (auto& v : av) v = frand(-3.0f, 3.0f); + for (auto& v : sv) v = frand(0.5f, 2.0f); + an.f(av); + rs.f(sv); + + T q(RAD_F8E4M3, {M, P * n}), s(RAD_F32, {M, P * n / G}); + A a; a.t(x).t(pr).t(an).t(rs).t(q).t(s) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); + CHECK_OK(run("givens_quant_act_fp8", a)); + double worst = 0; + int bad_norm = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t p = 0; p < P; ++p) { + std::vector b((size_t)n); + double n0 = 0; + for (int64_t k = 0; k < n; ++k) { + b[(size_t)k] = (double)x.at(m * n + k) / (double)sv[(size_t)(p * n + k)]; + n0 += b[(size_t)k] * b[(size_t)k]; + } + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < n / 2; ++j) { + const int64_t ia = pr.iat((p * S + st) * n + 2 * j), ib = pr.iat((p * S + st) * n + 2 * j + 1); + const double t = av[(size_t)((p * S + st) * (n / 2) + j)], c = std::cos(t), sn = std::sin(t); + const double va = b[(size_t)ia], vb = b[(size_t)ib]; + b[(size_t)ia] = va * c + vb * sn; + b[(size_t)ib] = vb * c - va * sn; + } + double n1 = 0; + for (int64_t k = 0; k < n; ++k) n1 += b[(size_t)k] * b[(size_t)k]; + if (std::fabs(n1 - n0) > 1e-9 * n0) ++bad_norm; + for (int64_t g = 0; g < n / G; ++g) { + double amax = 0; + for (int64_t i = 0; i < G; ++i) amax = std::max(amax, std::fabs(b[(size_t)(g * G + i)])); + const double sc = s.at(m * (P * n / G) + p * (n / G) + g); + CHECK(std::fabs(sc - amax / 448.0) < 1e-5 * amax / 448.0 + 1e-12); + for (int64_t i = 0; i < G; ++i) { + const double deq = (double)q.at(m * P * n + p * n + g * G + i) * sc; + worst = std::max(worst, std::fabs(deq - b[(size_t)(g * G + i)]) / amax); + } + } + } + CHECK_EQ(bad_norm, 0); + CHECK(worst < 0.04); // half an e4m3 step at the top of the range is 1/16 of 1/2 + + // zero angles, unit scales: exactly quant_act_fp8 + T an0(RAD_F32, {P * S, n / 2}), rs1(RAD_F32, {P, n}); + std::vector ones((size_t)(P * n), 1.0f); + rs1.f(ones); + T q1(RAD_F8E4M3, {M, P * n}), s1(RAD_F32, {M, P * n / G}); + A b; b.t(x).t(pr).t(an0).t(rs1).t(q1).t(s1) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("stages", S).i("parts", P); + CHECK_OK(run("givens_quant_act_fp8", b)); + T q2(RAD_F8E4M3, {M, n}), s2(RAD_F32, {M, n / G}); + A c; c.t(x).t(q2).t(s2).i("M", M).i("n", n).i("group", G).s("dtype", "bf16"); + CHECK_OK(run("quant_act_fp8", c)); + int diff = 0; + for (int64_t m = 0; m < M; ++m) + for (int64_t p = 0; p < P; ++p) { + for (int64_t k = 0; k < n; ++k) + if (q1.mem[(size_t)(m * P * n + p * n + k)] != q2.mem[(size_t)(m * n + k)]) ++diff; + for (int64_t g = 0; g < n / G; ++g) + if (s1.at(m * (P * n / G) + p * (n / G) + g) != s2.at(m * (n / G) + g)) ++diff; + } + CHECK_EQ(diff, 0); +} + /* A BLOCK GRID WHOSE LAST BLOCK IS PARTIAL, on both axes. K = 300 at 128 is three scales over 128, * 128 and 44 columns; N = 129 is two row blocks, the second of one row, and N = 300 is three. The * expected value of every output is written out from that definition: with every code 1, output