diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index e99c8e3f..51ee97e6 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -697,10 +697,18 @@ struct LinearFP8 { * (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. */ - bool paro = false, probed_paro = false; + bool paro = false; /* ...AND ITS 5-BIT SIBLING: the same rotation, to f16 (`rot_q` is then the f16 plane and there is no * `rot_s`), then gemm_nt_q at w5a16 over a weight of u5 codes, an f16 scale and a zero point. */ bool paro5 = false; + /* ...AND ITS PREFILL BAND (z-lab's int4 and the int5): above `rot_split` rows the f16 skinny kernel is + * bound by the slow f16 matrix instruction, so a second chain runs there -- the same rotation to + * int8 with a scale a (row, 128) into `rot_q2`/`rot_s2`, then the int8 tiled GEMM + * (`w4a8i8_asym` / `w5a8i8`), both reading the SAME weight views. At or below the split the f16 chain + * above runs. */ + 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_buf rot_q = 0, rot_s = 0; rad_op op_rot = 0; @@ -743,7 +751,7 @@ struct LinearFP8 { /* `span_lo`/`span_hi`, when hi is set, is this rank's uneven slice of the split dimension in * the model's units -- rows of each row part for RAD_SHARD_ROW, columns for RAD_SHARD_COL -- * and n_out / n_in is already its width; see rad_weight_shard_span. Whole scale blocks. */ - /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight (probed_paro), + /* `rot_parts`: the rows of each independently rotated part of a ROTATED weight, * which `row_parts` is when the pieces and the shard parts are the same cut -- gate|up -- and * is not when they are not: the delta net's qkv|z is four shard parts and two rotated ones. */ int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -862,8 +870,8 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* enc.plane[0].dtype == RAD_BF16; probed_i8 = known && linear_is_w8(enc); /* A ROTATED weight rotates the bf16 plane itself: its quantiser is not the producer's. */ - probed_paro = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); - reads_x = g.w_bf16 || plain || probed_i8 || probed_paro; + const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); + reads_x = g.w_bf16 || plain || probed_i8 || rotated; return RAD_OK; } @@ -1074,31 +1082,63 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha for (int64_t p : rot_part_rows) cut.push_back(p); if (cut.empty()) for (int64_t p : row_parts) cut.push_back(p); int64_t pb1 = 0, pb2 = 0; - RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, max_rows, cut, true, - &pb1, &pb2)); + const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; const bool bits5 = enc.plane[0].dtype == RAD_U5; + const int64_t kSplit = 64; /* the skinny kernel's M ceiling */ + const bool band = hi > kSplit; + RAD_ARCH_TRY(declare_rotation(b, nm, g, base, wn, enc, N, K, grp, a, + band ? kSplit : max_rows, cut, true, &pb1, &pb2)); w = decl_view(b, wn, nullptr, "codes", enc.plane[0].dtype, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp); if (!w || !ws) return RAD_E_INVAL; - const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; op = rot_parts > 1 ? rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym"), RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), RAD_WEIGHTS(w, ws)), { rot_q }, { y }) : rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_PARAMS(RAD_RANGE("M", 1, band ? kSplit : hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a16" : "w4a16_asym")), RAD_WEIGHTS(w, ws)), { rot_q }, { y }); - paro = false; - return op ? RAD_OK : RAD_E_INVAL; + if (!op) return RAD_E_INVAL; + if (band) { + /* THE PREFILL BAND: rows above the skinny kernel's ceiling rotate to int8 and meet the int8 + * tiled GEMM. Declared over the tables and weight views already made above. */ + const int64_t P = rot_parts; + rot_split = kSplit; + 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; + const RadEncPlane* tp = rad_enc_plane(&enc, "t.pairs"); + const int64_t S = tp->extent[0] / P; + op_rot2 = rw(b, RAD_OP(b, "givens_quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_INT("stages", S), RAD_INT("parts", P)), + RAD_WEIGHTS(rot_pairs, rot_angle, rot_scale)), + { a.x }, { rot_q2, rot_s2 }); + op2 = rot_parts > 1 + ? rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym"), + RAD_INT("pb1", pb1), RAD_INT("pb2", pb2)), + RAD_WEIGHTS(w, ws)), + { rot_q2, rot_s2 }, { y }) + : rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", kSplit + 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", bits5 ? "w5a8i8" : "w4a8i8_asym")), + RAD_WEIGHTS(w, ws)), + { rot_q2, rot_s2 }, { y }); + if (!op_rot2 || !op2) return RAD_E_INVAL; + } + return RAD_OK; } /* An E4M3 weight reads the E4M3 pair, and an input the model feeds at int8 codes has none -- @@ -1295,6 +1335,15 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); 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), + 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)), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + return; + } if (paro5) { 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(rot_q, r0, rows, rot_parts * K)); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 55d0c061..3f414b92 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -621,7 +621,6 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, c.name = name; c.rad_dtype = i5 ? RAD_U5 : RAD_U4; c.shape = { N, K }; - c.int5 = true; c.pbits = i5 ? 5 : 4; c.aux[0] = hi; c.aux[1] = qz; c.aux[2] = qzh; sliced_.push_back(std::move(c)); @@ -1047,11 +1046,11 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b (gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor"; } else if (!same) { out->why = "its pieces are stored in different dtypes"; - } else if (p0.int5) { + } else if (p0.pbits) { /* PARO int5-bitplane: u5 codes, an f16 scale and a u8 zero point a 128 of K, then the * rotation tables. Joined only along rows (gate|up), as every imported form is. */ bool fits = d == 0 || out->pieces.size() == 1; - for (const SrcTensor* pk : out->pieces) fits = fits && pk->int5 && pk->pbits == p0.pbits; + for (const SrcTensor* pk : out->pieces) fits = fits && pk->pbits == p0.pbits; if (!fits) { out->why = "its int5 pieces are joined along a column, across their groups"; } else { @@ -1389,7 +1388,7 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds const uint32_t dt = w.enc.plane[k].dtype; const int64_t eb = rad_dtype_bits(dt) / 8; uint8_t* o = (uint8_t*)dst; - if (w.paro && w.pieces[0]->int5 && k <= 2) { + if (w.paro && w.pieces[0]->pbits && k <= 2) { /* PARO int5-bitplane, RE-LAID a row of the logical [N, K] matrix at a time. The checkpoint * packs along N: qweight [K, N/8] holds eight low nibbles per word in AWQ order (word * column c of a group of eight sits in nibble j, ORDER[j] == c), and qweight_hi [K, N/32] diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index ee522ca0..f2eb8cd7 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -60,8 +60,7 @@ struct SrcTensor { * [K, N/8] and the tensor described is the logical [N, K] u5 code matrix; `aux` are the fifth-bit * plane qweight_hi [K, N/32], and the zero points qzeros [G, N/8] and qzeros_hi [G, N/32]. * z-lab's int4 (Import::ParoI4) is the same without the fifth-bit planes (aux[0], aux[2] null). */ - bool int5 = false; - int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4 */ + int pbits = 0; /* 5 for int5-bitplane, 4 for z-lab's plain AWQ-packed int4; 0 otherwise */ const SrcTensor* aux[3] = { nullptr, nullptr, nullptr }; int64_t numel() const { diff --git a/docs/OPS.md b/docs/OPS.md index 8fd23617..4c7ce457 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -363,6 +363,7 @@ 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_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 ff6a9ced..c901984c 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -108,6 +108,7 @@ set(R4D_UNITS "r4d_gemm_bf16_nt_tiled|" "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_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_gemm_wpa8i8_tiled.hip b/libr4d/r4d_gemm_wpa8i8_tiled.hip new file mode 100644 index 00000000..731ca882 --- /dev/null +++ b/libr4d/r4d_gemm_wpa8i8_tiled.hip @@ -0,0 +1,280 @@ +// r4d_gemm_wpa8i8_tiled.hip - r4d_gemm_w4a8i8_tiled / r4d_gemm_w5a8i8_tiled: the 4- and 5-bit ASYMMETRIC +// weight x int8 activation GEMM for PREFILL row counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with +// +// 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 +// 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: +// +// * a 256 x 64 tile (4 x 2 waves, 4 x 2 fragments each); the activation is re-tiled by +// r4d_mxfp4a8_tile_a into fragment order (one 16 x 16 fragment = 256 bytes) in the op's scratch and +// read straight into registers; the weight slab is staged through LDS; +// * a slab is one scale group (128 of K = 8 WMMA steps): the int32 accumulators start at zero each slab and +// are folded into the running float total as slab * (a_scale[row][g] * w_scale[col][g]), because the +// weight's f16 scale varies by column and so cannot ride inside the matrix instruction; +// * a partitioned weight (pb1/pb2) is one launch per part over windows of the planes. +// +// WHY INT8 AND NOT FP8. (code - zero) is -15..15 (int4) or -31..31 (int5); both are exact in an int8, +// so the weight needs no conversion at all -- the staging is a byte-wise subtract -- whereas e4m3's three +// mantissa bits stop at 16 and int5 would need two matrix issues a step. The activation is quantised to +// int8 with one scale a (row, 128 of K): after the rotation a group is flat, so 127 uniform levels of its +// maximum are finer than e4m3's relative 2^-4 for nearly every element (measured: ppl equal to the f16 +// path's, slightly better than the fp8 band's). The accumulators are int32 and exact: a slab is 128 +// products of at most 31 * 127. +// +// STAGING. A code byte c (0..31) minus the zero z (0..31): (c | 0x80) - z is 128 + (c - z), never below +// 97 and never carrying into the next byte, and XOR 0x80 turns it into the two's complement byte of +// (c - z). Three ALU ops a dword of four weights. +// +// THE WEIGHT BLOB is r4d_gemm_w5a16_nt_m64's (BITS 5): the nibble plane (w4's fragment order), then the +// fifth bits, one dword a (n-tile, 64 of K, lane): byte s = k step s of the block, bit e = element e. For +// BITS 4 it is the nibble plane alone. The scale operand is the f16 kernel's dword plane +// [N/16][K/128][16]: the f16 scale in the low half, -(1024 + zero) in the high. +#include "r4d.h" +#include "r4d_gemm_args.h" +#include "r4d_common.h" + +#include +#include +#include +#include +#include + +#define R4D_WPT_TM 4 // 16-row fragments per wave +#define R4D_WPT_TN 2 // 16-column fragments per wave +#define R4D_WPT_WM 4 // waves along M +#define R4D_WPT_WN 2 // waves along N +#define R4D_WPT_PAD 8 // LDS row pad: 16 lanes reading rows 136 B apart +#define R4D_WPT_NTHR (R4D_WPT_WM * R4D_WPT_WN * 32) +#define R4D_WPT_BMF (R4D_WPT_WM * R4D_WPT_TM * 16) +#define R4D_WPT_LBK 128 // one scale group a slab + +typedef int wpt_v2i __attribute__((ext_vector_type(2))); +typedef int wpt_v8i __attribute__((ext_vector_type(8))); +typedef unsigned wpt_u4 __attribute__((ext_vector_type(4))); + +// 4 bits -> bit 4 of each byte: the fifth bits of four elements, in the position above their nibbles +static __device__ __forceinline__ unsigned wpt_spread16(unsigned n) { + return ((n * 0x00204081u) & 0x01010101u) << 4; +} + +// four code bytes (0..31) and the zero point in every byte -> the four bytes of (code - zero), signed +static __device__ __forceinline__ unsigned wpt_sub_zero(unsigned codes4, unsigned zz) { + return ((codes4 | 0x80808080u) - zz) ^ 0x80808080u; +} + +template +__global__ __launch_bounds__(R4D_WPT_NTHR) void r4d_gemm_wpa8i8_tiled_kernel( + const unsigned char* __restrict__ AT, const float* __restrict__ As, + const unsigned* __restrict__ Wq, const unsigned* __restrict__ Whi, const unsigned* __restrict__ Wsz, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int ldc) { + constexpr int TM = R4D_WPT_TM, TN = R4D_WPT_TN, WN = R4D_WPT_WN, NTHR = R4D_WPT_NTHR, BMF = R4D_WPT_BMF; + constexpr int LBK = R4D_WPT_LBK, NS = LBK / 16, STR = LBK + R4D_WPT_PAD, BNF = WN * TN * 16; + constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32; + // A thread stages one lane's 16 bytes of a 64-wide k block -- four k steps of one weight row, which + // is how the fragment-order plane is laid out (dword (t, kb, lane, s)) -- so a slab of two blocks + // over the block's tiles is TOT_SLOTS / 4 reads. + constexpr int NW = TOT_SLOTS / 4 / NTHR; + static_assert(NW * NTHR * 4 == TOT_SLOTS, "the W tile must split evenly over the block"); + __shared__ unsigned char sW[BNF * STR]; + + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int wm = wave / WN, wn = wave % WN; + const int col = lane & 15, kb8 = (lane >> 4) * 8; + const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF; + const int ksteps = K / 16, kpb = K / 64, Mt = (M + 15) >> 4, nsz = K / 128; + const int ntile_last = N / 16 - 1; + + const unsigned char* abase[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) { + int mt = (m0 >> 4) + wm * TM + i; + mt = mt < Mt - 1 ? mt : Mt - 1; + abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256); + } + const unsigned int aoff = (unsigned int)lane * 8; + + // The activation scales this lane folds with: one per M fragment, at the row its accumulators hold. + const float* __restrict__ arow[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) { + int m = m0 + wm * TM * 16 + i * 16 + col; + m = m < M ? m : M - 1; + arow[i] = As + (size_t)m * as_rs; + } + + // The W reads this thread makes, fixed across slabs: lane `wl` of n-tile `wt` (clamped to the last + // real tile), 64-wide k block `wkb` of the slab, staged to the LDS row `wrow` at half `whalf`. + int wrow[NW], wkb[NW], whalf[NW], wt[NW], wlane[NW]; +#pragma unroll + for (int it = 0; it < NW; ++it) { + const int idx = it * NTHR + tid; + wlane[it] = idx & 31; + wkb[it] = (idx >> 5) & 1; + const int ntl = (idx >> 5) >> 1; + wrow[it] = ntl * 16 + (wlane[it] & 15); + whalf[it] = wlane[it] >> 4; + const int t = (n0 >> 4) + ntl; + wt[it] = t < ntile_last ? t : ntile_last; + } + + float tot[TM][TN][8]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) tot[i][j][e] = 0.f; + + for (int k0 = 0, g = 0; k0 < K; k0 += LBK, ++g) { + // A fragments for the slab, one clause, consumed only at the WMMAs. + wpt_v2i af[TM][NS]; +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int st = 0; st < NS; ++st) + af[i][st] = *(const wpt_v2i*)(abase[i] + + (aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256))); + // The scales of this slab, issued ahead of the staging that hides their latency. + float sa[TM]; +#pragma unroll + for (int i = 0; i < TM; ++i) sa[i] = arow[i][g]; + float ws[TN][8]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + int t = (n0 + wn * TN * 16 + j * 16) >> 4; + t = t < ntile_last ? t : ntile_last; + const wpt_u4* p = (const wpt_u4*)(Wsz + ((size_t)t * nsz + g) * 16 + kb8); + const wpt_u4 v0 = p[0], v1 = p[1]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + ws[j][e] = __half2float(__ushort_as_half((unsigned short)(v0[e] & 0xFFFFu))); + ws[j][4 + e] = __half2float(__ushort_as_half((unsigned short)(v1[e] & 0xFFFFu))); + } + } + // W slab -> LDS as int8 (code - zero), by true k. A dword's element e is nibble 2e (e < 4) or + // 2(e-4)+1, and k = 8*(e>>2) + 4*(lane>>4) + (e&3): a lane writes its elements 0..3 at + // k = 4*(lane>>4) and 4..7 at +8, and the WMMA reads eight consecutive bytes. +#pragma unroll + for (int it = 0; it < NW; ++it) { + const size_t blk = (size_t)wt[it] * kpb + k0 / 64 + wkb[it]; + const wpt_u4 wv = *(const wpt_u4*)&Wq[blk * 128 + wlane[it] * 4]; + unsigned hb4 = 0; + if constexpr (BITS == 5) hb4 = Whi[blk * 32 + wlane[it]]; // byte s: the fifth bits of k step s + const unsigned sz = Wsz[((size_t)wt[it] * nsz + g) * 16 + (wlane[it] & 15)]; + const unsigned zz = ((sz >> 16) & 0x1Fu) * 0x01010101u; // high half is -(1024 + zero) in f16 +#pragma unroll + for (int s_ = 0; s_ < 4; ++s_) { + const unsigned w = wv[s_]; + unsigned cl = w & 0x0F0F0F0Fu, ch = (w >> 4) & 0x0F0F0F0Fu; // elements 0..3, 4..7 + if constexpr (BITS == 5) { + const unsigned hb = (hb4 >> (8 * s_)) & 0xFFu; + cl |= wpt_spread16(hb & 15u); + ch |= wpt_spread16(hb >> 4); + } + unsigned char* d = &sW[wrow[it] * STR + (wkb[it] * 4 + s_) * 16 + whalf[it] * 4]; + *(unsigned*)d = wpt_sub_zero(cl, zz); + *(unsigned*)(d + 8) = wpt_sub_zero(ch, zz); + } + } + lds_barrier(); + + wpt_v8i gacc[TM][TN]; +#pragma unroll + for (int step = 0; step < NS; ++step) { + const int kk = step * 16 + kb8; + wpt_v2i wf[TN]; +#pragma unroll + for (int j = 0; j < TN; ++j) { + const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk]; + wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4); + } + __builtin_amdgcn_sched_barrier(0); +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) + gacc[i][j] = step == 0 + ? __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, wf[j], true, af[i][step], (wpt_v8i)(0), false) + : __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, wf[j], true, af[i][step], gacc[i][j], false); + } +#pragma unroll + for (int i = 0; i < TM; ++i) +#pragma unroll + for (int j = 0; j < TN; ++j) +#pragma unroll + for (int e = 0; e < 8; ++e) tot[i][j][e] = fmaf((float)gacc[i][j][e], sa[i] * ws[j][e], tot[i][j][e]); + lds_barrier(); + } + +#pragma unroll + for (int j = 0; j < TN; ++j) { + const int nb = n0 + wn * TN * 16 + j * 16 + kb8; + if (nb >= N) continue; +#pragma unroll + for (int i = 0; i < TM; ++i) { + const int m = m0 + wm * TM * 16 + i * 16 + col; + if (m >= M) continue; + union { __hip_bfloat16 h[8]; wpt_u4 v; } o; +#pragma unroll + for (int e = 0; e < 8; ++e) o.h[e] = (__hip_bfloat16)tot[i][j][e]; + *(wpt_u4*)(C + (size_t)m * ldc + nb) = o.v; + } + } +} + +template +static void wpa8i8_launch(long at, long ascale, long wq, long whi, long wsz, long c, int M, int K, int N, + int as_rs, long stream, int ldc) { + if (M < 1) throw std::runtime_error("r4d gemm_wpa8i8_tiled: M must be >= 1"); + if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_wpa8i8_tiled: N must be a multiple of 16"); + if (K % R4D_WPT_LBK) throw std::runtime_error("r4d gemm_wpa8i8_tiled: K must be a multiple of 128"); + const int bnf = R4D_WPT_WN * R4D_WPT_TN * 16; + dim3 grid((N + bnf - 1) / bnf, (M + R4D_WPT_BMF - 1) / R4D_WPT_BMF), block(R4D_WPT_NTHR); + hipLaunchKernelGGL((r4d_gemm_wpa8i8_tiled_kernel), grid, block, 0, (hipStream_t)stream, + (const unsigned char*)at, (const float*)ascale, (const unsigned*)wq, + (const unsigned*)whi, (const unsigned*)wsz, (__hip_bfloat16*)c, M, K, N, as_rs, ldc); +} + +// ============================================================== the plugin ABI entry points +// The row-major int8 activation is re-tiled into the op's scratch (one slab a part), then the GEMM +// reads it from there -- mxfp4a8_tiled's arrangement exactly, including a partitioned weight as +// one launch per part over windows of the planes. +template +static int wpa8i8_dispatch(const RadArgs* a, RadStream s) { + GemmOps g; + int rc = gemm_ops(a, &g, 1); + if (rc != RAD_OK) return rc; + if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE); + if (!g.ascale) return R4D_NO(RAD_E_INVAL); + MxParts mp; + rc = mx_parts(a, &g, &mp); + if (rc != RAD_OK) return rc; + if (g.K % R4D_WPT_LBK) return R4D_NO(RAD_E_SHAPE); + int as_group = 0, as_rs = 1; + rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n); + if (rc != RAD_OK) return rc; + if (as_group != 128) return R4D_NO(RAD_E_SHAPE); // one scale a (row, 128): the slab + const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K); + if (!a->scratch || a->scratch_bytes < slab * mp.n) return R4D_NO(RAD_E_INVAL); + const long long kb = g.K / 128; + for (int p = 0; p < mp.n; ++p) { + const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p]; + const long at = (long)(uintptr_t)a->scratch + (long)(p * slab); + R4D_TRY("gemm_wpa8i8_tiled", + r4d_mxfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K, (long)(uintptr_t)s, + (int)(mp.lda ? mp.lda : g.K)); + wpa8i8_launch(at, r4d_addr(g.ascale) + p * kb * 4, + r4d_addr(g.b) + n0 * g.K / 2, + BITS == 5 ? r4d_addr(g.b) + g.N * g.K / 2 + n0 * g.K / 8 : 0L, + r4d_addr(g.bscale) + (n0 / 16) * kb * 16 * 4, + r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, as_rs, + (long)(uintptr_t)s, (int)g.N)); + } + return RAD_OK; +} + +extern "C" int r4d_rad_gemm_w4a8i8_tiled(const RadArgs* a, RadStream s) { return wpa8i8_dispatch<4>(a, s); } +extern "C" int r4d_rad_gemm_w5a8i8_tiled(const RadArgs* a, RadStream s) { return wpa8i8_dispatch<5>(a, s); } diff --git a/libr4d/r4d_givens_quant_act_fp8.hip b/libr4d/r4d_givens_quant_act_fp8.hip index b5bed570..58208f4c 100644 --- a/libr4d/r4d_givens_quant_act_fp8.hip +++ b/libr4d/r4d_givens_quant_act_fp8.hip @@ -26,12 +26,17 @@ // 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 { @@ -58,14 +63,18 @@ __device__ __forceinline__ void wave_sync() { // 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. -// QUANT false is givens_rotate: the same rotation, no quantiser, the rotated row written as f16 into +// 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. -template +// 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; @@ -126,7 +135,7 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( const float4 r = *(const float4*)(buf + lane * 4u); float v[4] = { r.x, r.y, r.z, r.w }; - if constexpr (!QUANT) { + 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; @@ -139,15 +148,10 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( #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 / 448.0f) : 1.0f; + 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; - const float inv = 1.0f / sc; - int pk = 0; - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); - *(uint32_t*)(q + (size_t)row * q_ld + (size_t)part * K + c0 + lane * 4u) = (uint32_t)pk; + *(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 @@ -160,8 +164,8 @@ __global__ __launch_bounds__(kThreads) void givens_quant_act_fp8_kernel( // 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, bool quant = true) { - if (!x || !pairs || !angle || !rscale || !q || (quant && !s)) return -1; + 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; @@ -169,17 +173,13 @@ static int givens_quant_launch(long x, long pairs, long angle, long rscale, long 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; - const int rc = quant - ? 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) - : 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); +#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; } @@ -189,7 +189,8 @@ 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, bool quant) { +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); @@ -199,7 +200,8 @@ static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { 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 (!quant && q->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE); + 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 @@ -220,14 +222,18 @@ static int givens_body(const RadArgs* a, const R4dSink& sk, bool quant) { 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, quant); + (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, true); + 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, false); + 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_layout.cpp b/libr4d/r4d_layout.cpp index f2d19202..ea31548c 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -506,15 +506,11 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons } uint32_t* wq = (uint32_t*)dst; uint32_t* hi = wq + g.N * g.K / 8; /* after the N*K/2 bytes of nibbles */ - const long long kpb = g.K / R4D_W4_KPB; const long long rb = (g.K * 5 + 7) / 8; for (long long nn = 0; nn < g.N; ++nn) { const uint8_t* row = pdata(pl[0]) + nn * rb; for (long long k = 0; k < g.K; ++k) { - const long long bit = k * 5; - uint32_t v = row[bit >> 3]; - if ((bit & 7) > 3) v |= (uint32_t)row[(bit >> 3) + 1] << 8; - const uint32_t q = (v >> (bit & 7)) & 31u; + const uint32_t q = rad_load_bits(row, 5, k); long long w; int nib; w4_slot(g, nn, k, &w, &nib); @@ -527,7 +523,6 @@ extern "C" int r4d_rad_relayout_w5(const RadParam* p, int n_p, int operand, cons hi[hw] |= (q >> 4) << (8 * s + e); } } - (void)kpb; return RAD_OK; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index dec3ecf4..25f30698 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -218,6 +218,8 @@ int r4d_rad_gemm_bf16_tiled (const RadArgs*, RadStream); int r4d_rad_gemm_w4a16_m64 (const RadArgs*, RadStream); 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_gemm_w8a16_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_m64 (const RadArgs*, RadStream); int r4d_rad_gemm_w4a8_tiled (const RadArgs*, RadStream); @@ -325,6 +327,8 @@ 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 1414c920..ac838947 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -704,7 +704,8 @@ static const RadOperandSpec oGemmNt[] = { { "y", RAD_OPD_OUT, 0 }, }; -/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows alone read them: the weight's rows +/* `pb1` and `pb2` are ParoQuant's, and the mxfp4a8 rows and the 4- and 5-bit asymmetric rows (w5a16, + * w4a16_asym, w4a8i8_asym, w5a8i8) read them: the weight's rows * [0, pb1), [pb1, pb2) and [pb2, N) each meet their own copy of the activation, side by side in a * row of `a` (so `a` is [M, parts * K]). 0 leaves a bound out. Optional, and absent from every * other grid: a fused projection whose pieces were not rotated apart has one activation. */ @@ -2345,6 +2346,10 @@ 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_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."), 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 " @@ -2944,6 +2949,12 @@ static const RadConstraint cGemmNtW5[] = { static const RadConstraint cGemmNtW4Asym[] = { C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16_asym"), }; +static const RadConstraint cGemmNtW4A8I8[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8i8_asym"), +}; +static const RadConstraint cGemmNtW5A8I8[] = { + C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a8i8"), +}; static const RadConstraint cGemmNtW2A8[] = { C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w2a8"), }; @@ -4713,6 +4724,30 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, +{ "gemm_w4a8i8_tiled", "gemm_nt_q", "gemm", + "the 4-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (z-lab's ParoQuant int4): " + "int8 WMMA over (code - zero), the weight and activation scales folded per 128 of K", + "N a multiple of 16; K a multiple of 128; the activation scale per (row, 128 of K); weight in the " + "f16 kernel's fragment order; a partitioned weight (pb1/pb2) one launch a part", + "I8 A (parts side by side) with an f32 scale per (row, part, 128), 4-bit W with an f16 scale and " + "integer zero per 128 K, bf16 C, int32 accumulate per 128 of K", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW4A8I8), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_w4a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, + r4d_rad_layout_w4, r4d_rad_relayout_w4, nullptr, nullptr }, + +{ "gemm_w5a8i8_tiled", "gemm_nt_q", "gemm", + "the 5-bit ASYMMETRIC weight x int8 activation GEMM for prefill row counts (ParoQuant int5): int8 " + "WMMA over (code - zero), the weight and activation scales folded per 128 of K", + "N a multiple of 16; K a multiple of 128; the activation scale per (row, 128 of K); weight in the " + "int5 kernel's two planes (nibbles, then fifth bits); a partitioned weight (pb1/pb2) one launch a part", + "I8 A (parts side by side) with an f32 scale per (row, part, 128), 5-bit W with an f16 scale and " + "integer zero per 128 K, bf16 C, int32 accumulate per 128 of K", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY, + ROW(cGemmNtW5A8I8), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_w5a8i8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch, + r4d_rad_layout_w5, r4d_rad_relayout_w5, nullptr, nullptr }, + { "gemm_w8a16_nt_m64", "gemm_nt_q", "gemm", "skinny GEMM with an 8-bit weight, 16x16x16 WMMA, split-K reduced in LDS", "M <= 64; N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, " @@ -5210,6 +5245,18 @@ static const RadKernelInfo kKernels[] = { 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, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_givens_quant_act_i8g_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 ad46b242..2d18e012 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -3741,8 +3741,8 @@ 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) { - const char* row = rot_only ? "givens_rotate" : "givens_quant_act_fp8"; + bool rot_only = false, bool i8 = false) { + const char* row = 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, @@ -3792,7 +3792,7 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_I32, { NPS, K }), T(d_a, RAD_F32, { NPS, K / 2 }), T(d_r, RAD_F32, { (int64_t)parts, K }), - T(d_q, rot_only ? (uint32_t)RAD_F16 : (uint32_t)RAD_F8E4M3, { M, parts * K }), + T(d_q, rot_only ? (uint32_t)RAD_F16 : i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, { M, parts * K }), T(d_s, RAD_F32, { M, parts * ng }), }; if (rot_only) ts.pop_back(); @@ -3835,16 +3835,17 @@ static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, in continue; } const double sc = hs[(size_t)(i * parts * ng + p * ng + g)]; - worst_scale = std::max(worst_scale, std::fabs(sc - amax / 448.0) / (amax / 448.0 + 1e-30)); + const double qmax = i8 ? 127.0 : 448.0; + worst_scale = std::max(worst_scale, std::fabs(sc - amax / qmax) / (amax / qmax + 1e-30)); for (int k = 0; k < G; ++k) { - const double deq = (double)rad_load_f32(hq.data(), RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc; + const double deq = (double)rad_load_f32(hq.data(), i8 ? RAD_I8 : RAD_F8E4M3, i * parts * K + p * K + g * G + k) * sc; worst_val = std::max(worst_val, std::fabs(deq - b[(size_t)(g * G + k)]) / (amax + 1e-30)); } } } char d[96]; 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 < 0.07), d); + ok(nm, rot_only ? worst_val < 1e-3 : (worst_scale < 1e-4 && worst_val < (i8 ? 0.01 : 0.07)), d); } @@ -3956,6 +3957,226 @@ static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int } +/* TIMING OF THE 5/4-BIT GEMM AT ONE PREFILL CHUNK, over the row's tuned axes. `--case w5a16_perf` + * only (it is a measurement, not a check). One weight buffer is replicated past the last-level cache + * and walked in turn, as perf_row does, so the GB/s printed is the weight stream's. */ +static void w5a16_perf(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K) { + if (!g_case || std::strcmp(g_case, "w5a16_perf")) return; + const char* row = bits == 5 ? "gemm_w5a16_nt_m64" : "gemm_w4a16_asym_nt_m64"; + const RadKernelInfo* r = find(pl, row); + if (!r) { std::printf("row absent\n"); return; } + const int64_t G = K / 128; + Planes p; + p.enc = rad_enc_affine(bits == 5 ? RAD_U5 : RAD_U4, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + for (auto& d : p.data[0]) d = (uint8_t)st_mix32((uint32_t)(&d - p.data[0].data())); + for (int64_t i = 0; i < N * G; ++i) { + rad_store_f32(p.data[1].data(), RAD_F16, i, 0.01f); + p.data[2][(size_t)i] = 8; + } + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 5 ? "w5a16" : "w4a16_asym") }; + std::vector wq, ws; + if (stored(r, lp, 2, p, { "codes" }, &wq) != RAD_OK || stored(r, lp, 3, p, { "scale", "zero" }, &ws) != RAD_OK) { + std::printf("relayout failed\n"); + return; + } + const size_t copies = std::max(2, (size_t)(256u << 20) / wq.size() + 1); + void* d_w = dalloc(wq.size() * copies); + void* d_s = dalloc(ws.size() * copies); + void* d_a = dalloc((size_t)(M * K * 2)); + void* d_y = dalloc((size_t)(M * N * 2)); + if (!d_w || !d_s || !d_a || !d_y) { std::printf("hipMalloc failed\n"); return; } + for (size_t c = 0; c < copies; ++c) { + st_memcpy((uint8_t*)d_w + c * wq.size(), wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy((uint8_t*)d_s + c * ws.size(), ws.data(), ws.size(), hipMemcpyHostToDevice); + } + std::printf("%s M=%lld N=%lld K=%lld (weight %.1f MiB)\n", row, (long long)M, (long long)N, + (long long)K, wq.size() / 1048576.0); + struct Cfg { int wv, sk, mb, npw, nt; }; + std::vector cfgs; + for (int sk : { 0, 1, 2, 4, 5, 8 }) + for (int mb : { 0, 1, 2, 4 }) + for (int npw : { 1, 4 }) + for (int wv : { 1, 2, 4 }) cfgs.push_back({ wv, sk, mb, npw, 1 }); + double best = 1e30; + Cfg bc{}; + for (const Cfg& c : cfgs) { + std::vector ts = { + T(d_a, RAD_F16, { M, K }), T(nullptr, RAD_F32, { 1 }), T(d_w, RAD_U8, { (int64_t)wq.size() }), + T(d_s, RAD_U8, { (int64_t)ws.size() }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_F32, { 1 }) }; + absent(ts[1]); absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 5 ? "w5a16" : "w4a16_asym"), + PI("wv", c.wv), PI("sk", c.sk), PI("mb", c.mb), PI("npw", c.npw), + PI("nt", c.nt) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (r->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) continue; + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + st_ev_record(e0, nullptr); + const int iters = 12; + for (int i = 0; i < iters; ++i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wq.size(); + ts[3].data = (uint8_t*)d_s + (size_t)(i % copies) * ws.size(); + 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); + const double us = (double)ms * 1000.0 / iters; + const double tf = 2.0 * M * N * K / (us * 1e6); + std::printf(" wv=%d sk=%d mb=%d npw=%d %9.1f us %6.1f TF/s %6.1f GB/s\n", c.wv, c.sk, c.mb, + c.npw, us, tf, (double)wq.size() / (us * 1e3)); + if (us < best) { best = us; bc = c; } + } + std::printf("best wv=%d sk=%d mb=%d npw=%d: %.1f us\n", bc.wv, bc.sk, bc.mb, bc.npw, best); +} + + +/* THE 4/5-BIT ASYMMETRIC x INT8 PREFILL GEMM against what the planes mean: u4/u5 codes, an f16 scale and + * a u8 zero a 128 of K, an int8 activation with an f32 scale a (row, 128), parts side by side. */ +static void wpa8i8_numeric(const Plugin& pl, int bits, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0, + int64_t pb2 = 0) { + const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; + if (!sel(row)) return; + const int64_t e1 = pb1 > 0 ? std::min(pb1, N) : N; + const int64_t e2 = pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N; + const int parts = e2 < N ? 3 : (e1 < N ? 2 : 1); + auto part_of = [&](int64_t n) { return (int)(n >= e1) + (int)(n >= e2); }; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld parts=%d", row, (long long)M, + (long long)N, (long long)K, parts); + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; } + const int64_t G = K / 128; + Planes p; + p.enc = rad_enc_affine(bits == 4 ? RAD_U4 : RAD_U5, RAD_F16, 1, 128); + rad_enc_add_plane(&p.enc, "zero", RAD_U8, 1, 128); + p.size(N, K); + const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero"); + const int64_t rb = p.row_bytes(ic); + for (int64_t n = 0; n < N; ++n) { + for (int64_t k = 0; k < K; ++k) { + const uint32_t q = st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & ((1u << bits) - 1); + const int64_t bit = k * bits; + uint8_t* b = p.data[(size_t)ic].data() + n * rb + (bit >> 3); + const uint32_t v = q << (bit & 7); + b[0] |= (uint8_t)(v & 0xFF); + if ((bit & 7) > 3) b[1] |= (uint8_t)(v >> 8); + } + for (int64_t g = 0; g < G; ++g) { + const uint32_t h = st_mix32((uint32_t)(n * G + g) ^ 0x2545u); + rad_store_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g, 0.002f * (float)(1 + h % 40)); + p.data[(size_t)iz][(size_t)(n * G + g)] = (uint8_t)((h >> 8) % (1u << bits)); + } + } + std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; + std::vector wq, ws; + const int rw = stored(r, lp, 2, p, { "codes" }, &wq); + const int rs = stored(r, lp, 3, p, { "scale", "zero" }, &ws); + if (rw != RAD_OK || rs != RAD_OK) { + ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs)); + return; + } + const int64_t PK = parts * K, PG = parts * G; + std::vector ha((size_t)(M * PK)); + std::vector av((size_t)(M * PK)), as((size_t)(M * PG)); + for (int64_t i = 0; i < M; ++i) { + for (int64_t c = 0; c < PG; ++c) + as[(size_t)(i * PG + c)] = 0.002f * (float)(1 + st_mix32((uint32_t)(i * PG + c) ^ 0xa5u) % 97); + for (int64_t k = 0; k < PK; ++k) { + const int q8 = (int)(st_mix32((uint32_t)(i * PK + k) ^ 0x3cu) % 255u) - 127; + ha[(size_t)(i * PK + k)] = (uint8_t)(int8_t)q8; + av[(size_t)(i * PK + k)] = (float)q8; + } + } + std::vector hy((size_t)(M * N), 0); + void* d_a = dalloc(ha.size()); + void* d_s = dalloc(as.size() * 4); + void* d_w = dalloc(wq.size()); + void* d_e = dalloc(ws.size()); + void* d_y = dalloc(hy.size() * 2); + if (!d_a || !d_s || !d_w || !d_e || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_I8, { M, PK }), T(d_s, RAD_F32, { M, PG }), + T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }), + T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(nullptr, RAD_F32, { 1 }), + }; + absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") }; + if (pb1) ps.push_back(PI("pb1", pb1)); + if (pb2) ps.push_back(PI("pb2", pb2)); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + a.world_size = 1; + if (r->scratch) { + const int64_t sb = r->scratch(&a); + if (sb > 0) { a.scratch = dalloc((size_t)sb); a.scratch_bytes = sb; } + } + const int rc = r->launch(&a, (RadStream) nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc=" + std::to_string(rc)); return; } + st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost); + const int64_t nstep = N > 96 ? N / 96 : 1; + double num = 0, den = 0; + for (int64_t i = 0; i < M; i += (M > 64 ? 3 : 1)) + for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) { + const int pt = part_of(n); + double acc = 0; + for (int64_t g = 0; g < G; ++g) { + double grp = 0; + const double z = p.data[(size_t)iz][(size_t)(n * G + g)]; + const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + g); + for (int64_t k = g * 128; k < (g + 1) * 128; ++k) { + const int64_t bit = k * bits; + const uint8_t* rowp = p.data[(size_t)ic].data() + n * rb; + uint32_t v = rowp[bit >> 3]; + if ((bit & 7) > 3) v |= (uint32_t)rowp[(bit >> 3) + 1] << 8; + const double q = (v >> (bit & 7)) & ((1u << bits) - 1); + grp += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z); + } + acc += grp * sc * (double)as[(size_t)(i * PG + pt * G + g)]; + } + const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc; + num += d * d; + den += acc * acc; + } + const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num); + char d[96]; + std::snprintf(d, sizeof d, "rel_l2 %.3e", rel); + if (M >= 1024) { // a prefill chunk: say how fast it ran + hipEvent_t e0, e1; + st_ev_create(&e0); st_ev_create(&e1); + st_ev_record(e0, nullptr); + for (int i = 0; i < 10; ++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::snprintf(d, sizeof d, "rel_l2 %.3e, %.0f us, %.1f TF/s", rel, ms * 100.0, + 2.0 * M * N * K / ((double)ms * 100.0 * 1e6)); + std::printf(" %s\n", d); + } + ok(nm, rel < 1e-2, d); +} + + /* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial * is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own * weights, activations and output and a DISJOINT slice of one scratch allocation, with a split @@ -12895,6 +13116,24 @@ static void device_phase(const Plugin& pl) { moe_w4_rot(pl); } + if (g_case && !std::strcmp(g_case, "w5a16_perf")) { + w5a16_perf(pl, 4, 64, 17408, 5120); + w5a16_perf(pl, 4, 64, 5120, 17408); + w5a16_perf(pl, 4, 16, 17408, 5120); + } + for (int bits : { 4, 5 }) { + const char* row = bits == 4 ? "gemm_w4a8i8_tiled" : "gemm_w5a8i8_tiled"; + if (!sel(row)) continue; + if (!g_case) std::printf("\nParoQuant int%d prefill GEMM (int8 WMMA), against the planes' meaning\n", bits); + wpa8i8_numeric(pl, bits, 300, 400, 640); + wpa8i8_numeric(pl, bits, 70, 272, 1280); + wpa8i8_numeric(pl, bits, 300, 400, 640, 192); + wpa8i8_numeric(pl, bits, 600, 512, 2560, 128, 384); + wpa8i8_numeric(pl, bits, 2100, 34816, 5120, 17408); + wpa8i8_numeric(pl, bits, 2048, 17408, 5120); + wpa8i8_numeric(pl, bits, 2048, 5120, 17408); + } + if (sel("gemm_w5a16_nt_m64")) { if (!g_case) std::printf("\nParoQuant's 5-bit GEMM, against the planes' meaning\n"); w5a16_numeric(pl, 8, 272, 640); @@ -12913,6 +13152,14 @@ 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); + } 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); diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 25d21468..d1c03330 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -101,6 +101,7 @@ 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_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); @@ -231,6 +232,7 @@ 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_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 8c79cf04..f0e60573 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -427,7 +427,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { * 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) { +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; @@ -475,12 +475,14 @@ static int givens_body(const RadArgs* a, bool quant) { const float m = std::fabs(buf[(size_t)(k0 + i)]); if (m > amax) amax = m; } - const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f; + const float 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 > 448.0f) v = 448.0f; - if (v < -448.0f) v = -448.0f; + 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); @@ -491,6 +493,7 @@ static int givens_body(const RadArgs* a, bool quant) { } 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 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). */ diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index eb83a176..56debdd1 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -811,6 +811,10 @@ 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_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 " "pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight whose GEMM " @@ -1184,6 +1188,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_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 7aa5d46c..d631961b 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -836,6 +836,10 @@ 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_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 df1fab70..c33ab599 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_rotate", "had_quant_act_i8", + "quant_act_i8", "quant_act_fp8", "had_quant_act_fp8", "givens_quant_act_fp8", "givens_quant_act_i8g", "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". */