diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 51bce18e..eaffb755 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -709,7 +709,7 @@ struct LinearFP8 { int64_t rot_split = 0; rad_buf rot_q2 = 0, rot_s2 = 0; rad_op op_rot2 = 0, op2 = 0; - rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0; + rad_weight rot_pairs = 0, rot_angle = 0, rot_scale = 0, rot_dense = 0; rad_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; int64_t rot_parts = 1, rot_stages = 0; @@ -761,21 +761,28 @@ struct LinearFP8 { std::initializer_list row_parts = {}, int64_t span_lo = 0, int64_t span_hi = 0, std::initializer_list rot_part_rows = {}); - /* THE ROTATION TABLES OF A ROTATED WEIGHT, declared as views of the weight's own planes, with - * `rot_parts` and `rot_stages`. `cut` is the rows of each rotated part; the GEMM's part bounds - * come back in pb1 and pb2. */ + /* THE ROTATION OF A ROTATED WEIGHT: its parts and stages (`rot_parts`, `rot_stages`) and its + * channel scale as a view of the weight's own plane. `cut` is the rows of each rotated part; the + * GEMM's part bounds come back in pb1 and pb2. */ int declare_rotation(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t N, int64_t K, RadWeightGroup grp, const std::vector& cut, int64_t* pb1, int64_t* pb2); - /* The op in front of the GEMM, over those tables: `op` is givens_rotate (f16 out) or a - * rotate-and-quantise (codes and a scale), for M in [lo, hi]. */ - rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, int64_t lo, - int64_t hi, std::initializer_list outs) const; + /* THE SEQUENTIAL NETWORK (decode: a few rows, where one network a row is cheap): the pairs and + * angles as views, and givens_rotate over them to f16, for M in [lo, hi]. */ + int decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, RadWeightGroup grp); + rad_op decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, int64_t hi, + std::initializer_list outs) const; + /* THE DENSE ROTATION (rot_dense, decl_dense): givens_dense_quant to `out` ("fp8" or "i8") codes + * and a scale, for M in [lo, hi]. */ + rad_op decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, int64_t lo, + int64_t hi, std::initializer_list outs) const; /* gemm_nt_q over this weight, M in [lo, hi]. `pb1`/`pb2` go only to a weight with rotated * parts, so a one-part op keeps the plain op's geometry -- the key the tune cache is read by. */ rad_op decl_gemm_q(RadBuilder* b, int64_t lo, int64_t hi, int64_t group, const char* dtype, int64_t pb1, int64_t pb2, std::initializer_list wts, std::initializer_list reads, rad_buf y) const; + rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, int64_t N, int64_t K, + RadWeightGroup grp); void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale @@ -930,18 +937,24 @@ inline int LinearFP8::declare_rotation(RadBuilder* b, Names& nm, const char* bas rot_stages = S; *pb1 = P > 1 ? cut[0] : 0; *pb2 = P > 2 ? cut[0] + cut[1] : 0; - rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, - { P * S, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, - { P * S, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); rot_scale = decl_view(b, nm.f("%s.rot_scale", base), wn, "t.scale", RAD_F32, { P, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); - return rot_pairs && rot_angle && rot_scale ? RAD_OK : RAD_E_INVAL; + return rot_scale ? RAD_OK : RAD_E_INVAL; } -inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* op, - int64_t lo, int64_t hi, std::initializer_list outs) const { - return rw(b, RAD_OP(b, op, +inline int LinearFP8::decl_seq_tables(RadBuilder* b, Names& nm, const char* base, const char* wn, + RadWeightGroup grp) { + const int64_t PS = rot_parts * rot_stages; + rot_pairs = decl_view(b, nm.f("%s.rot_pairs", base), wn, "t.pairs", RAD_I32, + { PS, K }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + rot_angle = decl_view(b, nm.f("%s.rot_angle", base), wn, "t.angle", RAD_F32, + { PS, K / 2 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + return rot_pairs && rot_angle ? RAD_OK : RAD_E_INVAL; +} + +inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& a, int64_t lo, + int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, "givens_rotate", RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), RAD_INT("stages", rot_stages), RAD_INT("parts", rot_parts)), @@ -949,6 +962,25 @@ inline rad_op LinearFP8::decl_rot_op(RadBuilder* b, const Geom& g, const ActFP8& { a.x }, outs); } +inline rad_op LinearFP8::decl_dense_op(RadBuilder* b, const Geom& g, const ActFP8& a, const char* out, + int64_t lo, int64_t hi, std::initializer_list outs) const { + return rw(b, RAD_OP(b, "givens_dense_quant", + RAD_PARAMS(RAD_RANGE("M", lo, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_INT("parts", rot_parts), + RAD_STR("out", out)), + RAD_WEIGHTS(rot_dense, rot_scale)), + { a.x }, outs); +} + +/* The dense rotation matrices of a rotated weight: a view of its two table planes, declared as several planes + * are -- at the first one's dtype (i32) and the weight's logical [N, K] -- that the op's layout hook + * (r4d_rad_layout_gdense) composes into [P * K, 128] f16. */ +inline rad_weight LinearFP8::decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, + int64_t N, int64_t K, RadWeightGroup grp) { + return decl_view(b, nm.f("%s.rot_dense", base), wn, "t.pairs,t.angle", RAD_I32, { N, K }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); +} + inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, std::initializer_list src, @@ -1097,10 +1129,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool band = hi > kSplit; const int64_t f16_hi = band ? kSplit : hi; /* the f16 chain's rows */ RAD_ARCH_TRY(declare_rotation(b, nm, base, wn, enc, N, K, grp, cut, &pb1, &pb2)); + RAD_ARCH_TRY(decl_seq_tables(b, nm, base, wn, grp)); const int64_t P = rot_parts; rot_q = decl_b(b, nm.f("%s.rot_y", base), RAD_F16, { f16_hi, P * K }); if (!rot_q) return RAD_E_INVAL; - op_rot = decl_rot_op(b, g, a, "givens_rotate", 1, f16_hi, { rot_q }); + op_rot = decl_rot_op(b, g, a, 1, f16_hi, { rot_q }); if (!op_rot) return RAD_E_INVAL; w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); @@ -1117,7 +1150,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha rot_q2 = decl_b(b, nm.f("%s.rot_q2", base), RAD_I8, { hi, P * K }); rot_s2 = decl_b(b, nm.f("%s.rot_s2", base), RAD_F32, { hi, P * (K / RAD_FP8_BLOCK) }); if (!rot_q2 || !rot_s2) return RAD_E_INVAL; - op_rot2 = decl_rot_op(b, g, a, "givens_quant_act_i8g", kSplit + 1, hi, { rot_q2, rot_s2 }); + rot_dense = decl_dense(b, nm, base, wn, N, K, grp); + if (!rot_dense) return RAD_E_INVAL; + op_rot2 = decl_dense_op(b, g, a, "i8", kSplit + 1, hi, { rot_q2, rot_s2 }); op2 = decl_gemm_q(b, kSplit + 1, hi, RAD_FP8_BLOCK, bits5 ? "w5a8i8" : "w4a8i8_asym", pb1, pb2, { w, ws }, { rot_q2, rot_s2 }, y); if (!op_rot2 || !op2) return RAD_E_INVAL; @@ -1187,7 +1222,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha rot_q = decl_b(b, nm.f("%s.rot_q", base), RAD_F8E4M3, { rows, rot_parts * K }); rot_s = decl_b(b, nm.f("%s.rot_s", base), RAD_F32, { rows, rot_parts * (K / RAD_FP8_BLOCK) }); if (!rot_q || !rot_s) return RAD_E_INVAL; - op_rot = decl_rot_op(b, g, a, "givens_quant_act_fp8", 1, rows, { rot_q, rot_s }); + rot_dense = decl_dense(b, nm, base, wn, N, K, grp); + if (!rot_dense) return RAD_E_INVAL; + op_rot = decl_dense_op(b, g, a, "fp8", 1, rows, { rot_q, rot_s }); if (!op_rot) return RAD_E_INVAL; } const char* sn = nm.f("%s.scale", base); @@ -1318,8 +1355,8 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in return; } if (paro5 && rot_split && rows > rot_split) { - RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), - RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), + RAD_ISSUE_N(c, op_rot2, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense), + RAD_W(rot_scale), brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), @@ -1339,8 +1376,8 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in const rad_buf aq = paro ? rot_q : a.q, as = paro ? rot_s : a.s; const int64_t ak = rot_parts * K; if (paro) - RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), - RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(aq, r0, rows, ak), + RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_dense), + RAD_W(rot_scale), brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK), diff --git a/docs/OPS.md b/docs/OPS.md index 42f56a32..75e73d3c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -367,6 +367,7 @@ spelling of `act`, not the vocabulary's. | `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`? | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index c901984c..c79bfa28 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -109,6 +109,7 @@ set(R4D_UNITS "r4d_gemm_w4a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w5a16_nt_m64|-DR4D_GEMM_W4_GROUP=${RAD_W4_GROUP}" "r4d_gemm_wpa8i8_tiled|" + "r4d_givens_dense|" "r4d_gemm_w8a16_nt_m64|-DR4D_GEMM_W8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w2a8_nt|-DR4D_GEMM_W2A8_GROUP=${RAD_W4_GROUP}" "r4d_gemm_w4a8_nt_m64|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}" diff --git a/libr4d/r4d_givens_dense.hip b/libr4d/r4d_givens_dense.hip new file mode 100644 index 00000000..eb534220 --- /dev/null +++ b/libr4d/r4d_givens_dense.hip @@ -0,0 +1,168 @@ +// r4d_givens_dense.hip -- ParoQuant's rotation as a dense per-group matrix on the matrix cores. +// +// 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 +// 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 +// sequential producer's. About 3x faster at prefill sizes and no slower at decode. +// +// THE MATRICES ARE THE WEIGHT: rad-convert composes them from the container's `t.pairs` / `t.angle` +// tables (r4d_layout.cpp, r4d.givens.dense) into [parts * K / 128][128 (j)][128 (i)] f16, so the +// serving side never walks a Givens network. The channel scale stays a separate table (`rscale`), a +// divide on the way in: folding 1/D into T would put entries of very different magnitude in one f16 +// matrix. +// +// ONE BLOCK A (part, group) x row chunk. The group's T (32 KiB of f16) is staged in LDS once and each +// of the block's four waves takes 16-row tiles: per k step one B fragment (the activation row's +// eight k, divided by D, as f16) meets the eight j tiles of T. The accumulators are C[j][m]: lane l +// holds column m = l & 15 and rows j = 8 * (l >> 4) + e, so a row's 128 outputs are split over lane m +// and lane m + 16 and its amax is a max over 64 registers and one xor-16 shuffle. +// +// WHAT MOVED THE TIME (selftest, 2048 rows x K 5120): the first version waited on one activation load a +// k step and spilled ~190 registers (186 us). A tile's eight loads are now issued together and the +// issue order is pinned per k step (sched_barrier), which is what keeps the A fragments from being +// hoisted whole into registers: 137 VGPRs, no spills, ~100 us. Double-buffering the next tile and +// coalescing the stores through LDS were tried and did not move it. +#include "r4d.h" +#include "r4d_emit.h" +#include "r4d_fp8_args.h" +#include "r4d_common.h" +#include "r4d_q8.h" +#include +#include +#include + +namespace { + +constexpr uint32_t kGroup = 128; +constexpr uint32_t kThreads = 128; +constexpr uint32_t kWaves = kThreads / 32; +constexpr uint32_t kTStride = kGroup + 8; // f16 per LDS row of T: 16 B pad, conflict-free b128 reads + +typedef _Float16 v8h_t __attribute__((ext_vector_type(8))); + +template +__global__ __launch_bounds__(kThreads) void givens_dense_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ tdense, const float* __restrict__ rscale, + uint8_t* __restrict__ q, float* __restrict__ s, uint32_t M, uint32_t K, uint32_t nkb, uint32_t x_ld, + uint32_t q_ld, uint32_t s_ld) { + __shared__ uint16_t Tl[kGroup * kTStride]; + __shared__ float invd[kGroup]; + const uint32_t gp = blockIdx.x, part = gp / nkb, g = gp % nkb; + const uint32_t tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + + // all sixteen loads in flight before the first LDS store: the staging is latency, not bandwidth + const uint4* tg = (const uint4*)(tdense + (size_t)gp * kGroup * kGroup); + constexpr uint32_t kStage = kGroup * kGroup / 8 / kThreads; + uint4 tv[kStage]; +#pragma unroll + for (uint32_t k = 0; k < kStage; ++k) tv[k] = tg[tid + k * kThreads]; +#pragma unroll + for (uint32_t k = 0; k < kStage; ++k) { + const uint32_t i = tid + k * kThreads, j = i / (kGroup / 8), c = i % (kGroup / 8); + *(uint4*)&Tl[j * kTStride + c * 8] = tv[k]; + } + invd[tid] = 1.0f / rscale[(size_t)part * K + g * kGroup + tid]; + __syncthreads(); + + const uint32_t h = lane >> 4, col = lane & 15; + const uint32_t Mt = (M + 15) >> 4; + const uint32_t step = gridDim.y * kWaves; + for (uint32_t tile = blockIdx.y * kWaves + wave; tile < Mt; tile += step) { + // The activation row a lane reads: lane (col, h) takes columns 8h .. 8h+7 of every 16-wide k step of + // row (tile * 16 + col). All eight k steps of a tile are loaded at once, so a tile costs one load + // latency and not eight. + uint32_t m = tile * 16 + col; + const bool live = m < M; + if (!live) m = M - 1; + const uint16_t* xr = x + (size_t)m * x_ld + g * kGroup + 8 * h; + uint4 raw[8]; +#pragma unroll + for (uint32_t ks = 0; ks < 8; ++ks) raw[ks] = *(const uint4*)(xr + ks * 16); + v8f acc[8]; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) acc[jt] = (v8f)(0.f); +#pragma unroll + for (uint32_t ks = 0; ks < 8; ++ks) { + const uint32_t c0 = ks * 16 + 8 * h; + const uint32_t w[4] = { raw[ks].x, raw[ks].y, raw[ks].z, raw[ks].w }; + v8h_t bf; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const uint32_t b = (w[e >> 1] >> (16 * (e & 1))) & 0xFFFFu; + const float v = __uint_as_float(b << 16) * invd[c0 + e]; + bf[e] = (_Float16)fminf(fmaxf(v, -65504.0f), 65504.0f); + } +#pragma unroll + for (int jt = 0; jt < 8; ++jt) { + const v8h_t af = *(const v8h_t*)&Tl[(jt * 16 + col) * kTStride + c0]; + acc[jt] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(af, bf, acc[jt]); + } + __builtin_amdgcn_sched_barrier(0); // keep a k step's A fragments from being hoisted over the last + } + float amax = 0.0f; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) +#pragma unroll + for (int e = 0; e < 8; ++e) amax = fmaxf(amax, fabsf(acc[jt][e])); + amax = fmaxf(amax, __shfl_xor(amax, 16)); + const float sc = amax > 0.0f ? amax * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if (!live) continue; + if (h == 0) s[(size_t)m * s_ld + (size_t)part * nkb + g] = sc; + uint8_t* qr = q + (size_t)m * q_ld + (size_t)part * K + g * kGroup + 8 * h; +#pragma unroll + for (int jt = 0; jt < 8; ++jt) { + const uint32_t lo = q8_pack4(acc[jt][0], acc[jt][1], acc[jt][2], acc[jt][3], inv); + const uint32_t hi = q8_pack4(acc[jt][4], acc[jt][5], acc[jt][6], acc[jt][7], inv); + *(uint2*)(qr + jt * 16) = make_uint2(lo, hi); + } + } +} + +} // namespace + +// x [M][K] bf16, `x_ld` elements a row (0 = K) +// tdense [parts * K/128][128][128] f16, T[j][i] of each (part, group), laid out by r4d_layout.cpp +// rscale [parts][K] f32, the factor the stored row was multiplied by +// q [M][parts * K] int8 or E4M3, `q_ld` elements a row (0 = parts * K) +// s [M][parts * K/128] f32, `s_ld` elements a row (0 = parts * K/128) +enum { GD_X = 0, GD_T = 1, GD_RSCALE = 2, GD_Q = 3, GD_S = 4 }; + +static int givens_dense_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* x = r4d_opt(a, GD_X); + const RadTensor* t = r4d_opt(a, GD_T); + const RadTensor* rs = r4d_opt(a, GD_RSCALE); + const RadTensor* q = r4d_opt(a, GD_Q); + const RadTensor* sc = r4d_opt(a, GD_S); + if (!x || !t || !rs || !q || !sc) return R4D_NO(RAD_E_INVAL); + if (x->rank < 2 || q->rank != 2 || sc->rank != 2 || t->rank != 2 || rs->rank != 2) + return R4D_NO(RAD_E_SHAPE); + if (t->dtype != RAD_F16 || rs->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + const bool i8 = q->dtype == RAD_I8; + if (!i8 && q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1); + const long long parts = r4d_geti_or(a, "parts", 1), nkb = K / kGroup; + if (r4d_geti_or(a, "group", kGroup) != kGroup || K % kGroup || parts < 1) return R4D_NO(RAD_E_SHAPE); + if (q->shape[0] != M || q->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE); + if (sc->shape[0] != M || sc->shape[1] != parts * nkb) return R4D_NO(RAD_E_SHAPE); + // tdense is a packed blob: its byte count is the layout hook's ([parts * K, 128] f16), not a shape to check + if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(t->data, 16) || !r4d_aligned(x->data, 16) || !r4d_aligned(q->data, 8)) + return R4D_NO(RAD_E_ALIGN); + const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); + if (xp < 0 || qp < 0 || sp < 0 || (xp * 2) % 16) return R4D_NO(RAD_E_STRIDE); + const long long mt = (M + 15) / 16; + const uint32_t gy = (uint32_t)std::max(1, (mt + 4 * kWaves - 1) / (4 * kWaves)); + const dim3 grid((uint32_t)(parts * nkb), gy); +#define GD_EMIT(I8_) R4D_EMIT(sk, (givens_dense_kernel), grid, dim3(kThreads), 0, \ + (const uint16_t*)x->data, (const uint16_t*)t->data, (const float*)rs->data, (uint8_t*)q->data, \ + (float*)sc->data, (uint32_t)M, (uint32_t)K, (uint32_t)nkb, (uint32_t)xp, (uint32_t)qp, (uint32_t)sp) + const int rc = i8 ? GD_EMIT(true) : GD_EMIT(false); +#undef GD_EMIT + if (rc != RAD_OK) return rc; + return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK; +} +R4D_ENTRY(r4d_rad_givens_dense_quant, givens_dense_body) diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 17ba87e0..02554bb3 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -571,6 +571,90 @@ extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, co return RAD_OK; } +/* ---- givens_dense: ParoQuant's rotation tables composed into one dense matrix a (part, group). + * + * A "givens" weight stores its rotation as pairs (i32 [P*S, K]) and angles (f32 [P*S, K/2]); the dense + * kernel (r4d_givens_dense.hip) applies it as T (x / D), T being the composition of the group's S + * stages. The blob is [P * K/128][128 (j)][128 (i)] f16, T[j][i] = output j of the network fed the unit + * vector e_i, so a (part, group) is 32 KiB the kernel stages whole. Composed in f32 in the order the + * stages are applied (stage 0 first), a' = a c + b s, b' = b c - a s -- libref's loop -- and rounded to + * f16 once. Operand 1 of givens_dense_quant; everything else stays as stored. */ +namespace { +constexpr int GD_OPERAND = 1; +constexpr long long GD_GROUP = 128; + +int gd_geom(const RadParam* p, int n_p, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, + long long* P, long long* S, long long* K) { + if (n != 2 || std::strncmp(r4d_enc::role(enc, sel, 0), "t.pairs", RAD_ENC_STR) != 0 || + std::strncmp(r4d_enc::role(enc, sel, 1), "t.angle", RAD_ENC_STR) != 0) return RAD_E_SHAPE; + *K = r4d_pgeti_or(p, n_p, "n", 0); + *P = r4d_pgeti_or(p, n_p, "parts", 1); + if (*K <= 0 || *K % GD_GROUP || *P < 1) return RAD_E_SHAPE; + if (pl[0].rank != 2 || pl[0].shape[1] != *K || pl[0].shape[0] % *P || pl[0].dtype != RAD_I32) + return RAD_E_SHAPE; + *S = pl[0].shape[0] / *P; + if (*S < 1 || !dims(pl[1], *P * *S, *K / 2) || pl[1].dtype != RAD_F32) return RAD_E_SHAPE; + return RAD_OK; +} +} /* namespace */ + +extern "C" int r4d_rad_layout_gdense(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, RadLayout* out) { + if (!out || !pl) return RAD_E_INVAL; + if (operand != GD_OPERAND) return RAD_E_UNSUPPORTED; + long long P, S, K; + const int rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &S, &K); + if (rc != RAD_OK) return rc; + fill(out, "r4d.givens.dense.g128", RAD_F16, P * K, GD_GROUP, P * K * GD_GROUP * 2); + return RAD_OK; +} + +extern "C" int r4d_rad_relayout_gdense(const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, void* dst, + int64_t dst_bytes) { + RadLayout L; + int rc = r4d_rad_layout_gdense(p, n_p, operand, enc, sel, pl, n, &L); + if (rc != RAD_OK) return rc; + if (dst_bytes != L.bytes) return RAD_E_SHAPE; + long long P, S, K; + rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &S, &K); + if (rc != RAD_OK) return rc; + const int32_t* pairs = (const int32_t*)pdata(pl[0]); + const float* ang = (const float*)pdata(pl[1]); + uint16_t* t = (uint16_t*)dst; + const long long nkb = K / GD_GROUP, half = GD_GROUP / 2; + std::vector ia((size_t)(S * half)), ib((size_t)(S * half)); + std::vector cs((size_t)(S * half)), sn((size_t)(S * half)); + std::vector v((size_t)GD_GROUP); + for (long long pt = 0; pt < P; ++pt) + for (long long g = 0; g < nkb; ++g) { + for (long long st = 0; st < S; ++st) + for (long long j = 0; j < half; ++j) { + const long long row = pt * S + st, o = (size_t)(st * half + j); + const long long a = pairs[row * K + g * GD_GROUP + 2 * j] - g * GD_GROUP; + const long long b = pairs[row * K + g * GD_GROUP + 2 * j + 1] - g * GD_GROUP; + if (a < 0 || a >= GD_GROUP || b < 0 || b >= GD_GROUP || a == b) return RAD_E_FORMAT; + ia[(size_t)o] = (int)a; + ib[(size_t)o] = (int)b; + const float th = ang[row * (K / 2) + g * half + j]; + cs[(size_t)o] = std::cos(th); + sn[(size_t)o] = std::sin(th); + } + uint16_t* tg = t + (size_t)(pt * nkb + g) * GD_GROUP * GD_GROUP; + for (long long i = 0; i < GD_GROUP; ++i) { + std::fill(v.begin(), v.end(), 0.0f); + v[(size_t)i] = 1.0f; + for (long long o = 0; o < S * half; ++o) { + const float va = v[(size_t)ia[(size_t)o]], vb = v[(size_t)ib[(size_t)o]]; + v[(size_t)ia[(size_t)o]] = va * cs[(size_t)o] + vb * sn[(size_t)o]; + v[(size_t)ib[(size_t)o]] = vb * cs[(size_t)o] - va * sn[(size_t)o]; + } + for (long long j = 0; j < GD_GROUP; ++j) tg[j * GD_GROUP + i] = f32_to_f16(v[(size_t)j]); + } + } + return RAD_OK; +} + /* ---- w8: i8 codes, symmetric about zero, an f16 scale a group. The f16 kernel (a16) reads the * code offset binary with zero 128 in the shared dword; the int8 kernel (a8) reads it signed with a * bare f16 scale plane. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 3609719f..abc57929 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -220,6 +220,8 @@ int r4d_rad_gemm_w5a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16asym_m64(const RadArgs*, RadStream); int r4d_rad_gemm_w4a8i8_tiled(const RadArgs*, RadStream); int r4d_rad_gemm_w5a8i8_tiled(const RadArgs*, RadStream); +int r4d_rad_givens_dense_quant(const RadArgs*, RadStream); +int r4d_rad_givens_dense_quant_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -401,6 +403,10 @@ int r4d_rad_relayout_w5(const RadParam*, int, int, const RadEncoding*, const int const RadTensor*, int, void*, int64_t); int r4d_rad_unrelayout_w5(const RadParam*, int, int, const RadEncoding*, const int*, const void*, int64_t, const RadTensor*, int); +int r4d_rad_layout_gdense(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_relayout_gdense(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, void*, int64_t); int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 5b841e59..202bc1eb 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1079,6 +1079,26 @@ static const RadOperandSpec oGivensQuantAct[] = { { "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 + * 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. */ +static const RadParamSpec pGivensDense[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + { "group", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "parts", RAD_P_INT, RAD_REQUIRED }, + { "out", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oGivensDense[] = { + { "x", RAD_OPD_IN, 0 }, + { "tdense", RAD_OPD_WEIGHT, 0 }, + { "rscale", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, +}; + /* `gram_accum` is a NEW OP and this plugin fixes its schema. It is the calibration half of GPTQ: * `h += x^T x` over an E4M3 activation, accumulated across every launch of a corpus. * @@ -2346,6 +2366,13 @@ static const RadOpSchema kSchemas[] = { "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 " @@ -3015,6 +3042,9 @@ static const RadConstraint cQuantActFp8[] = { * straddle the end of a row: the ragged tail the unrotated kernel writes zero-padded would mix * real values with padding inside one butterfly, and there is no weight block on the other side * that was rotated the same way. */ +static const RadConstraint cGivensDense[] = { + C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_IN("out", "i8 fp8"), +}; static const RadConstraint cHadQuantActFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; @@ -5258,6 +5288,18 @@ static const RadKernelInfo kKernels[] = { 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", + "n a multiple of 128 and group 128; the matrices are the weight, composed from the givens tables at " + "convert time", + "bf16 in, int8 or E4M3 out in PLAIN ROW-MAJOR order, parts side by side, with an f32 scale (amax/127 " + "or amax/448) per (row, part, 128 columns); f16 matrices and f32 channel scales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGivensDense), NOTUNE, + nullptr, nullptr, r4d_rad_givens_dense_quant, nullptr, r4d_rad_layout_gdense, r4d_rad_relayout_gdense, + nullptr, nullptr, nullptr, r4d_rad_givens_dense_quant_describe }, + { "givens_rotate", "givens_rotate", "quant", "the channel scale and ParoQuant's Givens rotations, once for each rotated part, to f16", "n a multiple of 128 and group 128: a rotation group cannot straddle the end of a row", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index c2f1f4f2..4c46a3ef 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3775,12 +3775,13 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_ * must sit within the E4M3 grid of the reference (half a step at the top of the range is 1/16 of * 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) { - const char* row = rot_only ? "givens_rotate" : i8 ? "givens_quant_act_i8g" : "givens_quant_act_fp8"; + 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"; if (!sel(row)) return; char nm[160]; - std::snprintf(nm, sizeof nm, "%s numeric M=%lld K=%lld parts=%d stages=%d", row, (long long)M, - (long long)K, parts, stages); + std::snprintf(nm, sizeof nm, "%s %s numeric M=%lld K=%lld parts=%d stages=%d", row, + dense ? (i8 ? "i8" : "fp8") : "", (long long)M, (long long)K, parts, stages); const RadKernelInfo* r = find(pl, row); if (!r || !r->launch) { ok(nm, false, "row absent"); return; } const int64_t G = 128, ng = K / G; @@ -3818,6 +3819,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in void* d_r = dalloc(rs.size() * 4); void* d_q = dalloc((size_t)(M * parts * K) * (rot_only ? 2 : 1)); void* d_s = dalloc((size_t)(M * parts * ng) * 4); + void* d_t = nullptr; if (!d_x || !d_p || !d_a || !d_r || !d_q || !d_s) { ok(nm, false, "hipMalloc failed"); return; } st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_p, pairs.data(), pairs.size() * 4, hipMemcpyHostToDevice); @@ -3832,6 +3834,29 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in if (rot_only) ts.pop_back(); std::vector ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), PI("stages", stages), PI("parts", parts) }; + if (dense) { + // the matrices come out of the row's own layout hook, from the same tables, as rad-convert makes them + Planes pp; + pp.enc = rad_enc_plain(RAD_BF16); + rad_enc_add_table(&pp.enc, "t.pairs", RAD_I32, NPS, K); + rad_enc_add_table(&pp.enc, "t.angle", RAD_F32, NPS, K / 2); + pp.data.assign(3, {}); + pp.rows = { 0, NPS, NPS }; + pp.cols = { 0, K, K / 2 }; + pp.data[1].assign((const uint8_t*)pairs.data(), (const uint8_t*)(pairs.data() + pairs.size())); + pp.data[2].assign((const uint8_t*)ang.data(), (const uint8_t*)(ang.data() + ang.size())); + std::vector lp = { PI("n", K), PI("parts", parts) }; + std::vector blob; + const int rl = stored(r, lp, 1, pp, { "t.pairs", "t.angle" }, &blob); + if (rl != RAD_OK) { ok(nm, false, "relayout rc " + std::to_string(rl)); return; } + d_t = dalloc(blob.size()); + if (!d_t) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_t, blob.data(), blob.size(), hipMemcpyHostToDevice); + ts = { T(d_x, RAD_BF16, { M, K }), T(d_t, RAD_F16, { parts * K, 128 }), T(d_r, RAD_F32, { (int64_t)parts, K }), + T(d_q, i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, { M, parts * K }), T(d_s, RAD_F32, { M, parts * ng }) }; + ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), PI("parts", parts), + PS("out", i8 ? "i8" : "fp8") }; + } RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -3877,9 +3902,25 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in } } } - char d[96]; + char d[128]; std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val); - ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < (i8 ? 0.01 : 0.07)), d); + if (M >= 1024) { // a prefill chunk: say how fast it ran + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + for (int i = 0; i < 3; ++i) r->launch(&a, nullptr); + st_ev_record(e0, nullptr); + for (int i = 0; i < 20; ++i) r->launch(&a, nullptr); + st_ev_record(e1, nullptr); + st_ev_sync(e1); + float ms = 0; + st_ev_elapsed(&ms, e0, e1); + st_ev_destroy(e0); st_ev_destroy(e1); + std::printf(" %.1f us a launch (%s)\n", (double)ms * 50.0, d); + } + // the dense form carries f16 matrices: its scale reads ~1e-3 off the f32 network's, its values stay within the + // quantiser's own step + ok(nm, rot_only ? worst_val < 1e-3 + : (worst_scale < (dense ? 3e-3 : 1e-4) && worst_val < (i8 ? 0.01 : 0.07)), d); } @@ -13148,6 +13189,22 @@ static void device_phase(const Plugin& pl) { 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) { + givens_numeric(pl, 1, 128, 1, 8, false, i8, true); + givens_numeric(pl, 5, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 8, 5120, 2, 8, false, i8, true); + givens_numeric(pl, 16, 5120, 1, 8, false, i8, true); + 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, 2048, 17408, 1, 8, false, i8, true); + } } if (sel("givens_quant_act_fp8")) { if (!g_case) std::printf("\nParoQuant's rotate-and-quantise, against an f64 rotation\n"); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index d1c03330..560f55b4 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -102,6 +102,7 @@ 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); int ref_gated_quant_fp8 (const RadArgs*, RadStream); @@ -233,6 +234,7 @@ 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); REF_SHAPE_FN(ref_gated_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index f0e60573..897b4894 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -495,6 +495,52 @@ static int givens_body(const RadArgs* a, bool quant, bool i8 = false) { 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 + * 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) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4]; + const int64_t n = p_int(a, "n", 0), P = p_int(a, "parts", 1), g = p_int(a, "group", 0); + if (n <= 0 || P <= 0 || g != 128 || n % g != 0) return RAD_E_SHAPE; + const bool i8 = q->dtype == RAD_I8; + if (!i8 && q->dtype != RAD_F8E4M3) return RAD_E_DTYPE; + const int64_t rows = numel(x) / n, ngrp = n / g; + if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n || + numel(s) < rows * P * ngrp) return RAD_E_SHAPE; + const float qmax = i8 ? 127.0f : 448.0f; + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n); + const int64_t xs = laststride(x), qs = laststride(q); + std::vector in((size_t)g), y((size_t)g); + for (int64_t p = 0; p < P; ++p) + for (int64_t gi = 0; gi < ngrp; ++gi) { + for (int64_t i = 0; i < g; ++i) + in[(size_t)i] = ldt(x, xb + (gi * g + i) * xs) / ldt(sc, p * n + gi * g + i); + float amax = 0.0f; + for (int64_t j = 0; j < g; ++j) { + double acc = 0.0; + for (int64_t i = 0; i < g; ++i) + acc += (double)ldt(tm, ((p * ngrp + gi) * g + j) * g + i) * (double)in[(size_t)i]; + y[(size_t)j] = (float)acc; + amax = std::max(amax, std::fabs(y[(size_t)j])); + } + const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f; + const float inv = 1.0f / scl; + for (int64_t j = 0; j < g; ++j) { + float v = y[(size_t)j] * 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 + gi * g + j) * qs, v); + } + stt(s, rowoff(s, r, P * ngrp) + (p * ngrp + gi) * laststride(s), scl); + } + } + 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); } diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 56debdd1..30430f8a 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -206,6 +206,10 @@ static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") }; * 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 RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), + P_INT("parts"), P_STR("out") }; +static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rscale"), OUT("q"), + 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"), @@ -811,6 +815,13 @@ static const RadOpSchema kSchemas[] = { "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 " @@ -1188,6 +1199,10 @@ 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", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index d631961b..f188cb1b 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -840,6 +840,10 @@ 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 */ +} + int ref_givens_rotate_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; /* a pairing cannot be drawn: see givens_quant_act_fp8 */ } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index c33ab599..5ca8af2d 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_rotate", "had_quant_act_i8", + "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", "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". */