diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index eaffb755..2ae94681 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -692,8 +692,8 @@ struct LinearFP8 { bool mx = false; rad_weight wref = 0; /* ...ROTATED (ParoQuant), a variant of `mx`: the same GEMM over an activation that - * `givens_quant_act_fp8` made from the input's bf16 plane -- the channel scale, the Givens - * stages and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection + * `givens_dense_quant` made from the input's bf16 plane -- the channel scale, the rotation (a + * dense per-group matrix) and the E4M3 quantiser in one pass, once for each rotated PART of a fused projection * (gate|up, qkv|z: each piece was rotated on its own) -- into this linear's own code and * scale planes, `parts` copies side by side. The tables are views of the weight's own planes. * The GEMM takes the parts' row bounds as `pb1`/`pb2` and meets copy p with part p's rows. */ diff --git a/data/recipes/q38-27b-paro-mxfp4-df2.recipe b/data/recipes/q38-27b-paro-mxfp4-df2.recipe index 2059d764..bf017745 100644 --- a/data/recipes/q38-27b-paro-mxfp4-df2.recipe +++ b/data/recipes/q38-27b-paro-mxfp4-df2.recipe @@ -10,7 +10,7 @@ # projection the Givens pairs and angles of 8 stages inside groups of 128 columns, and the channel # scales. A fused gate|up or qkv|z keeps one set of tables a checkpoint tensor (parts). rad-convert # writes them as planes of the weight; the GEMM is the plain MXFP4 one, and the activation is -# rotated in front of it (givens_quant_act_fp8) -- nothing is re-quantised, so the weights are the +# rotated in front of it (givens_dense_quant) -- nothing is re-quantised, so the weights are the # release's to the bit. # # What the checkpoint does NOT ship in a form the architecture declares gets a rule. The release is diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 66e2126a..3734a186 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -350,7 +350,7 @@ by weight, so their quantised linears need no recipe rule: | `quantization_config` | read as | | |---|---|---| | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) | -| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_quant_act_fp8` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | +| `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped); served by the rotating activation quantiser `givens_dense_quant` and the ordinary MXFP4 GEMM (docs/OPS.md). Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | | `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and the integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only; served by `givens_rotate` and `gemm_nt_q` at `w5a16` / `w4a16_asym` over an f16 activation (docs/OPS.md) | | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped | diff --git a/docs/OPS.md b/docs/OPS.md index 75e73d3c..cf285453 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -365,33 +365,35 @@ 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` | -| `givens_quant_act_i8g` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `q`, `scale` | | `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` | | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `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 +### `givens_dense_quant`: 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. +`givens_dense_quant` is that: `x / rscale`, then the rotation, then a block-scaled quantiser (`out` +names it: `fp8` is `quant_act_fp8`'s, scale `amax / 448`; `i8` is `quant_act_i8g`'s, scale +`amax / 127`, round to nearest) per `group` columns. The rotation is applied as ONE dense 128 x 128 +f16 matrix a (part, group) -- `tdense`, `[parts * n, 128]` -- the composition of the group's `stages` +rounds `a' = a cos t + b sin t, b' = b cos t - a sin t` over its pairs. A weight's `pairs` and `angle` +tables are column indices and angles of the row and each pair lies inside ONE scale group (ParoQuant's +are within groups of 128), so the matrices are the weight's own: rad-convert's layout hook for this op +composes them from the tables (`r4d_rad_layout_gdense`). The consumers are `gemm_nt_q` at `mxfp4a8` +(`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8); 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. `givens_rotate` is the same rotation with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). `givens_quant_act_i8g` is the rotation with `quant_act_i8g`'s quantiser (scale `amax / 127` per `group`), for `w5a8i8` / `w4a8i8_asym`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the +planes. `givens_rotate` is the same rotation done stage by stage, with no quantiser, `y` in its own dtype (f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`; their GEMM serves any `M` (rows past 64 run as chunks of 64). The int8 activation of `w5a8i8` / `w4a8i8_asym` is `givens_dense_quant`'s at `out` `i8`. `pb1` absent is one part; `pb2` absent ends the second part at `N`. The `mxfp4a8` rows and the asymmetric 4- and 5-bit rows (`w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`) read them, and the host rows that do not (`libavx`) refuse a call that names one rather than contract against the wrong copy. diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index c79bfa28..90e68a0b 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -126,7 +126,7 @@ set(R4D_UNITS "r4d_gemm_fp8a16_nt_m1|" "r4d_gemm_fp8a8|" "r4d_quant_act_fp8|" - "r4d_givens_quant_act_fp8|" + "r4d_givens_rotate|" "r4d_fused_quant_fp8|" "r4d_gram_accum_fp8|" "r4d_qsa_block_key_bf16|" diff --git a/libr4d/r4d_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip index b098f01e..ec0fdda2 100644 --- a/libr4d/r4d_gemm_wpa8i8_tiled.hip +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -3,7 +3,7 @@ // // dequant(Wq)[n][k] = scale[n][k/128] * (code[n][k] - zero[n][k/128]), code in 0..15 or 0..31 // -// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_quant_act_i8g) -- in +// -- ParoQuant's int4 (z-lab) and int5 once the activation has been rotated (givens_dense_quant) -- in // 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights // also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the // tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement: diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip index eb534220..9d0a3f04 100644 --- a/libr4d/r4d_givens_dense.hip +++ b/libr4d/r4d_givens_dense.hip @@ -2,7 +2,7 @@ // // The Givens stages of a 128-column group compose to one orthogonal 128 x 128 matrix T, so // y = T (x / D) is a small GEMM: out[m][j] = sum_i T[j][i] * (x[m][i] / D[i]). The sequential kernel -// (r4d_givens_quant_act_fp8.hip) does the same job in `stages` dependent LDS rounds a group and is +// (r4d_givens_rotate.hip) does the same job in `stages` dependent LDS rounds a group and is // latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which // is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the // int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip deleted file mode 100644 index 58208f4c..00000000 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ /dev/null @@ -1,239 +0,0 @@ -// ParoQuant's activation side: channel scale, Givens rotations, then the per-(row, 128-column) -// symmetric E4M3 quantiser of r4d_quant_act_fp8.hip. The weight it pairs with is stored as -// v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with -// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and -// the weight is read by the plain MXFP4 GEMM unchanged. -// -// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- -// that is how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) -// refuse one that does -- so a group is a closed system: its 128 values are rotated by S stages of 64 disjoint pairs and then quantised -// with ONE scale. A wave owns a group. The values sit in LDS (128 floats a wave, no barrier -// needed: a wave's LDS accesses are in order, and the pairs of a stage are disjoint so no two lanes -// touch one address), each lane takes two pairs a stage, and the absmax is a wave reduction. The -// quantiser after it is quant_act_fp8's, byte for byte. -// -// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated -// copies, side by side: q is [M, parts * K] and scale [M, parts * K/128]. A (part, group) pair is -// one unit of work, one wave's (a row is several blocks, grid.y). The tables stack the parts -// as the "givens" encoding does -- stages rows each of pairs and angle, one row of channel scales. -// -// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was -// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the -// reference (libref) divides in f32 too, so the two agree on this step exactly. -// -// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or -// two, which is also what libref's libm is. The rotation is a handful of FMAs on top of that; the -// quantiser's rounding to E4M3 then swallows nearly all of the difference, and rad-kbench-style -// comparisons against the reference allow one code of disagreement per element. -// -// givens_quant_act_i8g is the same producer with an int8 output (scale amax / 127, round to nearest) for -// the int8 prefill GEMMs: after the rotation a group is flat, and 127 uniform levels beat e4m3's three -// mantissa bits for nearly every element. -// -// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. - -#include "r4d.h" -#include "r4d_emit.h" -#include "r4d_fp8_args.h" -#include "r4d_fp8_wmma.h" -#include "r4d_q8.h" -#include - -namespace { - -constexpr uint32_t kWave = 32; -constexpr uint32_t kThreads = 256; -constexpr uint32_t kWaves = kThreads / kWave; -constexpr uint32_t kGroup = 128; -constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 - -// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is -// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS -// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency -// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. -constexpr uint32_t kPre = 8; - -__device__ __forceinline__ void wave_sync() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); - __builtin_amdgcn_wave_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); -} - -// One wave rotates and quantises one (part, group) of one row: grid.x is the row, and grid.y -// spreads a row's `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is -// several blocks and a decode step of a few rows still fills the part. A wave that has no group -// returns at once; nothing in the kernel is a block barrier. -// Rotate is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into -// `q` (read as a uint16 plane, y_ld elements a row) for a GEMM that reads a 16-bit activation. -// Fp8 and I8 are the two quantisers (r4d_q8.h: E4M3 with scale amax/448, int8 with amax/127). -enum class GvMode { Rotate, Fp8, I8 }; - -template -__global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( - const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, - const float* __restrict__ angle, const float* __restrict__ rscale, uint8_t* __restrict__ q, - float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, - uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { - constexpr bool I8 = MODE == GvMode::I8; - __shared__ float sbuf[kWaves][kGroup]; - const uint32_t row = blockIdx.x; - const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; - const uint32_t item = blockIdx.y * kWaves + wave; - if (item >= parts * nkb) return; - const uint32_t part = item / nkb, g = item % nkb; - const uint32_t c0 = g * kGroup; - const size_t xrow = (size_t)row * x_ld; - float* buf = sbuf[wave]; - - // channel scale: v = x / D, four consecutive columns a lane - { - const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u); - const uint32_t xc = c0 + lane * 4u; - const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x; - const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y; - const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z; - const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w; - *(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3); - } - - for (uint32_t st0 = 0; st0 < stages; st0 += kPre) { - const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre; - int2 ab[kPre][kPairsPerLane]; - float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane]; -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) { - const size_t trow = (size_t)part * stages + st0 + k; - const int32_t* pr = pairs + trow * K + c0; - const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u); -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) { - const uint32_t j = lane + u * kWave; - ab[k][u] = *(const int2*)(pr + 2u * j); - th[k][u] = an[j]; - } - } -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]); - wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS -#pragma unroll - for (uint32_t k = 0; k < kPre; ++k) - if (k < nst) { -#pragma unroll - for (uint32_t u = 0; u < kPairsPerLane; ++u) { - const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0; - const float va = buf[ia], vb = buf[ib]; - buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb); - buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va); - } - wave_sync(); - } - } - - const float4 r = *(const float4*)(buf + lane * 4u); - float v[4] = { r.x, r.y, r.z, r.w }; - if constexpr (MODE == GvMode::Rotate) { - // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an - // outlier finite instead of inf - union { __half h[4]; uint2 u; } o; -#pragma unroll - for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); - *(uint2*)((uint16_t*)q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = o.u; - return; - } - float m = 0.0f; -#pragma unroll - for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); - m = r4d_wave_max(m); - const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; - if (lane == 0) s[(size_t)row * s_ld + (size_t)part * nkb + g] = sc; - *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = - q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); -} - -} // namespace - -// x [M][K] bf16, `x_ld` elements a row (0 = K) -// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j -// angle [parts*stages][K/2] f32 -// rscale [parts][K] f32, the factor the stored row was multiplied by -// q [M][parts*K] E4M3 -// s [M][parts*K/128] f32 -static int givens_quant_launch(long x, long pairs, long angle, long rscale, long q, long s, int M, - int K, int parts, int stages, int x_ld, int q_ld, int s_ld, - const R4dSink& sk, GvMode mode = GvMode::Fp8) { - if (!x || !pairs || !angle || !rscale || !q || (mode != GvMode::Rotate && !s)) return -1; - if (M <= 0 || K <= 0 || parts <= 0 || stages <= 0) return -2; - if (K % (int)kGroup) return -3; // a rotation group cannot straddle the end of a row - if (!x_ld) x_ld = K; - const int nkb = K / (int)kGroup; - if (!q_ld) q_ld = parts * K; - if (!s_ld) s_ld = parts * nkb; - const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; -#define GV_EMIT(M_) R4D_EMIT(sk, (givens_quant_act_fp8_kernel), dim3((uint32_t)M, gy), dim3(kThreads), 0, \ - (const uint16_t*)x, (const int32_t*)pairs, (const float*)angle, (const float*)rscale, \ - (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, (uint32_t)parts, (uint32_t)stages, \ - (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) - const int rc = mode == GvMode::I8 ? GV_EMIT(GvMode::I8) - : mode == GvMode::Fp8 ? GV_EMIT(GvMode::Fp8) : GV_EMIT(GvMode::Rotate); -#undef GV_EMIT - if (rc != RAD_OK) return -4; - return (!sk.desc && hipGetLastError() != hipSuccess) ? -4 : 0; -} - -extern "C" int r4d_givens_quant_act_fp8_group(void) { return (int)kGroup; } - -// ============================================================== the plugin ABI entry point -enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Q = 4, GV_S = 5 }; - -static int givens_body(const RadArgs* a, const R4dSink& sk, GvMode mode) { - const bool quant = mode != GvMode::Rotate; - const RadTensor* x = r4d_opt(a, GV_X); - const RadTensor* pr = r4d_opt(a, GV_PAIRS); - const RadTensor* an = r4d_opt(a, GV_ANGLE); - const RadTensor* rs = r4d_opt(a, GV_RSCALE); - const RadTensor* q = r4d_opt(a, GV_Q); - const RadTensor* sc = quant ? r4d_opt(a, GV_S) : nullptr; - if (!x || !pr || !an || !rs || !q || (quant && !sc)) return R4D_NO(RAD_E_INVAL); - if (x->rank < 2 || q->rank != 2 || (quant && sc->rank != 2) || pr->rank != 2 || an->rank != 2 || - rs->rank != 2) return R4D_NO(RAD_E_SHAPE); - if (mode == GvMode::Rotate && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); - if (mode == GvMode::I8 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); - if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) - return R4D_NO(RAD_E_DTYPE); - // rows are dim 0 and everything after it is the row, as quant_act_fp8 reads them - const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); - const long long grp = (long long)kGroup, nkb = K / grp; - const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0); - if (r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) - return R4D_NO(RAD_E_SHAPE); - if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); - if (quant && (sc->shape[0] != M || sc->shape[1] != parts * nkb)) return R4D_NO(RAD_E_SHAPE); - // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles - if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); - if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); - if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); - if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(q->data, 4)) - return R4D_NO(RAD_E_ALIGN); - const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = quant ? r4d_row_pitch(sc) : 0; - if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); - const int e = givens_quant_launch(r4d_addr(x), r4d_addr(pr), r4d_addr(an), r4d_addr(rs), - r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)parts, - (int)stages, (int)xp, (int)qp, (int)sp, sk, mode); - return e == 0 ? RAD_OK : RAD_E_SHAPE; -} -static int rad_givens_quant_act_fp8_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::Fp8); -} -static int rad_givens_quant_act_i8g_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::I8); -} -static int rad_givens_rotate_body(const RadArgs* a, const R4dSink& sk) { - return givens_body(a, sk, GvMode::Rotate); -} -R4D_ENTRY(r4d_rad_givens_quant_act_fp8, rad_givens_quant_act_fp8_body) -R4D_ENTRY(r4d_rad_givens_rotate, rad_givens_rotate_body) -R4D_ENTRY(r4d_rad_givens_quant_act_i8g, rad_givens_quant_act_i8g_body) diff --git a/libr4d/r4d_givens_rotate.hip b/libr4d/r4d_givens_rotate.hip new file mode 100644 index 00000000..7266be9b --- /dev/null +++ b/libr4d/r4d_givens_rotate.hip @@ -0,0 +1,174 @@ +// ParoQuant's rotation, to f16: the channel scale and Givens stages applied to a bf16 activation, for the +// 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64 -- decode). The weight it pairs with is stored +// as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product with +// x' = x . D^-1 . G_1 ... G_S is : the rotation is the activation's to do, once a token, and the +// weight is read by the GEMM unchanged. The quantising form, for prefill-sized rows and for MXFP4, is +// r4d_givens_dense.hip. +// +// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- that is +// how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) refuse +// one that does -- so a group is a closed system: +// its 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group. The values sit in LDS +// (128 floats a wave, no barrier needed: a wave's LDS accesses are in order, and the pairs of a stage are +// disjoint so no two lanes touch one address) and each lane takes two pairs a stage. +// +// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated +// copies, side by side: y is [M, parts * K]. A (part, group) pair is one unit of work, one wave's (a row +// is several blocks, grid.y). The tables stack the parts as the "givens" encoding does -- stages rows each +// of pairs and angle, one row of channel scales. +// +// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was +// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the +// reference (libref) divides in f32 too, so the two agree on this step exactly. +// +// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or two, +// which is also what libref's libm is. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. + +#include "r4d.h" +#include "r4d_emit.h" +#include "r4d_fp8_args.h" +#include + +namespace { + +constexpr uint32_t kWave = 32; +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr uint32_t kGroup = 128; +constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2 + +// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is +// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS +// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency +// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages. +constexpr uint32_t kPre = 8; + +__device__ __forceinline__ void wave_sync() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); + __builtin_amdgcn_wave_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); +} + +// One wave rotates one (part, group) of one row: grid.x is the row, and grid.y spreads a row's +// `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is several blocks and a +// decode step of a few rows still fills the part. A wave that has no group returns at once; nothing in +// the kernel is a block barrier. The rotated row is written as f16 into `y`, y_ld elements a row. +__global__ __launch_bounds__(kThreads) void givens_rotate_kernel( + const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs, + const float* __restrict__ angle, const float* __restrict__ rscale, uint16_t* __restrict__ y, + uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, uint32_t x_ld, uint32_t y_ld) { + __shared__ float sbuf[kWaves][kGroup]; + const uint32_t row = blockIdx.x; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint32_t item = blockIdx.y * kWaves + wave; + if (item >= parts * nkb) return; + const uint32_t part = item / nkb, g = item % nkb; + const uint32_t c0 = g * kGroup; + const size_t xrow = (size_t)row * x_ld; + float* buf = sbuf[wave]; + + // channel scale: v = x / D, four consecutive columns a lane + { + const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u); + const uint32_t xc = c0 + lane * 4u; + const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x; + const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y; + const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z; + const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w; + *(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3); + } + + for (uint32_t st0 = 0; st0 < stages; st0 += kPre) { + const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre; + int2 ab[kPre][kPairsPerLane]; + float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane]; +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { + const size_t trow = (size_t)part * stages + st0 + k; + const int32_t* pr = pairs + trow * K + c0; + const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u); +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const uint32_t j = lane + u * kWave; + ab[k][u] = *(const int2*)(pr + 2u * j); + th[k][u] = an[j]; + } + } +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]); + wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS +#pragma unroll + for (uint32_t k = 0; k < kPre; ++k) + if (k < nst) { +#pragma unroll + for (uint32_t u = 0; u < kPairsPerLane; ++u) { + const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0; + const float va = buf[ia], vb = buf[ib]; + buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb); + buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va); + } + wave_sync(); + } + } + + const float4 r = *(const float4*)(buf + lane * 4u); + const float v[4] = { r.x, r.y, r.z, r.w }; + // f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an outlier + // finite instead of inf + union { __half h[4]; uint2 u; } o; +#pragma unroll + for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f)); + *(uint2*)(y + (size_t)row * y_ld + (size_t)part * K + c0 + lane * 4u) = o.u; +} + +} // namespace + +// x [M][K] bf16, `x_ld` elements a row (0 = K) +// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j +// angle [parts*stages][K/2] f32 +// rscale [parts][K] f32, the factor the stored row was multiplied by +// y [M][parts*K] f16 +enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 }; + +static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GV_X); + const RadTensor* pr = r4d_opt(a, GV_PAIRS); + const RadTensor* an = r4d_opt(a, GV_ANGLE); + const RadTensor* rs = r4d_opt(a, GV_RSCALE); + const RadTensor* y = r4d_opt(a, GV_Y); + if (!x || !pr || !an || !rs || !y) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || y->rank != 2 || pr->rank != 2 || an->rank != 2 || rs->rank != 2) + return R4D_NO(RAD_E_SHAPE); + if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32) + return R4D_NO(RAD_E_DTYPE); + // rows are dim 0 and everything after it is the row + const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); + const long long grp = (long long)kGroup, nkb = K / grp; + const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0); + if (M <= 0 || r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1) + return R4D_NO(RAD_E_SHAPE); + if (y->shape[0] != M || y->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); + // the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles + if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE); + if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 4)) + return R4D_NO(RAD_E_ALIGN); + const long long xp = r4d_row_pitch(x), yp = r4d_row_pitch(y); + if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves; + const int rc = R4D_EMIT(sk, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, + (const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data, + (const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb, + (uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K), (uint32_t)(yp ? yp : parts * K)); + if (rc != RAD_OK) return rc; + return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; +} +R4D_ENTRY(r4d_rad_givens_rotate, givens_rotate_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 02554bb3..e5b2fde4 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -901,7 +901,7 @@ namespace { /* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 -- * stored in the basis the "givens" transform names, with the rotation's tables beside them. The * GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the - * activation's (givens_quant_act_fp8), and the tables are separate weight operands of that op, so + * activation's (givens_dense_quant), and the tables are separate weight operands of that op, so * nothing here touches them. What is checked is that they are there and are the kind of * rotation the quantiser applies: a transform this library does not read would hand the kernel * codes that decode to other numbers. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index abc57929..8f7c33d2 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -327,10 +327,6 @@ int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_givens_rotate (const RadArgs*, RadStream); int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_givens_quant_act_fp8 (const RadArgs*, RadStream); -int r4d_rad_givens_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); -int r4d_rad_givens_quant_act_i8g (const RadArgs*, RadStream); -int r4d_rad_givens_quant_act_i8g_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 202bc1eb..e4d51e77 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1052,10 +1052,10 @@ static const RadOperandSpec oQuantActFp8[] = { { "scale", RAD_OPD_OUT, 0 }, }; -/* `givens_quant_act_fp8` is ParoQuant's activation side, and libref declared this schema first - * (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT operands; - * see libref/ref_quant.cpp for the contract and r4d_givens_quant_act_fp8.hip for the kernel. */ -static const RadParamSpec pGivensQuantAct[] = { +/* `givens_rotate` is ParoQuant's activation side for the 16-bit GEMMs, and libref declared this schema + * first (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT + * operands; see libref/ref_quant.cpp for the contract and r4d_givens_rotate.hip for the kernel. */ +static const RadParamSpec pGivensRotate[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, { "group", RAD_P_INT, RAD_REQUIRED }, @@ -1070,16 +1070,8 @@ static const RadOperandSpec oGivensRotate[] = { { "rscale", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; -static const RadOperandSpec oGivensQuantAct[] = { - { "x", RAD_OPD_IN, 0 }, - { "pairs", RAD_OPD_WEIGHT, 0 }, - { "angle", RAD_OPD_WEIGHT, 0 }, - { "rscale", RAD_OPD_WEIGHT, 0 }, - { "q", RAD_OPD_OUT, 0 }, - { "scale", RAD_OPD_OUT, 0 }, -}; -/* `givens_dense_quant` is givens_quant_act_fp8 with the rotation done by a dense per-group matrix on the +/* `givens_dense_quant` is ParoQuant's activation quantiser, the rotation done by a dense per-group matrix on the * matrix cores (r4d_givens_dense.hip). The matrices are the weight -- rad-convert composes them from the * givens tables (r4d_rad_layout_gdense) -- so its tables are `tdense` and the channel scale `rscale`. * `out` is the quantiser: "i8" (scale amax / 127) or "fp8" (E4M3, amax / 448), as q's dtype says. */ @@ -2352,31 +2344,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8, "quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored " "rotated, its scale carrying the residual factor of `group`."), - SCHEMA("givens_rotate", pGivensQuantAct, oGivensRotate, - "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of " + SCHEMA("givens_rotate", pGivensRotate, oGivensRotate, + "ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of " "Givens pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight " "whose GEMM reads a 16-bit activation. `group` is the width a pair stays inside."), - SCHEMA("givens_quant_act_fp8", pGivensQuantAct, oGivensQuantAct, - "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."), SCHEMA("givens_dense_quant", pGivensDense, oGivensDense, "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " - "givens_quant_act_i8g / _fp8 up to the f16 rounding of T."), - SCHEMA("givens_quant_act_i8g", pGivensQuantAct, oGivensQuantAct, - "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " - "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " - "prefill GEMMs of a weight stored with the \"givens\" transform."), + "the sequential rotation, up to the f16 rounding of T."), SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8, "the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with " "an expert weight stored at dtype w4a8h, which carries the matching rotation and the " @@ -5257,37 +5235,6 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr, r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe }, -/* ParoQuant's rotation and the quantiser in one pass, because the rotation changes the maximum the - * scale is taken over and so cannot be a separate launch ahead of quant_act_fp8 without writing - * and re-reading the rotated row. It exists for the MXFP4 weight stored rotated and for nothing - * else. */ -{ "givens_quant_act_fp8", "givens_quant_act_fp8", "quant", - "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric E4M3 " - "quantisation, once for each rotated part of a fused projection", - "n a multiple of 128 -- a rotation group cannot straddle the end of a row -- and group 128, " - "which is both the rotation group and the weight scale's activation block", - "bf16 in, E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale per (row, part, " - "128 columns); the tables are the weight's int32 pairs (checked at load to pair each group's own " - "columns), f32 angles and f32 channel scales", - RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_fp8, nullptr, r4d_rad_layout_givens_pairs, - r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, - r4d_rad_givens_quant_act_fp8_describe }, - -{ "givens_quant_act_i8g", "givens_quant_act_i8g", "quant", - "the channel scale, ParoQuant's Givens rotations, then per-(row, 128-column) symmetric int8 " - "quantisation, once for each rotated part of a fused projection", - "n a multiple of 128 and group 128, as givens_quant_act_fp8's", - "bf16 in, int8 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale of amax/127 per " - "(row, part, 128 columns); the tables are the weight's int32 pairs, f32 angles and f32 channel " - "scales", - RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cHadQuantActFp8), NOTUNE, - nullptr, nullptr, r4d_rad_givens_quant_act_i8g, nullptr, r4d_rad_layout_givens_pairs, - r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr, - r4d_rad_givens_quant_act_i8g_describe }, - { "givens_dense_quant", "givens_dense_quant", "quant", "ParoQuant's rotation as a dense 128 x 128 f16 matrix a (part, group) on the matrix cores, then " "per-(row, 128-column) symmetric quantisation to int8 or E4M3, once for each rotated part", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 4c46a3ef..e68f2084 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3776,8 +3776,7 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * the group's maximum, so 7% of it is a bound a wrong pair or a wrong angle cannot meet). */ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, bool rot_only = false, bool i8 = false, bool dense = false) { - const char* row = dense ? "givens_dense_quant" : rot_only ? "givens_rotate" - : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; + const char* row = dense ? "givens_dense_quant" : "givens_rotate"; if (!sel(row)) return; char nm[160]; std::snprintf(nm, sizeof nm, "%s %s numeric M=%lld K=%lld parts=%d stages=%d", row, @@ -13182,17 +13181,6 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 300, 6144, 2, 8, true); } - if (sel("givens_quant_act_i8g")) { - if (!g_case) std::printf("\nParoQuant's rotated activation, int8 output, against libm's rotation\n"); - givens_numeric(pl, 1, 128, 1, 8, false, true); - givens_numeric(pl, 3, 5120, 1, 8, false, true); - givens_numeric(pl, 5, 5120, 2, 8, false, true); - givens_numeric(pl, 64, 17408, 1, 8, false, true); - givens_numeric(pl, 300, 6144, 2, 8, false, true); - givens_numeric(pl, 2048, 5120, 1, 8, false, true); - givens_numeric(pl, 2048, 5120, 2, 8, false, true); - givens_numeric(pl, 2048, 17408, 1, 8, false, true); - } if (sel("givens_dense_quant")) { if (!g_case) std::printf("\nParoQuant's rotation as dense per-group matrices, int8 and E4M3 output, against libm's rotation\n"); for (int i8 = 0; i8 < 2; ++i8) { @@ -13203,18 +13191,11 @@ static void device_phase(const Plugin& pl) { givens_numeric(pl, 300, 6144, 2, 8, false, i8, true); givens_numeric(pl, 2048, 5120, 1, 8, false, i8, true); givens_numeric(pl, 2048, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 64, 17408, 1, 8, false, i8, true); givens_numeric(pl, 2048, 17408, 1, 8, false, i8, true); + givens_numeric(pl, 7, 5120, 3, 2, false, i8, true); } } - if (sel("givens_quant_act_fp8")) { - if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); - givens_numeric(pl, 1, 128, 1, 8); - givens_numeric(pl, 3, 5120, 1, 8); - givens_numeric(pl, 5, 5120, 2, 8); - givens_numeric(pl, 64, 17408, 1, 8); - givens_numeric(pl, 300, 6144, 2, 8); - givens_numeric(pl, 7, 5120, 3, 2); - } if (sel("gram_accum")) { if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n"); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 560f55b4..aaccbcb8 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -100,8 +100,6 @@ 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_givens_quant_act_i8g(const RadArgs*, RadStream); int ref_givens_dense_quant(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); @@ -232,8 +230,6 @@ 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_givens_quant_act_i8g); REF_SHAPE_FN(ref_givens_dense_quant); REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 897b4894..ddbd46b3 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -410,35 +410,31 @@ 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. +/* ------------------------------------------------------------- givens_rotate */ +/* ParoQuant's activation side: every row scaled by its channel factors and rotated by `stages` rounds of + * disjoint Givens pairs, written in y's dtype. 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. For a weight whose GEMM reads a 16-bit + * activation (w5a16); the quantising form is givens_dense_quant, over the composed matrices. * * 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. + * copies, written side by side: y is [rows, parts * n], 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 stay inside one group of `group` (the checkpoint's are within groups of 128). * * 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. */ -static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { - if (!have(a, quant ? 6 : 5)) 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 = quant ? &a->t[5] : nullptr; + * stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32. 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_rotate(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4]; 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); + const 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 || (quant && numel(s) < rows * P * ngrp)) return RAD_E_SHAPE; + if (rows <= 0 || numel(q) < rows * P * n) return RAD_E_SHAPE; // validated before the loop, because an OpenMP body cannot return for (int64_t i = 0; i < P * S * n; ++i) { @@ -464,38 +460,13 @@ static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { buf[(size_t)ib] = vb * c - va * sn; } } - if (!quant) { // givens_rotate: the rotated row, in q's dtype - for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); - continue; - } - 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 qmax = i8 ? 127.0f : 448.0f; - const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 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 > qmax) v = qmax; - if (v < -qmax) v = -qmax; - if (i8) v = std::nearbyint(v); - 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); - } + for (int64_t k = 0; k < n; ++k) st_dt(q->dtype, q->data, qb + (p * n + k) * qs, buf[(size_t)k]); } } return RAD_OK; } -int ref_givens_quant_act_fp8(const RadArgs* a, RadStream) { return givens_body(a, true); } -int ref_givens_quant_act_i8g(const RadArgs* a, RadStream) { return givens_body(a, true, true); } - -/* The same activation with the rotation applied as the dense matrix: y[j] = sum_i T[j][i] * x[i] / D[i] over +/* ParoQuant's activation quantiser: the rotation applied as the dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] over * each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128] * matrix a (part, group) -- what r4d_rad_relayout_gdense composes from the givens tables. */ int ref_givens_dense_quant(const RadArgs* a, RadStream) { @@ -541,9 +512,6 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) { return RAD_OK; } -/* The same channel scale and rotations with NO quantiser: y = the rotated row in y's dtype, `parts` - * copies side by side. For a weight whose GEMM reads a 16-bit activation (w5a16). */ -int ref_givens_rotate(const RadArgs* a, RadStream) { return givens_body(a, false); } /* ---------------------------------------------------------------- the Gram accumulator * diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 30430f8a..8a4fe796 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -201,10 +201,10 @@ 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 +/* ParoQuant's rotation: a rotation per part, to f16 for the 16-bit GEMMs. 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"), +static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("stages"), P_INT("parts") }; static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_INT("parts"), P_STR("out") }; @@ -212,8 +212,6 @@ static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rsc OUT("scale") }; static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"), OUT("y") }; -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` @@ -806,28 +804,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." }, { "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense), "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " "group) that its Givens stages compose to, then the block-scaled quantiser `out` names " "(\"i8\": scale amax / 127, round to nearest; \"fp8\": E4M3, amax / 448). q is [M, parts * n] " "and scale [M, parts * n / group]; tdense is [parts * n, 128]. The same activation as " - "givens_quant_act_i8g / _fp8 up to the f16 rounding of T." }, -{ "givens_quant_act_i8g", ARR(pGivensQuant), ARR(oGivensQuant), - "givens_quant_act_fp8 with an int8 output: the same channel scale and rotations, then " - "quant_act_i8g's quantiser (scale = amax / 127 per `group`, round to nearest). For the int8 " - "prefill GEMMs of a weight stored with the \"givens\" transform." }, -{ "givens_rotate", ARR(pGivensQuant), ARR(oGivensRotate), - "givens_quant_act_fp8 without the quantiser: y = x / rscale rotated by `stages` rounds of Givens " + "the sequential rotation, up to the f16 rounding of T." }, +{ "givens_rotate", ARR(pGivensRotate), ARR(oGivensRotate), + "ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of Givens " "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " "reads a 16-bit activation. `group` is the width a pair stays inside." }, { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), @@ -1195,18 +1180,10 @@ SIMPLE("ref_dflash_select", "dflash_select", "draft", SIMPLE("ref_givens_rotate", "givens_rotate", "quant", "channel scale and Givens rotations per part, in the output's dtype", "float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate), -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_givens_dense_quant", "givens_dense_quant", "quant", "the rotation as a dense per-group matrix, then the block-scaled int8 or E4M3 quantiser", "float in, int8 or fp8_e4m3 out, f32 scale per group; f16 matrices and f32 channel scales", ref_givens_dense_quant), -SIMPLE("ref_givens_quant_act_i8g", "givens_quant_act_i8g", "quant", - "channel scale and Givens rotations per part, then the block-scaled int8 quantiser", - "float in, int8 out, f32 scale per group; int32 pairs, f32 angles and channel scales", - ref_givens_quant_act_i8g), 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 f188cb1b..dc5a5112 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -832,20 +832,12 @@ int ref_gram_accum_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou * 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_givens_quant_act_i8g_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ -} - int ref_givens_dense_quant_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: see givens_quant_act_fp8 */ + return RAD_E_UNSUPPORTED; /* a composed rotation cannot be drawn: it is a weight, built from real pairings */ } int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { - return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ + return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: a described operand can only be drawn, and an index draw has repeats */ } int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 5ca8af2d..e7372111 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -261,7 +261,7 @@ TEST(op_vocabulary) { "embed_lookup_q", "cast", "scale_rows", "softmax", - "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "givens_dense_quant", "givens_rotate", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_dense_quant", "givens_rotate", "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". */ @@ -1506,10 +1506,13 @@ TEST(op_gemm_nt_q_parts_read_their_own_activation_copy) { } } -/* 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) { +/* ParoQuant's activation quantiser, the rotation as dense per-group matrices. T[j][i] of a (part, group) is + * the group's composed network applied to the unit vector e_i, built here in double from the same pairs and + * angles the device layout hook reads; with it the dequantised row is the rotated row to within the + * quantiser's grid (plus the f16 rounding of T), and the rotation preserves the row's norm -- both checked + * per part against a double-precision rotation. With T the identity and unit channel scales it IS + * quant_act_fp8, exactly. Run for both quantisers `out` names. */ +TEST(op_givens_dense_quant) { 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; }; @@ -1517,70 +1520,105 @@ TEST(op_givens_quant_act_fp8) { 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 + x.f(xv); // 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}); + std::vector pairs((size_t)(P * S * 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]); + for (int i = 0; i < G; ++i) pairs[(size_t)(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); + T rs(RAD_F32, {P, n}); 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); + // the composed matrices, [P * n/G groups][G (j)][G (i)], as f16 + auto compose = [&](const std::vector& angles, std::vector* tm) { + tm->assign((size_t)(P * (n / G) * G * G), 0.0f); + for (int64_t p = 0; p < P; ++p) + for (int64_t g = 0; g < n / G; ++g) 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); + std::vector v((size_t)G, 0.0); + v[(size_t)i] = 1.0; + for (int64_t st = 0; st < S; ++st) + for (int64_t j = 0; j < G / 2; ++j) { + const int64_t ia = pairs[(size_t)((p * S + st) * n + g * G + 2 * j)] - g * G; + const int64_t ib = pairs[(size_t)((p * S + st) * n + g * G + 2 * j + 1)] - g * G; + const double t = angles[(size_t)((p * S + st) * (n / 2) + g * (G / 2) + j)]; + const double c = std::cos(t), sn = std::sin(t); + const double va = v[(size_t)ia], vb = v[(size_t)ib]; + v[(size_t)ia] = va * c + vb * sn; + v[(size_t)ib] = vb * c - va * sn; + } + for (int64_t j = 0; j < G; ++j) + (*tm)[(size_t)(((p * (n / G) + g) * G + j) * G + i)] = (float)v[(size_t)j]; + } + }; + std::vector tmv; + compose(av, &tmv); + T tm(RAD_F16, {P * n, G}); + tm.f(tmv); + + for (int i8 = 0; i8 < 2; ++i8) { + const double qmax = i8 ? 127.0 : 448.0; + const uint32_t qdt = i8 ? RAD_I8 : RAD_F8E4M3; + T q(qdt, {M, P * n}), s(RAD_F32, {M, P * n / G}); + A a; a.t(x).t(tm).t(rs).t(q).t(s) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", i8 ? "i8" : "fp8"); + CHECK_OK(run("givens_dense_quant", 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 = pairs[(size_t)((p * S + st) * n + 2 * j)]; + const int64_t ib = pairs[(size_t)((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 / qmax) < 2e-3 * amax / qmax + 1e-12); // T is f16 + 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 + CHECK_EQ(bad_norm, 0); + CHECK(worst < (i8 ? 0.006 : 0.04)); // half a step of the grid (int8: 1/254 of the maximum), and T's f16 + } - // 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); + // T the identity, unit scales: exactly quant_act_fp8 + std::vector eye((size_t)(P * (n / G) * G * G), 0.0f), ones((size_t)(P * n), 1.0f); + for (int64_t pg = 0; pg < P * (n / G); ++pg) + for (int64_t i = 0; i < G; ++i) eye[(size_t)((pg * G + i) * G + i)] = 1.0f; + T tid(RAD_F16, {P * n, G}), rs1(RAD_F32, {P, n}); + tid.f(eye); 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)); + A b; b.t(x).t(tid).t(rs1).t(q1).t(s1) + .i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", "fp8"); + CHECK_OK(run("givens_dense_quant", 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));