Archived
Rotated Qwen3.8-27B checkpoints: ParoQuant MXFP4, int5 bit-plane and z-lab's int4 import (the givens
transform with parts, per-row scales, zero points), the w5a16/w4a16_asym decode GEMMs, the
w4a8i8/w5a8i8 prefill band, the givens_rotate kernel, and the dense per-group rotation
(givens_dense_quant: one 128x128 f16 matrix a part and group on the matrix cores) for the quantising
rotation in prefill. gemm_nt_q gains part bounds (pb1/pb2), an op-schema change an out-of-tree
kernel library has to follow.
Fixes on top: the dense matrices are a container table ("t.dense") that rad-convert composes in f64
from the pairs and angles, and the loader only moves its bits. A container converted before this is
refused at load, naming the re-convert (--reuse copies every unchanged weight). A gemm_nt_q row that
does not read part bounds refuses them instead of ignoring them. libavx implements givens_rotate and
givens_dense_quant.
This commit is contained in:
commit
f6a9467cb5
40 files changed
+4206
-143
No files matched your search
@@ -114,6 +114,9 @@ set(R4D_UNITS
|
||||
"r4d_gemm_bf16_nt_m64|"
|
||||
"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_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}"
|
||||
@@ -130,6 +133,7 @@ set(R4D_UNITS
|
||||
"r4d_gemm_fp8a16_nt_m1|"
|
||||
"r4d_gemm_fp8a8|"
|
||||
"r4d_quant_act_fp8|"
|
||||
"r4d_givens_rotate|"
|
||||
"r4d_fused_quant_fp8|"
|
||||
"r4d_gram_accum_fp8|"
|
||||
"r4d_qsa_block_key_bf16|"
|
||||
|
||||
+6
-3
@@ -592,7 +592,8 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i
|
||||
// as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs.
|
||||
void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW,
|
||||
int as_group, int as_rs, long stream);
|
||||
int as_group, int as_rs, long stream,
|
||||
int lda = 0, int ldws = 0, int ldc = 0);
|
||||
int r4d_gemm_mxfp4a8_nt_m64_max_m(void);
|
||||
int r4d_gemm_mxfp4a8_nt_m64_group(void);
|
||||
// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a
|
||||
@@ -601,8 +602,10 @@ int r4d_gemm_mxfp4a8_nt_m64_group(void);
|
||||
// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row,
|
||||
// 128 = one per (row, 128 of K) at row stride as_rs.
|
||||
void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs, long stream);
|
||||
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream);
|
||||
int M, int K, int N, int TN, int as_group, int as_rs, long stream,
|
||||
int ldws = 0, int ldc = 0);
|
||||
// `lda` is the activation's row pitch in bytes (0 = K), for a window of a wider plane.
|
||||
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0);
|
||||
long r4d_mxfp4a8_tile_a_bytes(int M, int K);
|
||||
int r4d_gemm_mxfp4a8_tiled_group(void);
|
||||
// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's
|
||||
|
||||
@@ -45,6 +45,9 @@ enum { FP8_OPS_BLOCK_SCALE = 0, FP8_OPS_ROW_SCALE = 1 };
|
||||
static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
|
||||
int wscale = FP8_OPS_BLOCK_SCALE) {
|
||||
std::memset(g, 0, sizeof(*g));
|
||||
/* No fp8 or int8 block GEMM reads a partitioned weight's `pb1`/`pb2`; refused, not ignored (see
|
||||
* gemm_ops). */
|
||||
if (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0) return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
g->a = r4d_opt(a, F_A);
|
||||
g->ascale = r4d_opt(a, F_ASCALE);
|
||||
g->b = r4d_opt(a, F_B);
|
||||
|
||||
+69
-4
@@ -326,7 +326,7 @@ struct GemmOps {
|
||||
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
|
||||
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
|
||||
* at the wrong width is an answer that is merely wrong. */
|
||||
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
|
||||
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs, int parts = 1) {
|
||||
const RadTensor* s = g.ascale;
|
||||
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
long long cols = 1, rstride = 1;
|
||||
@@ -340,18 +340,83 @@ static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
|
||||
rstride = cols;
|
||||
}
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
|
||||
if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; }
|
||||
/* PARTS: the activation's copies sit side by side in a row, so its scale row is `parts` times
|
||||
* as long; each part reads its own kb of them at the row stride. */
|
||||
if (parts == 1 && cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
|
||||
if (cols == kb * parts && rstride >= kb * parts) { *group = 128; *rs = (int)rstride; return RAD_OK; }
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* THE PARTS OF A PARTITIONED MXFP4 WEIGHT (gemm_nt_q's `pb1`/`pb2`), as launches.
|
||||
*
|
||||
* A fused projection whose pieces were rotated apart (ParoQuant: gate|up, q|k|v) has one copy of
|
||||
* the activation a piece, written side by side in a row of `a` -- [M, parts * K] -- and its scales
|
||||
* the same, so the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet THEIR copy. A part is
|
||||
* then the ordinary product over a window of the planes: the activation from byte p * K of each row
|
||||
* and its scales from p * ceil(K/128), the fragment-order weight from tile n0 / 16 (its bytes are
|
||||
* n0 * K / 2 in), the exponents and reference from column n0, the output from column n0, the last
|
||||
* three with the full planes' row pitch. So the kernels learn only row pitches (`lda`, `ldws`,
|
||||
* `ldc`) and a part is one launch of the kernel the shape would have picked anyway.
|
||||
*
|
||||
* `pb1` = 0 is one part and `pb2` = 0 ends the second part at N, as libref reads them. Bounds are
|
||||
* whole 16-row tiles (the weight's fragment unit). Returns the parts in `p`, K corrected to the
|
||||
* op's own (gemm_ops read the row's width, which is parts * K), and the activation's row pitch in
|
||||
* `lda`. */
|
||||
struct MxParts {
|
||||
int n = 1;
|
||||
long long n0[3] = { 0, 0, 0 }, n1[3] = { 0, 0, 0 };
|
||||
long long lda = 0; /* 0: the plane's own K */
|
||||
};
|
||||
|
||||
/* The bounds `pb1`/`pb2` name over N rows, as every reader takes them: { 0, e1, e2, N }, part i
|
||||
* being [bound[i], bound[i+1]). Returns how many copies of the activation they imply, 1..3. */
|
||||
static inline int mx_part_bounds(long long N, long long pb1, long long pb2, long long bound[4]) {
|
||||
const long long e1 = pb1 > 0 && pb1 < N ? pb1 : N;
|
||||
long long e2 = pb2 > 0 && pb2 < N ? pb2 : N;
|
||||
if (e2 < e1) e2 = e1;
|
||||
bound[0] = 0;
|
||||
bound[1] = e1;
|
||||
bound[2] = e2;
|
||||
bound[3] = N;
|
||||
return e2 < N ? 3 : (e1 < N ? 2 : 1);
|
||||
}
|
||||
|
||||
static inline int mx_parts(const RadArgs* a, GemmOps* g, MxParts* p) {
|
||||
p->n = 1;
|
||||
p->n0[0] = 0;
|
||||
p->n1[0] = g->N;
|
||||
p->lda = 0;
|
||||
long long bound[4];
|
||||
const int segs = mx_part_bounds(g->N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
|
||||
if (segs == 1) return RAD_OK;
|
||||
const long long K = r4d_geti_or(a, "K", 0);
|
||||
if (K <= 0) return R4D_NO(RAD_E_INVAL);
|
||||
if (g->K != (long long)segs * K || (bound[1] % 16) || (bound[2] % 16)) return R4D_NO(RAD_E_SHAPE);
|
||||
p->n = 0;
|
||||
for (int i = 0; i < 3; ++i)
|
||||
if (bound[i + 1] > bound[i]) {
|
||||
p->n0[p->n] = bound[i];
|
||||
p->n1[p->n] = bound[i + 1];
|
||||
++p->n;
|
||||
}
|
||||
if (p->n != segs) return R4D_NO(RAD_E_SHAPE); /* an empty middle part has no copy to meet */
|
||||
p->lda = g->K;
|
||||
g->K = K;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
|
||||
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
|
||||
* checked here beyond being present, which is deliberate: the byte count that matters is the one
|
||||
* rad-convert wrote from RadLayout.bytes, and re-deriving it from N and K would be a second
|
||||
* source for one number. */
|
||||
static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised) {
|
||||
/* `parts`: the caller reads a partitioned weight's `pb1`/`pb2` (mx_parts). Any other row REFUSES them
|
||||
* rather than ignore them -- a part bound it does not apply would multiply every row of the weight by
|
||||
* the first copy of the activation. */
|
||||
static inline int gemm_ops(const RadArgs* a, GemmOps* g, int quantised, int parts = 0) {
|
||||
std::memset(g, 0, sizeof(*g));
|
||||
if (quantised && !parts && (r4d_geti_or(a, "pb1", 0) > 0 || r4d_geti_or(a, "pb2", 0) > 0))
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
if (quantised) {
|
||||
g->a = r4d_opt(a, Q_A);
|
||||
g->ascale = r4d_opt(a, Q_ASCALE);
|
||||
|
||||
@@ -119,8 +119,8 @@ template <int DTM, int DKS, bool ABLK>
|
||||
static __device__ __forceinline__ void mxd_epilogue(
|
||||
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks,
|
||||
int kb_end, unsigned* s_last, float* sR) {
|
||||
__hip_bfloat16* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8,
|
||||
int ks, int kb_end, unsigned* s_last, float* sR) {
|
||||
constexpr int NTHR = R4D_MXD_DWN * 32, BND = R4D_MXD_DWN * 16;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
const int tid = threadIdx.x;
|
||||
@@ -155,7 +155,7 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
o.y = bf16x2_rne_nan(v[2], v[3]);
|
||||
o.z = bf16x2_rne_nan(v[4], v[5]);
|
||||
o.w = bf16x2_rne_nan(v[6], v[7]);
|
||||
*(mxd_u4*)(C + (size_t)m * N + nb) = o;
|
||||
*(mxd_u4*)(C + (size_t)m * ldc + nb) = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ static __device__ __forceinline__ void mxd_epilogue(
|
||||
float sum = 0.f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
|
||||
C[(size_t)m * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
|
||||
C[(size_t)m * ldc + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,7 +220,8 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int lda, int ldws,
|
||||
int ldc) {
|
||||
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
constexpr int STR = DBK + R4D_MXD_PAD;
|
||||
@@ -266,7 +267,7 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
|
||||
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
|
||||
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
|
||||
}
|
||||
}
|
||||
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
|
||||
@@ -290,7 +291,7 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * N + gc + q]);
|
||||
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
|
||||
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
|
||||
@@ -323,7 +324,7 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
@@ -340,7 +341,8 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs, int lda, int ldws,
|
||||
int ldc) {
|
||||
constexpr int DTM = 1, VEC = 4;
|
||||
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_MXD_MTILE * DTM;
|
||||
@@ -403,7 +405,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1;
|
||||
ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
|
||||
ra[j] = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
|
||||
}
|
||||
}
|
||||
const int kstep0 = k0 / 16;
|
||||
@@ -414,7 +416,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
rw[it] = mxd_ld<NT>((const wv_t*)&Wp[slot]);
|
||||
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * N + s_gc[it] + q];
|
||||
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q];
|
||||
}
|
||||
};
|
||||
auto store = [&]() {
|
||||
@@ -472,7 +474,7 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
|
||||
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
@@ -530,7 +532,7 @@ long mxd_partial_bytes(int M, int N, int ks) {
|
||||
|
||||
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
|
||||
int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
|
||||
long scratch_bytes) {
|
||||
long scratch_bytes, int lda, int ldws, int ldc) {
|
||||
if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128");
|
||||
if (N < 16 || N % 16 || N > R4D_MXD_MAX_N)
|
||||
@@ -565,10 +567,10 @@ void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M,
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
#define MXD_L(BK_, KS_, TM_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
|
||||
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
|
||||
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
|
||||
#define MXD_L1(BK_, KS_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
|
||||
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
|
||||
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
|
||||
#define MXD_AB(BK_, KS_, TM_, NT_) \
|
||||
{ if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); }
|
||||
#define MXD_NT(BK_, KS_, TM_) \
|
||||
@@ -602,38 +604,58 @@ extern "C" int r4d_gemm_mxfp4a8_decode_max_m(void) { return R4D_MXD_MTILE * R4D_
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.M > r4d_gemm_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
R4D_TRY("gemm_mxfp4a8_decode",
|
||||
mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt, as_group, as_rs,
|
||||
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes));
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
R4D_TRY("gemm_mxfp4a8_decode",
|
||||
mxd_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
|
||||
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
|
||||
r4d_addr(g.bref) + n0, r4d_addr(g.y) + n0 * 2,
|
||||
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
|
||||
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
|
||||
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
|
||||
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
|
||||
* band times its widest M -- an upper bound on every launch the band can make. */
|
||||
* band times its widest M -- an upper bound on every launch the band can make. A partitioned
|
||||
* weight launches each part at ITS rows, which splits wider than the whole would, so the bound is
|
||||
* the largest of the parts' (they run one after another and share the scratch). */
|
||||
extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
|
||||
const long long K = r4d_geti_or(a, "K", 0);
|
||||
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_mxfp4a8_decode_max_m()) return 0;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
int ks = 1;
|
||||
for (int m = 1; m <= (int)M; ++m) {
|
||||
const int k = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
|
||||
if (k > ks) ks = k;
|
||||
long long bound[4];
|
||||
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
|
||||
int64_t worst = 0;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const long long np = bound[i + 1] - bound[i];
|
||||
if (np < 16) continue;
|
||||
int ks = 1;
|
||||
for (int m = 1; m <= (int)M; ++m) {
|
||||
const int k = mxd_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
|
||||
if (k > ks) ks = k;
|
||||
}
|
||||
const int64_t b = (int64_t)mxd_partial_bytes((int)M, (int)np, ks);
|
||||
if (b > worst) worst = b;
|
||||
}
|
||||
return (int64_t)mxd_partial_bytes((int)M, (int)N, ks);
|
||||
return worst;
|
||||
}
|
||||
@@ -115,7 +115,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int WV, int SK, int as_rs) {
|
||||
int M, int K, int N, int WV, int SK, int as_rs, int lda, int ldws, int ldc) {
|
||||
extern __shared__ float red[];
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
@@ -189,7 +189,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
for (int i = 0; i < MT; i++) {
|
||||
int r = (mt0 + i) * 16 + nlane;
|
||||
r = r < M - 1 ? r : M - 1;
|
||||
const unsigned int* pa = (const unsigned int*)(A + (size_t)r * K + kg + mhalf);
|
||||
const unsigned int* pa = (const unsigned int*)(A + (size_t)r * lda + kg + mhalf);
|
||||
af[i][0] = (int)pa[0];
|
||||
af[i][1] = (int)pa[1];
|
||||
}
|
||||
@@ -200,7 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
|
||||
// apart -- a fully strided read on the operand that dominates traffic.
|
||||
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
|
||||
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n]));
|
||||
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * ldws + n]));
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]);
|
||||
@@ -232,7 +232,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
|
||||
if (n >= N || m >= M) continue;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
C[(size_t)m * N + n] =
|
||||
C[(size_t)m * ldc + n] =
|
||||
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m]));
|
||||
}
|
||||
}
|
||||
@@ -243,7 +243,14 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP
|
||||
|
||||
extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int WV, int SK, int MB, int NPW,
|
||||
int as_group, int as_rs, long stream) {
|
||||
int as_group, int as_rs, long stream,
|
||||
int lda, int ldws, int ldc) {
|
||||
// The operands of one PART of a partitioned weight (ParoQuant) are windows of larger planes:
|
||||
// the activation a row of lda bytes, the exponents a row of ldws, the output a row of ldc.
|
||||
// 0 is the plane's own width, which is every other caller.
|
||||
if (!lda) lda = K;
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
|
||||
@@ -273,9 +280,10 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
#define LAUNCH(MTv, NPv) \
|
||||
do { \
|
||||
if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, lda, ldws, ldc); \
|
||||
else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
|
||||
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs, \
|
||||
lda, ldws, ldc); \
|
||||
} while (0)
|
||||
#define LAUNCH_MB(NPv) switch (MB) { \
|
||||
case 1: LAUNCH(1, NPv); break; \
|
||||
@@ -300,7 +308,7 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
|
||||
// is no adapter directory between the core and these launches.
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.M > r4d_gemm_mxfp4a8_nt_m64_max_m()) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -309,18 +317,27 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
|
||||
* so gemm_nt_q carries it as a trailing optional weight operand. Without it the fold has no
|
||||
* reference and every element would be scaled against zero. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const int group = r4d_gemm_mxfp4a8_nt_m64_group();
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
R4D_TRY("gemm_mxfp4a8_nt_m64",
|
||||
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
|
||||
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
|
||||
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
|
||||
as_group, as_rs, (long)(uintptr_t)s));
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
R4D_TRY("gemm_mxfp4a8_nt_m64",
|
||||
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a) + p * g.K,
|
||||
r4d_addr(g.ascale) + (long)(p * kb * 4),
|
||||
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
|
||||
r4d_addr(g.bref) + n0, r4d_addr(g.y) + n0 * 2,
|
||||
(int)g.M, (int)g.K, (int)np, c.wv, c.sk, c.mb, c.npw,
|
||||
as_group, as_rs, (long)(uintptr_t)s,
|
||||
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ static __device__ __forceinline__ void mxt_lds_barrier() {
|
||||
// contiguous and each lane reads one 8-byte group of one row.
|
||||
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
|
||||
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
|
||||
long long slots) {
|
||||
long long slots, int lda) {
|
||||
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
|
||||
if (o >= slots) return;
|
||||
const int ks = K / 16;
|
||||
@@ -110,7 +110,7 @@ __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
|
||||
const int mt = (int)(f / ks), kst = (int)(f % ks);
|
||||
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
|
||||
mxt_u2 v = { 0u, 0u };
|
||||
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k);
|
||||
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * lda + k);
|
||||
*(mxt_u2*)(AT + o * 8) = v;
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs) {
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
|
||||
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
@@ -213,14 +213,14 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const mxt_u4 v = *(const mxt_u4*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
|
||||
wsw = *(const unsigned int*)(Ws + (size_t)blk * N + wrc[it]);
|
||||
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const mxt_u2 v = *(const mxt_u2*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1];
|
||||
wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]);
|
||||
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else {
|
||||
wq[0] = *src;
|
||||
wsw = Ws[(size_t)blk * N + wrc[it]];
|
||||
wsw = Ws[(size_t)blk * ldws + wrc[it]];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int q = 0; q < WSLOTS; ++q) {
|
||||
@@ -312,7 +312,7 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
o.y = bf16x2_rne_nan(v[2], v[3]);
|
||||
o.z = bf16x2_rne_nan(v[4], v[5]);
|
||||
o.w = bf16x2_rne_nan(v[6], v[7]);
|
||||
*(mxt_u4*)(C + (size_t)m * N + nb) = o;
|
||||
*(mxt_u4*)(C + (size_t)m * ldc + nb) = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,17 +323,20 @@ extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
|
||||
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
|
||||
}
|
||||
|
||||
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) {
|
||||
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) {
|
||||
if (!lda) lda = K;
|
||||
if (M < 1) throw std::runtime_error("r4d mxfp4a8_tile_a: M must be >= 1");
|
||||
if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16");
|
||||
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
|
||||
hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0,
|
||||
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots);
|
||||
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots, lda);
|
||||
}
|
||||
|
||||
extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs,
|
||||
long stream) {
|
||||
long stream, int ldws, int ldc) {
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1");
|
||||
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
|
||||
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
|
||||
@@ -361,7 +364,7 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define MXT_LAUNCH(TNv, LBKv, ABv) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
|
||||
Wp, Zp, Rp, Cp, M, K, N, as_rs)
|
||||
Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
|
||||
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
|
||||
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
|
||||
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
|
||||
@@ -370,34 +373,46 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
|
||||
// A partitioned weight re-tiles each part's copy of the activation into the scratch in turn and
|
||||
// runs the GEMM over that part's rows (mx_parts).
|
||||
extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1);
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
|
||||
/* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
|
||||
* reference and every element would be scaled against zero. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K))
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
if (g.K % R4D_MXT_KUNIT) 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;
|
||||
const long long slab = r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K);
|
||||
if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL);
|
||||
R4dMxTileCfg t;
|
||||
r4d_cfg_mxfp4_tiled(a, &t);
|
||||
const long kb = (long)((g.K + 127) / 128);
|
||||
const long at = (long)(uintptr_t)a->scratch;
|
||||
R4D_TRY("gemm_mxfp4a8_tiled",
|
||||
r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s);
|
||||
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
|
||||
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
|
||||
t.tn, as_group, as_rs, (long)(uintptr_t)s));
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
R4D_TRY("gemm_mxfp4a8_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));
|
||||
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4, r4d_addr(g.b) + n0 * g.K / 2,
|
||||
r4d_addr(g.bscale) + n0, r4d_addr(g.bref) + n0,
|
||||
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
|
||||
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
|
||||
* the activation, whole 16-row fragments. */
|
||||
* the activation, whole 16-row fragments. One copy for every part: the parts run one after another
|
||||
* on the op's stream, so a part's re-tile cannot overtake the previous part's GEMM. */
|
||||
extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
|
||||
return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K);
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// r4d_gemm_w5a16_nt_m64.hip - r4d_gemm_w5a16_nt_m64: 5-bit-weight skinny GEMM for M up to 64,
|
||||
// gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, f16 A, bf16 C, fp32 accumulate.
|
||||
//
|
||||
// r4d_gemm_w4a16_nt_m64 with a fifth bit per weight, for ParoQuant's int5 (asymmetric, an f16 scale
|
||||
// and a 5-bit integer zero per 128 of K, the rotation done on the activation in front of it). The
|
||||
// reading of that kernel's header holds word for word -- weight-streaming, memory-bound, f16
|
||||
// because 1024 + n is exact -- and this file only says what the fifth bit changes.
|
||||
//
|
||||
// THE WEIGHT BLOB IS TWO PLANES. The low four bits of every code are w4's fragment order exactly
|
||||
// (offset binary here: the nibble is q & 15, no sign flip). The fifth bits follow as a second
|
||||
// plane of 32-bit words, ONE A (n-tile, 64-wide k block, lane):
|
||||
//
|
||||
// hi[(t * (K/64) + kb) * 32 + lane] byte s = k step s of the block, bit e = element e
|
||||
//
|
||||
// element e of a lane's fragment being the same one nibble 2e / 2(e-4)+1 of dword s holds. So a
|
||||
// lane's 16 bytes of nibbles and its 4 bytes of fifth bits cover the same 32 weights, and the
|
||||
// second load is one dword a block.
|
||||
//
|
||||
// THE UNPACK ADDS TWO MULTIPLIES TO w4's. The even elements' fifth bits are the byte's low nibble,
|
||||
// the odd elements' its high one; a 4-bit mask n becomes one bit a byte by n * 0x00204081 (bit j
|
||||
// lands at 8j and nothing else lands on a multiple of eight below bit 32), masked with 0x01010101
|
||||
// and shifted to the 16s place of the nibble's byte. The 5-bit code is then 0..31, 1024 + q is
|
||||
// exact in f16, and the zero point -- an integer 0..31 in the scale dword's high half as
|
||||
// -(1024 + zero) -- subtracts exactly.
|
||||
//
|
||||
// The dispatcher takes M past 64 as chunks of 64 rows (the weight is re-read per chunk, which at a
|
||||
// 2048-row prefill chunk is near the compute bound of the f16 matrix instruction anyway), and
|
||||
// partitioned weights (ParoQuant's gate|up: `pb1`/`pb2`, see r4d_gemm_args.h) as one launch per
|
||||
// part over windows of the planes.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_GEMM_W4_MAX_M 64
|
||||
#ifndef R4D_GEMM_W4_GROUP
|
||||
#define R4D_GEMM_W4_GROUP 128 // K per (scale, zero) pair
|
||||
#endif
|
||||
#define R4D_GEMM_W4_KPB 64 // K per packed block: 4 k steps, 16 bytes per lane
|
||||
#define WAVE32 32
|
||||
|
||||
typedef _Float16 v8h __attribute__((ext_vector_type(8)));
|
||||
typedef unsigned uint4v __attribute__((ext_vector_type(4)));
|
||||
|
||||
// NT reads the weight non-temporally. The weight is streamed once per step and never reused, while
|
||||
// the activation is re-read once per column tile and wants to stay resident, so telling the cache
|
||||
// not to keep the weight decides which of the two occupies the last level. It is a gain at M=8 and
|
||||
// M=16 and a LOSS from M=24 up on the shapes with the longest K, so it is per-call, like every
|
||||
// other geometry parameter, and the table in radiance_w4.py carries the value per M band.
|
||||
//
|
||||
// One copy of any of these weights fits this part's 64 MiB last level, so a bench that streams a
|
||||
// SINGLE buffer in a loop measures a cache-resident machine and cannot see this effect at all; a
|
||||
// pooled working set is what makes the difference visible.
|
||||
|
||||
// NPW (column tiles per WAVE) is a template parameter because it sizes the accumulator array, and a
|
||||
// launch argument because the right value is a property of M: at M=8 the kernel is at the DRAM
|
||||
// roofline and NPW>1 only costs blocks, while at M=64 the activation re-read is four times the
|
||||
// weight and NPW=4 is what claws it back. Instantiated only for the two values that win in
|
||||
// practice; anything else is rejected rather than silently rounded.
|
||||
|
||||
// Address-space-qualified so the loads stay global_load rather than flat_load: on gfx12 a flat
|
||||
// load increments dscnt as well as loadcnt, so a later LDS wait would also wait on HBM. See the
|
||||
// same declaration in r4d_gemm_bf16_nt_m64.hip for why the element type is a scalar there.
|
||||
typedef __attribute__((address_space(1))) const uint4v* r4d_gw4;
|
||||
typedef __attribute__((address_space(1))) const unsigned long long* r4d_gu2;
|
||||
typedef __attribute__((address_space(1))) const unsigned* r4d_gu1;
|
||||
|
||||
__device__ __forceinline__ v8h fragA(r4d_gu2 p, int u) {
|
||||
union { unsigned long long w[2]; v8h f; } x;
|
||||
x.w[0] = p[4 * u];
|
||||
x.w[1] = p[4 * u + 2];
|
||||
return x.f;
|
||||
}
|
||||
|
||||
// DO NOT FOLD THE GROUP SCALE INTO THE B FRAGMENT. One v_pk_mul_f16 per pair on the finished
|
||||
// integer q is exact in f16, removes the second accumulator array entirely and takes the M=64 shape
|
||||
// from 192 VGPRs to 135 -- and it is SLOWER on most of the drafter's shapes. The multiply lands
|
||||
// inside the per-fragment dependent chain between the unpack and the WMMA, where the per-group
|
||||
// epilogue it replaces sits outside it; this kernel is stall-bound, not register-bound.
|
||||
|
||||
// One dword of eight nibbles plus the byte of their fifth bits -> one 16x16x16 f16 B fragment,
|
||||
// minus the zero point. Nibble 2e (e < 4) / 2(e-4)+1 is fragment element e, so bits 0..3 of `hb`
|
||||
// are the fifth bits of the even nibbles' elements and bits 4..7 the odd nibbles'. Each v_perm_b32
|
||||
// pairs two code bytes with the constant high byte 0x64, the f16 exponent field for 1024, so a half
|
||||
// is 1024 + code; nz carries -(1024 + zero) in BOTH halves, so one v_pk_add_f16 corrects a pair.
|
||||
// The codes are offset binary (0..31, or 0..15 without the fifth bit): no sign flip.
|
||||
__device__ __forceinline__ unsigned spread16(unsigned n) { // 4 bits -> bit 4 of each byte
|
||||
return ((n * 0x00204081u) & 0x01010101u) << 4;
|
||||
}
|
||||
__device__ __forceinline__ v8h dequant5(unsigned w, unsigned hb, __half2 nz) {
|
||||
const unsigned K64 = 0x64646464u;
|
||||
const unsigned t0 = (w & 0x0F0F0F0Fu) | spread16(hb & 15u);
|
||||
const unsigned t1 = ((w >> 4) & 0x0F0F0F0Fu) | spread16(hb >> 4);
|
||||
union { unsigned u[4]; __half2 h2[4]; v8h f; } x;
|
||||
x.u[0] = __builtin_amdgcn_perm(K64, t0, 0x05010400u); // elements 0, 1
|
||||
x.u[1] = __builtin_amdgcn_perm(K64, t0, 0x05030402u); // elements 2, 3
|
||||
x.u[2] = __builtin_amdgcn_perm(K64, t1, 0x05010400u); // elements 4, 5
|
||||
x.u[3] = __builtin_amdgcn_perm(K64, t1, 0x05030402u); // elements 6, 7
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; i++) x.h2[i] = __hadd2(x.h2[i], nz);
|
||||
return x.f;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ v8f mmah(v8h a, v8h b, v8f c) {
|
||||
return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
|
||||
}
|
||||
|
||||
// MT = row tiles per BLOCK, as in the bf16 kernel: more of them amortise the weight fragment and
|
||||
// its unpack over more WMMA, fewer put more blocks on the machine.
|
||||
// HI false is the 4-bit asymmetric grid (z-lab's plain int4): the same kernel with no fifth-bit plane.
|
||||
template <int MT, int NPW, bool NT, bool HI>
|
||||
__global__ __launch_bounds__(1024) void r4d_gemm_w5a16_nt_m64_kernel(
|
||||
const unsigned short* __restrict__ A, const unsigned* __restrict__ Wq,
|
||||
const unsigned* __restrict__ Whi, const unsigned* __restrict__ Wsz,
|
||||
__hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK, int lda, int ldc) {
|
||||
extern __shared__ float red[]; // WV*NPW*SK*256 floats: a 16x16 tile per (column, split)
|
||||
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
|
||||
const int col_local = wave / SK, ksplit = wave % SK;
|
||||
const int nt0 = (blockIdx.x * WV + col_local) * NPW;
|
||||
const int n0 = nt0 * 16;
|
||||
const int mt0 = blockIdx.y * MT;
|
||||
const int Ks = K / SK;
|
||||
const int groups = Ks / R4D_GEMM_W4_GROUP; // groups this split owns
|
||||
const int kbase = ksplit * Ks;
|
||||
|
||||
v8f acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) acc[j][i] = (v8f)(0.f);
|
||||
|
||||
if (n0 < N) {
|
||||
// Activation: rows clamped, never masked -- a tile past M re-reads the last valid row and
|
||||
// computes a result nobody stores.
|
||||
unsigned aoff[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
aoff[i] = rowGo((unsigned)lda, (mt0 + i) * 16, M - 1, lane) + (unsigned)kbase;
|
||||
r4d_gu2 pa[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] = (r4d_gu2)(const unsigned long long*)(A + aoff[i]);
|
||||
|
||||
// Weight: one uint4 per lane per four k steps, tiles already permuted, so the whole k loop is
|
||||
// global_load_b128 with a constant stride and no address arithmetic per step.
|
||||
const int kpb = K / R4D_GEMM_W4_KPB; // packed blocks in a full row of tiles
|
||||
const int nsz = K / R4D_GEMM_W4_GROUP; // (scale, zero) dwords per row of tiles
|
||||
r4d_gw4 pw[NPW];
|
||||
r4d_gu1 ph[NPW];
|
||||
r4d_gu1 ps[NPW];
|
||||
const int ntlast = N / 16 - 1;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
// Clamped, like the row tiles: a wave whose last column tiles run past N re-reads the last
|
||||
// real tile and computes a result the store discards, rather than reading memory it does not
|
||||
// own or diverging the whole k loop on a mask.
|
||||
const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast;
|
||||
pw[j] = (r4d_gw4)(const uint4v*)(Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
// Quantizer parameters: 16 distinct dwords per group, read by the 16 lanes that own the rows.
|
||||
ph[j] = (r4d_gu1)(const unsigned*)(HI ? Whi : Wq) +
|
||||
(size_t)(t * kpb + kbase / R4D_GEMM_W4_KPB) * WAVE32 + lane;
|
||||
ps[j] = (r4d_gu1)(const unsigned*)(Wsz) +
|
||||
(size_t)(t * nsz + kbase / R4D_GEMM_W4_GROUP) * 16 + (lane & 15);
|
||||
}
|
||||
|
||||
const int bpg = R4D_GEMM_W4_GROUP / R4D_GEMM_W4_KPB; // packed blocks per group
|
||||
|
||||
for (int g = 0; g < groups; g++) {
|
||||
float sc[NPW];
|
||||
__half2 nz[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const unsigned sz = ps[j][(size_t)g * 16];
|
||||
sc[j] = __half2float(__ushort_as_half((unsigned short)(sz & 0xFFFFu)));
|
||||
nz[j] = __half2half2(__ushort_as_half((unsigned short)(sz >> 16)));
|
||||
}
|
||||
|
||||
// The first WMMA of a group takes an inline zero for C, so the group accumulator costs no
|
||||
// instruction to clear.
|
||||
v8f g_acc[NPW][MT];
|
||||
#pragma unroll
|
||||
for (int b = 0; b < bpg; b++) {
|
||||
uint4v wv[NPW];
|
||||
unsigned hv[NPW];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const size_t o = (size_t)(g * bpg + b) * WAVE32;
|
||||
wv[j] = NT ? __builtin_nontemporal_load(&pw[j][o]) : pw[j][o];
|
||||
hv[j] = HI ? (NT ? __builtin_nontemporal_load(&ph[j][o]) : ph[j][o]) : 0u;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 4; s++) {
|
||||
const int u = b * 4 + s;
|
||||
v8h afrag[MT];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) afrag[i] = fragA(pa[i], u); // loaded once, spent NPW times
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const v8h bfrag = dequant5(wv[j][s], (hv[j] >> (8 * s)) & 0xFFu, nz[j]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
g_acc[j][i] = u == 0 ? mmah(afrag[i], bfrag, (v8f)(0.f))
|
||||
: mmah(afrag[i], bfrag, g_acc[j][i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) acc[j][i][e] = fmaf(g_acc[j][i][e], sc[j], acc[j][i][e]);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) pa[i] += (R4D_GEMM_W4_GROUP / 16) * 4;
|
||||
}
|
||||
}
|
||||
|
||||
// Split-K reduction and store: identical to r4d_gemm_bf16_nt_m64, one row tile at a time so the
|
||||
// LDS is WV*SK KiB whatever MT is, and in a fixed order over splits so the result does not depend
|
||||
// on how the waves were scheduled.
|
||||
const int ncols = WV * NPW;
|
||||
const int nthreads = WV * SK * WAVE32;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < MT; i++) {
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NPW; j++) {
|
||||
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; e++) red[slot + e * WAVE32 + lane] = acc[j][i][e];
|
||||
}
|
||||
__syncthreads();
|
||||
for (int idx = tid; idx < ncols * 256; idx += nthreads) {
|
||||
const int col = idx >> 8, off = idx & 255;
|
||||
float v = 0.f;
|
||||
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
|
||||
const int l = off & 31;
|
||||
const int n = (blockIdx.x * ncols + col) * 16 + (l & 15);
|
||||
const int m = (mt0 + i) * 16 + 8 * (l >> 4) + (off >> 5);
|
||||
if (n < N && m < M) C[(size_t)m * ldc + n] = (__hip_bfloat16)v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void r4d_gemm_w5a16_nt_m64(long a, long wq, long whi, long wsz, long c, int M, int K, int N,
|
||||
int WV, int SK, int MB, int NPW, int NT, long stream, int lda, int ldc,
|
||||
bool hi5) {
|
||||
if (!lda) lda = K;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1 || M > R4D_GEMM_W4_MAX_M)
|
||||
throw std::runtime_error("r4d gemm_w5a16_nt_m64: M must be 1..64");
|
||||
if (N % 16) throw std::runtime_error("r4d gemm_w5a16_nt_m64: N must be a multiple of 16");
|
||||
if (K % (SK * R4D_GEMM_W4_GROUP))
|
||||
throw std::runtime_error("r4d gemm_w5a16_nt_m64: K must be divisible by SK*128");
|
||||
if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: threads/block > 1024");
|
||||
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB must be 1..4");
|
||||
if (NPW != 1 && NPW != 4) throw std::runtime_error("r4d gemm_w5a16_nt_m64: NPW must be 1 or 4");
|
||||
const int ntiles = N / 16, mtiles = (M + 15) / 16;
|
||||
const int ncols = WV * NPW;
|
||||
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
|
||||
size_t smem = (size_t)ncols * SK * 256 * sizeof(float);
|
||||
if (smem > 64 * 1024) throw std::runtime_error("r4d gemm_w5a16_nt_m64: WV*NPW*SK too large");
|
||||
auto Ap = (const unsigned short*)a;
|
||||
auto Wp = (const unsigned*)wq;
|
||||
auto Hp = (const unsigned*)whi;
|
||||
auto Sp = (const unsigned*)wsz;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define LAUNCH(MT, NP, TT) do { \
|
||||
if (hi5) hipLaunchKernelGGL((r4d_gemm_w5a16_nt_m64_kernel<MT, NP, TT, true>), grid, block, smem, \
|
||||
st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); \
|
||||
else hipLaunchKernelGGL((r4d_gemm_w5a16_nt_m64_kernel<MT, NP, TT, false>), grid, block, smem, \
|
||||
st, Ap, Wp, Hp, Sp, Cp, M, K, N, WV, SK, lda, ldc); } while (0)
|
||||
#define LAUNCH_MB(NP, TT) switch (MB) { \
|
||||
case 1: LAUNCH(1, NP, TT); break; \
|
||||
case 2: LAUNCH(2, NP, TT); break; \
|
||||
case 3: LAUNCH(3, NP, TT); break; \
|
||||
case 4: LAUNCH(4, NP, TT); break; \
|
||||
default: throw std::runtime_error("r4d gemm_w5a16_nt_m64: MB unsupported"); }
|
||||
if (NPW == 1) {
|
||||
if (NT) { LAUNCH_MB(1, true); } else { LAUNCH_MB(1, false); }
|
||||
} else {
|
||||
if (NT) { LAUNCH_MB(4, true); } else { LAUNCH_MB(4, false); }
|
||||
}
|
||||
#undef LAUNCH_MB
|
||||
#undef LAUNCH
|
||||
}
|
||||
|
||||
int r4d_gemm_w5a16_nt_m64_max_m(void) { return R4D_GEMM_W4_MAX_M; }
|
||||
int r4d_gemm_w5a16_nt_m64_group(void) { return R4D_GEMM_W4_GROUP; }
|
||||
|
||||
// ============================================================== the plugin ABI entry points
|
||||
//
|
||||
// The operand reader and the split law are in r4d_gemm_args.h. See libr4d/r4d_args.h for why there
|
||||
// is no adapter directory between the core and these launches.
|
||||
/* ------------------------------------------------------------------ f16-activation grids */
|
||||
|
||||
static int w5_dispatch(const RadArgs* a, RadStream s, bool hi5) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % R4D_GEMM_W4_GROUP) return R4D_NO(RAD_E_SHAPE);
|
||||
const int group = r4d_gemm_w5a16_nt_m64_group();
|
||||
// The row's M is the step's, not the kernel's: rows past 64 are chunks of 64, each its own pass
|
||||
// over the weight, so a prefill chunk costs the weight's bytes once a 64 rows.
|
||||
const long long mc = std::min<long long>(g.M, r4d_gemm_w5a16_nt_m64_max_m());
|
||||
Cfg c;
|
||||
rc = cfg_for(a, g.K, mc, group, BR_FLAT, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
/* cfg_for pins MB = 1 across the decode band (the grid, not the weight, is the cost for the bf16 and
|
||||
* mxfp4 skinny kernels). Here the dequantise is: one block per row tile unpacks each weight fragment
|
||||
* once PER TILE, so three streams (M = 24, two tiles) pay it twice. Cover every row tile in one block
|
||||
* unless the tuner pinned MB; same split, so the output bits are unchanged. */
|
||||
R4dGemmCfg tuned;
|
||||
r4d_cfg_gemm(a, &tuned);
|
||||
if (tuned.mb <= 0) c.mb = std::min<long long>(4, (mc + 15) / 16);
|
||||
const long long Ntot = g.N, K = g.K, lda = mp.lda ? mp.lda : g.K;
|
||||
const long long nsz = K / R4D_GEMM_W4_GROUP;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
for (long long m0 = 0; m0 < g.M; m0 += mc) {
|
||||
const long long mm = std::min<long long>(mc, g.M - m0);
|
||||
R4D_TRY("gemm_w5a16_nt_m64",
|
||||
r4d_gemm_w5a16_nt_m64(
|
||||
r4d_addr(g.a) + (m0 * lda + p * K) * 2,
|
||||
r4d_addr(g.b) + n0 * K / 2, /* the nibble plane */
|
||||
hi5 ? r4d_addr(g.b) + Ntot * K / 2 + n0 * K / 8 : 0L, /* the fifth-bit plane */
|
||||
r4d_addr(g.bscale) + (n0 / 16) * nsz * 16 * 4,
|
||||
r4d_addr(g.y) + (m0 * Ntot + n0) * 2,
|
||||
(int)mm, (int)K, (int)np, c.wv, c.sk, c.mb, c.npw, c.nt, (long)(uintptr_t)s,
|
||||
(int)lda, (int)Ntot, hi5));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gemm_w5a16_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, true); }
|
||||
/* ...and the plain 4-bit asymmetric grid (z-lab's int4), whose blob is the nibble plane alone. */
|
||||
extern "C" int r4d_rad_gemm_w4a16asym_m64(const RadArgs* a, RadStream s) { return w5_dispatch(a, s, false); }
|
||||
@@ -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_dense_quant) -- in
|
||||
// 16x16x16 int8 WMMA, which issues at the fp8 instruction's rate. The f16 skinny kernel these weights
|
||||
// also serve (r4d_gemm_w5a16_nt_m64) is capped by the f16 matrix instruction at about 75 TF/s; this is the
|
||||
// tall-tile form with no such ceiling, built on r4d_gemm_mxfp4a8_tiled.hip's arrangement:
|
||||
//
|
||||
// * 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 <hip/hip_bf16.h>
|
||||
#include <hip/hip_fp16.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#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 <int BITS>
|
||||
__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 <int BITS>
|
||||
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<BITS>), 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, the parts in turn), 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 <int BITS>
|
||||
static int wpa8i8_dispatch(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/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) return R4D_NO(RAD_E_INVAL);
|
||||
const long long kb = g.K / 128;
|
||||
const long at = (long)(uintptr_t)a->scratch;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
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<BITS>(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); }
|
||||
@@ -0,0 +1,173 @@
|
||||
// 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_rotate.hip) does the same job in `stages` dependent LDS rounds a group and is
|
||||
// latency bound (~100-130 GB/s of ~640); this one spends ~8x the multiply-adds on the f16 WMMA, which
|
||||
// is 5 us of math for a 2048-row part, and quantises in the epilogue -- int8 (scale amax / 127, for the
|
||||
// int8 prefill GEMMs) or E4M3 (amax / 448, for the mxfp4a8 GEMMs), the same scale grid as the
|
||||
// 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 Givens stages and stores them as the
|
||||
// encoding's `t.dense` table, [parts * K / 128][128 (j)][128 (i)] f16, which the layout
|
||||
// (r4d_layout.cpp, r4d.givens.dense) takes as it is, 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 <hip/hip_fp16.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kGroup = 128;
|
||||
constexpr uint32_t kThreads = 128;
|
||||
constexpr uint32_t kWaves = kThreads / 32;
|
||||
constexpr uint32_t kTStride = kGroup + 8;
|
||||
static_assert(kThreads == kGroup, "a thread stages one channel scale of the group (invd[tid])"); // f16 per LDS row of T: 16 B pad, conflict-free b128 reads
|
||||
|
||||
typedef _Float16 v8h_t __attribute__((ext_vector_type(8)));
|
||||
|
||||
template <bool I8>
|
||||
__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<I8>()) : 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<I8>(acc[jt][0], acc[jt][1], acc[jt][2], acc[jt][3], inv);
|
||||
const uint32_t hi = q8_pack4<I8>(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);
|
||||
// `out` names the quantiser and q's dtype must be it: a mismatch is refused, not read from q
|
||||
const char* out = r4d_gets(a, "out");
|
||||
const bool i8 = q->dtype == RAD_I8;
|
||||
if (!i8 && q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!out || std::strcmp(out, i8 ? "i8" : "fp8") != 0) 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<long long>(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<I8_>), 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)
|
||||
@@ -0,0 +1,174 @@
|
||||
// ParoQuant's rotation, to f16: the channel scale and Givens stages applied to a bf16 activation, for the
|
||||
// 16-bit-activation GEMMs (w5a16 / w4a16_asym, rows up to 64 -- decode). The weight it pairs with is stored
|
||||
// as v = w . D . G_1 ... G_S (abi/rad_encoding.h, "givens"), so the product <v, x'> with
|
||||
// x' = x . D^-1 . G_1 ... G_S is <w, x>: the rotation is the activation's to do, once a token, and the
|
||||
// weight is read by the GEMM unchanged. The quantising form, for prefill-sized rows and for MXFP4, is
|
||||
// r4d_givens_dense.hip.
|
||||
//
|
||||
// WHY THE ROTATION IS A GROUP AT A TIME. ParoQuant's pairs never leave a group of 128 columns -- that is
|
||||
// how the checkpoint is trained, and the converter and the loader (r4d_rad_relayout_givens_pairs) refuse
|
||||
// one that does -- so a group is a closed system:
|
||||
// its 128 values are rotated by S stages of 64 disjoint pairs. A wave owns a group. The values sit in LDS
|
||||
// (128 floats a wave, no barrier needed: a wave's LDS accesses are in order, and the pairs of a stage are
|
||||
// disjoint so no two lanes touch one address) and each lane takes two pairs a stage.
|
||||
//
|
||||
// PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row yields `parts` rotated
|
||||
// copies, side by side: y is [M, parts * K]. A (part, group) pair is one unit of work, one wave's (a row
|
||||
// is several blocks, grid.y). The tables stack the parts as the "givens" encoding does -- stages rows each
|
||||
// of pairs and angle, one row of channel scales.
|
||||
//
|
||||
// THE CHANNEL SCALE IS A DIVIDE, because the encoding's t.scale is the factor the stored row was
|
||||
// multiplied by (D), and the activation takes its inverse. A true IEEE divide on both sides: the
|
||||
// reference (libref) divides in f32 too, so the two agree on this step exactly.
|
||||
//
|
||||
// COS AND SIN ARE COMPUTED HERE, in f32, from the stored angle: sincosf is accurate to an ulp or two,
|
||||
// which is also what libref's libm is.
|
||||
//
|
||||
// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip.
|
||||
|
||||
#include "r4d.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_fp8_args.h"
|
||||
#include <hip/hip_fp16.h>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kWave = 32;
|
||||
constexpr uint32_t kThreads = 256;
|
||||
constexpr uint32_t kWaves = kThreads / kWave;
|
||||
constexpr uint32_t kGroup = 128;
|
||||
constexpr uint32_t kPairsPerLane = kGroup / 2 / kWave; // 2
|
||||
|
||||
// kPre stages' tables are loaded and their angles' sine and cosine taken BEFORE the first of them is
|
||||
// applied, so the dependent chain a stage would otherwise be -- table load, LDS read, rotate, LDS
|
||||
// write -- overlaps its neighbours' loads. At decode (M of a handful of rows) the kernel is latency
|
||||
// and not bandwidth: a row is 40 groups of 128 and each group is eight serial stages.
|
||||
constexpr uint32_t kPre = 8;
|
||||
|
||||
__device__ __forceinline__ void wave_sync() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront");
|
||||
__builtin_amdgcn_wave_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront");
|
||||
}
|
||||
|
||||
// One wave rotates one (part, group) of one row: grid.x is the row, and grid.y spreads a row's
|
||||
// `parts * nkb` groups over blocks of kWaves waves -- one group a wave, so a row is several blocks and a
|
||||
// decode step of a few rows still fills the part. A wave that has no group returns at once; nothing in
|
||||
// the kernel is a block barrier. The rotated row is written as f16 into `y`, y_ld elements a row.
|
||||
__global__ __launch_bounds__(kThreads) void givens_rotate_kernel(
|
||||
const uint16_t* __restrict__ x, const int32_t* __restrict__ pairs,
|
||||
const float* __restrict__ angle, const float* __restrict__ rscale, uint16_t* __restrict__ y,
|
||||
uint32_t K, uint32_t nkb, uint32_t parts, uint32_t stages, uint32_t x_ld, uint32_t y_ld) {
|
||||
__shared__ float sbuf[kWaves][kGroup];
|
||||
const uint32_t row = blockIdx.x;
|
||||
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
|
||||
const uint32_t item = blockIdx.y * kWaves + wave;
|
||||
if (item >= parts * nkb) return;
|
||||
const uint32_t part = item / nkb, g = item % nkb;
|
||||
const uint32_t c0 = g * kGroup;
|
||||
const size_t xrow = (size_t)row * x_ld;
|
||||
float* buf = sbuf[wave];
|
||||
|
||||
// channel scale: v = x / D, four consecutive columns a lane
|
||||
{
|
||||
const float4 d = *(const float4*)(rscale + (size_t)part * K + c0 + lane * 4u);
|
||||
const uint32_t xc = c0 + lane * 4u;
|
||||
const float v0 = __uint_as_float((uint32_t)x[xrow + xc + 0] << 16) / d.x;
|
||||
const float v1 = __uint_as_float((uint32_t)x[xrow + xc + 1] << 16) / d.y;
|
||||
const float v2 = __uint_as_float((uint32_t)x[xrow + xc + 2] << 16) / d.z;
|
||||
const float v3 = __uint_as_float((uint32_t)x[xrow + xc + 3] << 16) / d.w;
|
||||
*(float4*)(buf + lane * 4u) = make_float4(v0, v1, v2, v3);
|
||||
}
|
||||
|
||||
for (uint32_t st0 = 0; st0 < stages; st0 += kPre) {
|
||||
const uint32_t nst = (stages - st0) < kPre ? (stages - st0) : kPre;
|
||||
int2 ab[kPre][kPairsPerLane];
|
||||
float th[kPre][kPairsPerLane], cs[kPre][kPairsPerLane], sn[kPre][kPairsPerLane];
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kPre; ++k)
|
||||
if (k < nst) {
|
||||
const size_t trow = (size_t)part * stages + st0 + k;
|
||||
const int32_t* pr = pairs + trow * K + c0;
|
||||
const float* an = angle + trow * (K / 2u) + g * (kGroup / 2u);
|
||||
#pragma unroll
|
||||
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
|
||||
const uint32_t j = lane + u * kWave;
|
||||
ab[k][u] = *(const int2*)(pr + 2u * j);
|
||||
th[k][u] = an[j];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kPre; ++k)
|
||||
if (k < nst)
|
||||
#pragma unroll
|
||||
for (uint32_t u = 0; u < kPairsPerLane; ++u) sincosf(th[k][u], &sn[k][u], &cs[k][u]);
|
||||
wave_sync(); // the scaled row (or the previous chunk's last stage) is in LDS
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kPre; ++k)
|
||||
if (k < nst) {
|
||||
#pragma unroll
|
||||
for (uint32_t u = 0; u < kPairsPerLane; ++u) {
|
||||
const int ia = ab[k][u].x - (int)c0, ib = ab[k][u].y - (int)c0;
|
||||
const float va = buf[ia], vb = buf[ib];
|
||||
buf[ia] = fmaf(cs[k][u], va, sn[k][u] * vb);
|
||||
buf[ib] = fmaf(cs[k][u], vb, -sn[k][u] * va);
|
||||
}
|
||||
wave_sync();
|
||||
}
|
||||
}
|
||||
|
||||
const float4 r = *(const float4*)(buf + lane * 4u);
|
||||
const float v[4] = { r.x, r.y, r.z, r.w };
|
||||
// f16 holds +-65504; a rotated post-norm row is orders below that, and the clamp keeps an outlier
|
||||
// finite instead of inf
|
||||
union { __half h[4]; uint2 u; } o;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) o.h[j] = __float2half(fminf(fmaxf(v[j], -65504.0f), 65504.0f));
|
||||
*(uint2*)(y + (size_t)row * y_ld + (size_t)part * K + c0 + lane * 4u) = o.u;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// x [M][K] bf16, `x_ld` elements a row (0 = K)
|
||||
// pairs [parts*stages][K] int32 column indices; (pairs[2j], pairs[2j+1]) is pair j
|
||||
// angle [parts*stages][K/2] f32
|
||||
// rscale [parts][K] f32, the factor the stored row was multiplied by
|
||||
// y [M][parts*K] f16
|
||||
enum { GV_X = 0, GV_PAIRS = 1, GV_ANGLE = 2, GV_RSCALE = 3, GV_Y = 4 };
|
||||
|
||||
static int givens_rotate_body(const RadArgs* a, const R4dSink& sk) {
|
||||
const RadTensor* x = r4d_opt(a, GV_X);
|
||||
const RadTensor* pr = r4d_opt(a, GV_PAIRS);
|
||||
const RadTensor* an = r4d_opt(a, GV_ANGLE);
|
||||
const RadTensor* rs = r4d_opt(a, GV_RSCALE);
|
||||
const RadTensor* y = r4d_opt(a, GV_Y);
|
||||
if (!x || !pr || !an || !rs || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (x->rank < 2 || y->rank != 2 || pr->rank != 2 || an->rank != 2 || rs->rank != 2)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
|
||||
if (pr->dtype != RAD_I32 || an->dtype != RAD_F32 || rs->dtype != RAD_F32)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
// rows are dim 0 and everything after it is the row
|
||||
const long long M = x->shape[0], K = r4d_numel(x) / (x->shape[0] > 0 ? x->shape[0] : 1);
|
||||
const long long grp = (long long)kGroup, nkb = K / grp;
|
||||
const long long parts = r4d_geti_or(a, "parts", 1), stages = r4d_geti_or(a, "stages", 0);
|
||||
if (M <= 0 || r4d_geti_or(a, "group", grp) != grp || K % grp || parts < 1 || stages < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (y->shape[0] != M || y->shape[1] != parts * K) return R4D_NO(RAD_E_SHAPE);
|
||||
// the tables are the weight's, contiguous: parts * stages rows of K pairs and K/2 angles
|
||||
if (pr->shape[0] != parts * stages || pr->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
|
||||
if (an->shape[0] != parts * stages || an->shape[1] != K / 2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (rs->shape[0] != parts || rs->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_aligned(rs->data, 16) || !r4d_aligned(pr->data, 8) || !r4d_aligned(y->data, 4))
|
||||
return R4D_NO(RAD_E_ALIGN);
|
||||
const long long xp = r4d_row_pitch(x), yp = r4d_row_pitch(y);
|
||||
if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const uint32_t gy = ((uint32_t)(parts * nkb) + kWaves - 1) / kWaves;
|
||||
const int rc = R4D_EMIT(sk, givens_rotate_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0,
|
||||
(const uint16_t*)x->data, (const int32_t*)pr->data, (const float*)an->data,
|
||||
(const float*)rs->data, (uint16_t*)y->data, (uint32_t)K, (uint32_t)nkb,
|
||||
(uint32_t)parts, (uint32_t)stages, (uint32_t)(xp ? xp : K), (uint32_t)(yp ? yp : parts * K));
|
||||
if (rc != RAD_OK) return rc;
|
||||
return (!sk.desc && hipGetLastError() != hipSuccess) ? RAD_E_DEVICE : RAD_OK;
|
||||
}
|
||||
R4D_ENTRY(r4d_rad_givens_rotate, givens_rotate_body)
|
||||
+270
-2
@@ -327,6 +327,18 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Every zero point a code of `bits` bits: what an asymmetric grid's zero is, and what the int8
|
||||
* prefill kernel reads back out of the scale dword (r4d_gemm_wpa8i8_tiled.hip takes five bits of it,
|
||||
* where the f16 kernel takes the whole value -- a larger zero would make the two disagree). */
|
||||
bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) {
|
||||
const long long nz = g.N * (g.K / g.group);
|
||||
for (long long i = 0; i < nz; ++i) {
|
||||
const int z = zero_at(zp, i);
|
||||
if (z < 0 || z >= (1 << bits)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym) {
|
||||
const long long nt = g.N / R4D_NTILE, nsz = g.K / g.group;
|
||||
for (long long t = 0; t < nt; ++t)
|
||||
@@ -342,6 +354,26 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym)
|
||||
}
|
||||
}
|
||||
|
||||
/* A ROTATED asymmetric grid (ParoQuant): codes of `codes` dtype, an f16 scale and a u8 zero point a
|
||||
* group, then a `givens` transform and its tables -- the same bytes as the unrotated grid, the
|
||||
* rotation being the activation's. */
|
||||
static bool paro_asym_enc(const RadEncoding* e, uint32_t codes, long long group) {
|
||||
if (!e || !rad_enc_is(e, "affine") || e->n_planes < 3) return false;
|
||||
const bool giv = std::strncmp(e->transform, "givens", RAD_ENC_STR) == 0;
|
||||
if (!giv && e->transform[0]) return false;
|
||||
if (!giv && e->n_planes != 3) return false;
|
||||
if (giv && (!rad_enc_valid(e) || rad_enc_find(e, "t.pairs") < 0)) return false;
|
||||
if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != codes ||
|
||||
e->plane[0].block[0] != 1 || e->plane[0].block[1] != 1) return false;
|
||||
const int s = rad_enc_find(e, "scale"), z = rad_enc_find(e, "zero");
|
||||
if (s != 1 || z != 2) return false;
|
||||
return e->plane[s].dtype == RAD_F16 && e->plane[s].kind == RAD_PLANE_TILED &&
|
||||
e->plane[s].block[0] == 1 && e->plane[s].block[1] == group &&
|
||||
(e->plane[z].dtype == RAD_U8 || e->plane[z].dtype == codes) &&
|
||||
e->plane[z].kind == RAD_PLANE_TILED && e->plane[z].block[0] == 1 &&
|
||||
e->plane[z].block[1] == group;
|
||||
}
|
||||
|
||||
/* ---- w4: a symmetric grid is i4 codes with an f16 scale; `_asym` is u4 codes with a zero. */
|
||||
int w4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
|
||||
@@ -352,7 +384,8 @@ int w4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
|
||||
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
|
||||
const bool asym = w4_asym(p, n_p);
|
||||
const bool ok = asym ? (r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U8) ||
|
||||
r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U4))
|
||||
r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U4) ||
|
||||
paro_asym_enc(enc, RAD_U4, g.group))
|
||||
: r4d_enc::affine(enc, RAD_I4, RAD_F16, 1, g.group);
|
||||
if (!ok) return RAD_E_DTYPE;
|
||||
if (gout) *gout = g;
|
||||
@@ -395,6 +428,9 @@ extern "C" int r4d_rad_relayout_w4(const RadParam* p, int n_p, int operand, cons
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
std::memset(dst, 0, (size_t)dst_bytes);
|
||||
if (operand == Q_BSCALE) {
|
||||
/* a ROTATED (ParoQuant) grid's zero is a 4-bit code */
|
||||
if (w4_asym(p, n_p) && std::strncmp(enc->transform, "givens", RAD_ENC_STR) == 0 &&
|
||||
!sz_zeros_fit(g, pl[1], 4)) return RAD_E_FORMAT;
|
||||
sz_write(g, pl, w4_asym(p, n_p) ? -1 : 8, (uint32_t*)dst);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -437,6 +473,214 @@ extern "C" int r4d_rad_unrelayout_w4(const RadParam* p, int n_p, int operand,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- w5: ParoQuant's int5, asymmetric: u5 codes, an f16 scale and a u8 zero point (0..31) a 128 of K.
|
||||
* The blob is w4's fragment order for the low four bits of every code (offset binary, no sign flip)
|
||||
* followed by a plane of 32-bit words holding the fifth bits, one a (n-tile, 64 of K, lane): byte s
|
||||
* is k step s of the block and bit e the fragment element e -- the element whose nibble is
|
||||
* 2e (e < 4) or 2(e-4)+1 in dword s of that lane's 16 bytes (r4d_gemm_w5a16_nt_m64.hip). The scale
|
||||
* operand is w4u's (scale, zero) dword plane. A ROTATED weight (a `givens` transform and its
|
||||
* tables beside the first three planes) is the same bytes: the rotation is the activation's. */
|
||||
namespace {
|
||||
bool w5_enc(const RadEncoding* e, long long group) { return paro_asym_enc(e, RAD_U5, group); }
|
||||
|
||||
int w5_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
WGeom g;
|
||||
int rc = wgeom(p, n_p, R4D_W4_GROUP, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
|
||||
if (!w5_enc(enc, g.group)) return RAD_E_DTYPE;
|
||||
if (gout) *gout = g;
|
||||
if (operand == Q_BSCALE)
|
||||
return sz_layout(g, enc, sel, pl, n, true, "r4d.w5.sz.g128", R4D_DT_W4_SZ, 4, out);
|
||||
if (operand != Q_B) return RAD_E_UNSUPPORTED;
|
||||
if (!selects(enc, sel, n, "codes") || !dims(pl[0], g.N, g.K)) return RAD_E_SHAPE;
|
||||
fill(out, "r4d.w5.frag.g128", R4D_DT_W4_FRAG, g.N, g.K, g.N * g.K * 5 / 8);
|
||||
return RAD_OK;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int r4d_rad_layout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* pl, int n, RadLayout* out) {
|
||||
return w5_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_relayout_w5(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;
|
||||
WGeom g;
|
||||
const int rc = w5_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
std::memset(dst, 0, (size_t)dst_bytes);
|
||||
if (operand == Q_BSCALE) {
|
||||
if (!sz_zeros_fit(g, pl[1], 5)) return RAD_E_FORMAT;
|
||||
sz_write(g, pl, -1, (uint32_t*)dst);
|
||||
return RAD_OK;
|
||||
}
|
||||
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 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 uint32_t q = rad_load_bits(row, 5, k);
|
||||
long long w;
|
||||
int nib;
|
||||
w4_slot(g, nn, k, &w, &nib);
|
||||
wq[w] |= (q & 15u) << (4 * nib);
|
||||
/* the fifth bit: word (t, kb, lane) = w / 4 (w4_slot's dword index is that * 4 + s);
|
||||
* byte s = w % 4, bit e from the nibble position */
|
||||
const long long hw = w / 4;
|
||||
const int s = (int)(w % 4);
|
||||
const int e = nib % 2 == 0 ? nib / 2 : 4 + nib / 2; /* nibble 2e / 2(e-4)+1 -> e */
|
||||
hi[hw] |= (q >> 4) << (8 * s + e);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_unrelayout_w5(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
WGeom g;
|
||||
const int rc = w5_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
if (operand == Q_BSCALE) {
|
||||
sz_read(g, (const uint32_t*)src, pl, true);
|
||||
return RAD_OK;
|
||||
}
|
||||
const uint32_t* wq = (const uint32_t*)src;
|
||||
const uint32_t* hi = wq + g.N * g.K / 8;
|
||||
const long long rb = (g.K * 5 + 7) / 8;
|
||||
uint8_t* d = (uint8_t*)pl[0].data;
|
||||
std::memset(d, 0, (size_t)(g.N * rb));
|
||||
for (long long nn = 0; nn < g.N; ++nn)
|
||||
for (long long k = 0; k < g.K; ++k) {
|
||||
long long w;
|
||||
int nib;
|
||||
w4_slot(g, nn, k, &w, &nib);
|
||||
const int e = nib % 2 == 0 ? nib / 2 : 4 + nib / 2; /* as r4d_rad_relayout_w5 */
|
||||
const uint32_t q = ((wq[w] >> (4 * nib)) & 15u) | (((hi[w / 4] >> (8 * (w % 4) + e)) & 1u) << 4);
|
||||
rad_store_bits(d + nn * rb, 5, k, q);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- givens pairs: ParoQuant's rotation pairs (i32 [P*S, K]), stored as they are but CHECKED.
|
||||
* The rotate kernels index a group's 128 LDS slots with them unchecked, so a stage that is not a
|
||||
* pairing of its own group -- an index outside the group, or one column twice -- is refused here,
|
||||
* at load, rather than read out of bounds. Operand 1 of the givens rows; the rest is as stored. */
|
||||
namespace {
|
||||
constexpr int GV_PAIRS_OPERAND = 1;
|
||||
constexpr long long GV_GROUP = 128;
|
||||
|
||||
int gv_pairs_layout(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 != GV_PAIRS_OPERAND) return RAD_E_UNSUPPORTED;
|
||||
const long long K = r4d_pgeti_or(p, n_p, "n", 0);
|
||||
if (K <= 0 || K % GV_GROUP || !selects(enc, sel, n, "t.pairs") || pl[0].rank != 2 ||
|
||||
pl[0].dtype != RAD_I32 || pl[0].shape[1] != K) return RAD_E_SHAPE;
|
||||
fill(out, "r4d.givens.pairs", RAD_I32, pl[0].shape[0], K, pl[0].shape[0] * K * 4);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Every row (a stage of a part) is, group by group, a perfect matching of the group's columns. */
|
||||
bool gv_pairs_ok(const int32_t* pairs, long long rows, long long K) {
|
||||
for (long long r = 0; r < rows; ++r)
|
||||
for (long long g = 0; g < K; g += GV_GROUP) {
|
||||
bool seen[GV_GROUP] = {};
|
||||
for (long long i = 0; i < GV_GROUP; ++i) {
|
||||
const long long c = (long long)pairs[r * K + g + i] - g;
|
||||
if (c < 0 || c >= GV_GROUP || seen[c]) return false;
|
||||
seen[c] = true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int r4d_rad_layout_givens_pairs(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, out);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_relayout_givens_pairs(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;
|
||||
const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
if (!gv_pairs_ok((const int32_t*)pl[0].data, L.shape[0], L.shape[1])) return RAD_E_FORMAT;
|
||||
std::memcpy(dst, pl[0].data, (size_t)L.bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_unrelayout_givens_pairs(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes,
|
||||
const RadTensor* pl, int n) {
|
||||
RadLayout L;
|
||||
const int rc = gv_pairs_layout(p, n_p, operand, enc, sel, pl, n, &L);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
|
||||
std::memcpy(pl[0].data, src, (size_t)L.bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- givens_dense: ParoQuant's rotation as one dense matrix a (part, group).
|
||||
*
|
||||
* The dense kernel (r4d_givens_dense.hip) applies a part's Givens stages over each group of 128 columns as
|
||||
* T (x / D), T being their composition. rad-convert composes T and stores it as the "givens" encoding's
|
||||
* "t.dense" table, f16 [P * K/128, 128 * 128], row p * (K/128) + g element j * 128 + i the output j for the
|
||||
* unit input e_i (abi/rad_encoding.h) -- which is the order the kernel stages a (part, group), 32 KiB, whole.
|
||||
* So the layout is the table as stored: a relayout that moves bytes and derives none (abi/rad_abi.h).
|
||||
* 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* K) {
|
||||
if (n != 1 || std::strncmp(r4d_enc::role(enc, sel, 0), "t.dense", 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 (!dims(pl[0], *P * (*K / GD_GROUP), GD_GROUP * GD_GROUP) || pl[0].dtype != RAD_F16) 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, K;
|
||||
const int rc = gd_geom(p, n_p, enc, sel, pl, n, &P, &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;
|
||||
std::memcpy(dst, pdata(pl[0]), (size_t)L.bytes);
|
||||
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. */
|
||||
@@ -615,6 +859,29 @@ extern "C" int r4d_rad_unrelayout_w2a8(const RadParam* p, int n_p, int operand,
|
||||
* exponents to [K/32][N], and b_ref is each row's largest exponent -- a reduction over the plane,
|
||||
* which is a derivation any reader of the plane could make and so not a choice. */
|
||||
namespace {
|
||||
/* A ROTATED MXFP4 WEIGHT (ParoQuant): the same two planes -- e2m1 codes, an E8M0 exponent a 32 --
|
||||
* stored in the basis the "givens" transform names, with the rotation's tables beside them. The
|
||||
* GEMM reads the codes and exponents exactly as it reads an unrotated weight; the rotation is the
|
||||
* activation's (givens_dense_quant), and the tables are separate weight operands of that op, so
|
||||
* nothing here touches them. What is checked is that they are there and are the kind of
|
||||
* rotation the quantiser applies: a transform this library does not read would hand the kernel
|
||||
* codes that decode to other numbers. */
|
||||
bool mx_paro_enc(const RadEncoding* e, long long K) {
|
||||
if (!e || !rad_enc_is(e, "affine") || std::strncmp(e->transform, "givens", RAD_ENC_STR) != 0) return false;
|
||||
if (e->n_planes < 5 || !rad_enc_valid(e)) return false;
|
||||
if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != RAD_FP4E2M1 ||
|
||||
e->plane[0].block[0] != 1 || e->plane[0].block[1] != 1) return false;
|
||||
const int s = rad_enc_find(e, "scale");
|
||||
if (s != 1 || e->plane[s].dtype != RAD_E8M0 || e->plane[s].kind != RAD_PLANE_TILED ||
|
||||
e->plane[s].block[0] != 1 || e->plane[s].block[1] != R4D_MXFP4_GROUP) return false;
|
||||
const int p = rad_enc_find(e, "t.pairs"), an = rad_enc_find(e, "t.angle"), sc = rad_enc_find(e, "t.scale");
|
||||
if (p < 0 || an < 0 || sc < 0) return false;
|
||||
if (e->plane[p].dtype != RAD_I32 || e->plane[an].dtype != RAD_F32 || e->plane[sc].dtype != RAD_F32)
|
||||
return false;
|
||||
// the quantiser rotates whole groups of 128 columns, one scale per group
|
||||
return K % 128 == 0 && e->plane[p].extent[1] == K;
|
||||
}
|
||||
|
||||
int mx_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
@@ -622,7 +889,8 @@ int mx_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
|
||||
int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE;
|
||||
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP)) return RAD_E_DTYPE;
|
||||
if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, R4D_MXFP4_GROUP) &&
|
||||
!mx_paro_enc(enc, g.K)) return RAD_E_DTYPE;
|
||||
if (gout) *gout = g;
|
||||
const long long nblk = g.K / R4D_MXFP4_GROUP;
|
||||
if (operand == Q_BSCALE || operand == Q_BREF) {
|
||||
|
||||
@@ -236,6 +236,12 @@ int r4d_rad_gemm_bf16_m16 (const RadArgs*, RadStream);
|
||||
int r4d_rad_gemm_bf16_m64 (const RadArgs*, RadStream);
|
||||
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_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);
|
||||
@@ -346,6 +352,8 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
|
||||
int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_had_quant_act_fp8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
|
||||
int r4d_rad_givens_rotate (const RadArgs*, RadStream);
|
||||
int r4d_rad_givens_rotate_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
|
||||
int r4d_rad_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*);
|
||||
@@ -412,10 +420,26 @@ int r4d_rad_relayout_w8a16(const RadParam*, int, int, const RadEncoding*, const
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_relayout_w8a8(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_layout_w5(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
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*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_unrelayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const void*, int64_t, const RadTensor*, int);
|
||||
|
||||
/* -- the small bf16 model ops (r4d_model_bf16.hip) --
|
||||
*
|
||||
|
||||
@@ -706,12 +706,19 @@ static const RadOperandSpec oGemmNt[] = {
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* `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. */
|
||||
static const RadParamSpec pGemmNtQ[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "N", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "K", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "group", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "pb1", RAD_P_INT, RAD_OPTIONAL },
|
||||
{ "pb2", RAD_P_INT, RAD_OPTIONAL },
|
||||
};
|
||||
/* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six
|
||||
* quantised GEMMs need a seventh operand each and neither is expressible as a weight aux stream,
|
||||
@@ -1047,6 +1054,45 @@ static const RadOperandSpec oQuantActFp8[] = {
|
||||
{ "scale", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* `givens_rotate` is ParoQuant's activation side for the 16-bit GEMMs, and libref declared this schema
|
||||
* first (the loader refuses two that differ). The tables are the "givens" encoding's, as WEIGHT
|
||||
* operands; see libref/ref_quant.cpp for the contract and r4d_givens_rotate.hip for the kernel. */
|
||||
static const RadParamSpec pGivensRotate[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "group", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "stages", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "parts", RAD_P_INT, RAD_REQUIRED },
|
||||
};
|
||||
static const RadOperandSpec oGivensRotate[] = {
|
||||
{ "x", RAD_OPD_IN, 0 },
|
||||
{ "pairs", RAD_OPD_WEIGHT, 0 },
|
||||
{ "angle", RAD_OPD_WEIGHT, 0 },
|
||||
{ "rscale", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* `givens_dense_quant` is ParoQuant's activation quantiser, the rotation done by a dense per-group matrix on the
|
||||
* matrix cores (r4d_givens_dense.hip). The matrices are the weight -- the givens encoding's "t.dense" table,
|
||||
* which rad-convert composes -- 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.
|
||||
*
|
||||
@@ -2461,6 +2507,17 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("had_quant_act_i8g", pQuantActFp8, oQuantActFp8,
|
||||
"quant_act_i8g with a `group`-wide Hadamard along K first; pairs with an i8 weight stored "
|
||||
"rotated, its scale carrying the residual factor of `group`."),
|
||||
SCHEMA("givens_rotate", pGivensRotate, oGivensRotate,
|
||||
"ParoQuant's rotation without a quantiser: y = x / rscale rotated by `stages` rounds of "
|
||||
"Givens pairs, `parts` copies side by side ([M, parts * n]) in y's own dtype. For a weight "
|
||||
"whose GEMM reads a 16-bit activation. `group` is the width a pair stays inside."),
|
||||
SCHEMA("givens_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 "
|
||||
"the sequential rotation, up to the f16 rounding of T."),
|
||||
SCHEMA("had_quant_act_fp8", pQuantActFp8, oQuantActFp8,
|
||||
"the same, with a `group`-wide Hadamard along K applied BEFORE the absmax. Pairs with "
|
||||
"an expert weight stored at dtype w4a8h, which carries the matching rotation and the "
|
||||
@@ -3109,6 +3166,19 @@ static const RadConstraint cGemmNtTiled[] = {
|
||||
static const RadConstraint cGemmNtW4[] = {
|
||||
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16"),
|
||||
};
|
||||
/* w5a16 serves any M: the dispatcher takes rows past 64 as chunks of 64. */
|
||||
static const RadConstraint cGemmNtW5[] = {
|
||||
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a16"),
|
||||
};
|
||||
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"),
|
||||
};
|
||||
@@ -3172,6 +3242,11 @@ static const RadConstraint cQuantActFp8[] = {
|
||||
static const RadConstraint cHadQuantActFp8[] = {
|
||||
C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* ParoQuant's dense rotation: the same whole-group rule (a rotation group cannot straddle a row's end),
|
||||
* and `out` one of the two quantisers its epilogue has. */
|
||||
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"),
|
||||
};
|
||||
|
||||
/* The dtype is the INPUT's, and the input is already quantised -- so it is `fp8a8` and not `bf16`
|
||||
* the way every other row in this family reads it. A four-multiple `n` is the staging slot (one
|
||||
@@ -5039,6 +5114,53 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_gemm_w4a16_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4,
|
||||
nullptr, r4d_rad_unrelayout_w4 },
|
||||
|
||||
{ "gemm_w5a16_nt_m64", "gemm_nt_q", "gemm",
|
||||
"skinny GEMM with a 5-bit asymmetric weight (ParoQuant int5), 16x16x16 f16 WMMA, split-K reduced "
|
||||
"in LDS; rows past 64 in chunks of 64, a partitioned weight (pb1/pb2) one launch a part",
|
||||
"N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, a nibble "
|
||||
"plane then a fifth-bit plane",
|
||||
"f16 A (parts side by side), 5-bit W with an f16 scale and integer zero per 128 K, bf16 C, fp32 "
|
||||
"accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY,
|
||||
ROW(cGemmNtW5), ROW(tGemmSkinny), r4d_tune_valid_gemm,
|
||||
nullptr, nullptr, r4d_rad_gemm_w5a16_m64, nullptr, r4d_rad_layout_w5, r4d_rad_relayout_w5,
|
||||
nullptr, r4d_rad_unrelayout_w5 },
|
||||
|
||||
{ "gemm_w4a16_asym_nt_m64", "gemm_nt_q", "gemm",
|
||||
"skinny GEMM with a 4-bit ASYMMETRIC weight (z-lab's ParoQuant int4), the 5-bit row's kernel with "
|
||||
"no fifth-bit plane; rows past 64 in chunks of 64, a partitioned weight (pb1/pb2) one launch a part",
|
||||
"N a multiple of 16; K divisible by SK*128; weight pre-permuted into fragment order, unsigned nibbles",
|
||||
"f16 A (parts side by side), 4-bit W with an f16 scale and integer zero per 128 K, bf16 C, fp32 "
|
||||
"accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_SKINNY,
|
||||
ROW(cGemmNtW4Asym), ROW(tGemmSkinny), r4d_tune_valid_gemm,
|
||||
nullptr, nullptr, r4d_rad_gemm_w4a16asym_m64, nullptr, r4d_rad_layout_w4, r4d_rad_relayout_w4,
|
||||
nullptr, r4d_rad_unrelayout_w4 },
|
||||
|
||||
{ "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, r4d_rad_unrelayout_w4 },
|
||||
|
||||
{ "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, r4d_rad_unrelayout_w5 },
|
||||
|
||||
{ "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, "
|
||||
@@ -5518,6 +5640,29 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr,
|
||||
r4d_shape_quant_act_fp8, nullptr, nullptr, r4d_rad_had_quant_act_fp8_describe },
|
||||
|
||||
{ "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",
|
||||
"bf16 in, f16 out, parts side by side; 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_rotate, nullptr, r4d_rad_layout_givens_pairs,
|
||||
r4d_rad_relayout_givens_pairs, nullptr, r4d_rad_unrelayout_givens_pairs, nullptr,
|
||||
r4d_rad_givens_rotate_describe },
|
||||
|
||||
{ "quant_act_i8g", "quant_act_i8g", "quant",
|
||||
"per-(row, 128-column) symmetric int8 quantisation of a bf16 activation",
|
||||
"quant_act_fp8's: n a multiple of 4, group 128, a ragged last group written zero-padded",
|
||||
|
||||
+585
-14
@@ -1105,6 +1105,42 @@ struct Planes {
|
||||
}
|
||||
};
|
||||
|
||||
/* gemm_nt_q's `pb1`/`pb2` over N rows (ParoQuant): rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1,
|
||||
* 2 of the activation, side by side in a row; `parts` is how many copies there are. 0 leaves a
|
||||
* bound out, as the kernels read it. */
|
||||
struct PartCut {
|
||||
int64_t e1, e2;
|
||||
int parts;
|
||||
PartCut(int64_t N, int64_t pb1, int64_t pb2)
|
||||
: e1(pb1 > 0 ? std::min(pb1, N) : N),
|
||||
e2(pb2 > 0 ? std::max(e1, std::min(pb2, N)) : N),
|
||||
parts(e2 < N ? 3 : (e1 < N ? 2 : 1)) {}
|
||||
int part_of(int64_t n) const { return (int)(n >= e1) + (int)(n >= e2); }
|
||||
};
|
||||
|
||||
/* An ASYMMETRIC grid's planes for a [N, K] weight: `bits`-bit codes (a bit stream along K), an f16
|
||||
* scale and a u8 zero point 0 .. 2^bits - 1 a 128 of K, drawn through st_mix32 of their coordinates. */
|
||||
static Planes asym_planes(int bits, int64_t N, int64_t K) {
|
||||
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), G = K / 128;
|
||||
const uint32_t top = (1u << bits) - 1;
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
rad_store_code(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k,
|
||||
(int)(st_mix32((uint32_t)(n * K + k) ^ 0x5eedu) & top));
|
||||
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) & top);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The unnormalised Sylvester Walsh-Hadamard transform of `n` values, in place: (a + b) to the lower
|
||||
* index and (a - b) to the upper, the transform an "fwhtN" encoding names. H_n H_n = n I. */
|
||||
static void h_fwht(float* v, int64_t n) {
|
||||
@@ -3844,11 +3880,17 @@ static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) {
|
||||
* spread over two decades and every eleventh block's is ZERO with zero codes behind it (an
|
||||
* all-zero activation block), which is the case the kernels carry their previous scale through. */
|
||||
static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
|
||||
int tn, bool ablk = false, std::vector<RadParam> extra = {}) {
|
||||
int tn, bool ablk = false, std::vector<RadParam> extra = {},
|
||||
int64_t pb1 = 0, int64_t pb2 = 0) {
|
||||
if (!sel(row)) return;
|
||||
/* PARTS (ParoQuant): the weight's rows [0, pb1), [pb1, pb2), [pb2, N) each meet their own copy
|
||||
* of the activation, the copies side by side in a row. `K` is one copy's width. */
|
||||
const PartCut cut(N, pb1, pb2);
|
||||
const int parts = cut.parts;
|
||||
char nm[160];
|
||||
std::string ex;
|
||||
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
|
||||
if (parts > 1) ex += " parts=" + std::to_string(parts);
|
||||
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
|
||||
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
|
||||
const RadKernelInfo* r = find(pl, row);
|
||||
@@ -3873,20 +3915,21 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
}
|
||||
|
||||
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
|
||||
std::vector<uint8_t> ha((size_t)(M * K));
|
||||
std::vector<float> av((size_t)(M * K)), as((size_t)(M * asc));
|
||||
const int64_t PK = parts * K, PA = parts * asc; /* a row of `a`, and of its scale */
|
||||
std::vector<uint8_t> ha((size_t)(M * PK));
|
||||
std::vector<float> av((size_t)(M * PK)), as((size_t)(M * PA));
|
||||
for (int64_t i = 0; i < M; ++i) {
|
||||
for (int64_t c = 0; c < asc; ++c) {
|
||||
const uint32_t h = st_mix32((uint32_t)(i * asc + c) ^ 0xa5u);
|
||||
as[(size_t)(i * asc + c)] =
|
||||
for (int64_t c = 0; c < PA; ++c) {
|
||||
const uint32_t h = st_mix32((uint32_t)(i * PA + c) ^ 0xa5u);
|
||||
as[(size_t)(i * PA + c)] =
|
||||
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
|
||||
: 0.0125f * (float)(1 + h % 5);
|
||||
}
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const bool zero = ablk && as[(size_t)(i * asc + k / 128)] == 0.0f;
|
||||
for (int64_t k = 0; k < PK; ++k) {
|
||||
const bool zero = ablk && as[(size_t)(i * PA + (k / K) * asc + (k % K) / 128)] == 0.0f;
|
||||
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
|
||||
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, v);
|
||||
av[(size_t)(i * K + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * K + k);
|
||||
rad_store_f32(ha.data(), RAD_F8E4M3, i * PK + k, v);
|
||||
av[(size_t)(i * PK + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * PK + k);
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> hy((size_t)(M * N), 0);
|
||||
@@ -3903,8 +3946,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_a, RAD_F8E4M3, { M, K }),
|
||||
ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }),
|
||||
T(d_a, RAD_F8E4M3, { M, PK }),
|
||||
ablk ? T(d_s, RAD_F32, { M, PA }) : T(d_s, RAD_F32, { M }),
|
||||
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(d_r, RAD_U8, { (int64_t)wr.size() }),
|
||||
};
|
||||
@@ -3912,6 +3955,8 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
|
||||
PS("dtype", "mxfp4a8") };
|
||||
if (tn) ps.push_back(PI("tn", tn));
|
||||
if (pb1) ps.push_back(PI("pb1", pb1));
|
||||
if (pb2) ps.push_back(PI("pb2", pb2));
|
||||
for (const RadParam& p : extra) ps.push_back(p);
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
@@ -3942,11 +3987,12 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
for (int64_t i = 0; i < M; ++i)
|
||||
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
|
||||
double acc = 0;
|
||||
const int pt = cut.part_of(n);
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
|
||||
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
|
||||
acc += (double)av[(size_t)(i * K + k)] * w *
|
||||
(ablk ? (double)as[(size_t)(i * asc + k / 128)] : 1.0);
|
||||
acc += (double)av[(size_t)(i * PK + pt * K + k)] * w *
|
||||
(ablk ? (double)as[(size_t)(i * PA + pt * asc + k / 128)] : 1.0);
|
||||
}
|
||||
if (!ablk) acc *= (double)as[(size_t)i];
|
||||
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
|
||||
@@ -3961,6 +4007,468 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
}
|
||||
|
||||
|
||||
/* PAROQUANT'S ACTIVATION QUANTISER AGAINST A DOUBLE-PRECISION ROTATION. The tables are real
|
||||
* pairings -- every stage of every group is a random permutation of the group's 128 columns read
|
||||
* as 64 pairs -- with angles over (-pi, pi) and channel scales over (0.5, 2), drawn through
|
||||
* st_mix32 of their coordinates. The reference divides, rotates in f64 and takes the absmax; the
|
||||
* kernel's scale must match it to the rounding of its f32 sincos, and every dequantised element
|
||||
* 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). */
|
||||
/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either quantiser. */
|
||||
enum class GvCase { Rotate, DenseFp8, DenseI8 };
|
||||
|
||||
static void givens_numeric(const Plugin& pl, int64_t M, int64_t K, int parts, int stages, GvCase mode) {
|
||||
const bool rot_only = mode == GvCase::Rotate, i8 = mode == GvCase::DenseI8, dense = !rot_only;
|
||||
const char* row = dense ? "givens_dense_quant" : "givens_rotate";
|
||||
if (!sel(row)) return;
|
||||
char nm[160];
|
||||
std::snprintf(nm, sizeof nm, "%s %s numeric M=%lld K=%lld parts=%d stages=%d", row,
|
||||
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;
|
||||
std::vector<uint16_t> hx((size_t)(M * K));
|
||||
std::vector<float> xv((size_t)(M * K));
|
||||
for (int64_t i = 0; i < M; ++i)
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ 0x77u);
|
||||
const float v = (float)((int)(h % 4001) - 2000) * 0.002f * (i % 4 == 3 ? 40.0f : 1.0f);
|
||||
hx[(size_t)(i * K + k)] = h_to_bf16(v);
|
||||
xv[(size_t)(i * K + k)] = h_bf16(hx[(size_t)(i * K + k)]);
|
||||
}
|
||||
const int64_t NPS = (int64_t)parts * stages;
|
||||
std::vector<int32_t> pairs((size_t)(NPS * K));
|
||||
std::vector<float> ang((size_t)(NPS * K / 2)), rs((size_t)(parts * K));
|
||||
for (int64_t ps = 0; ps < NPS; ++ps) {
|
||||
for (int64_t g = 0; g < ng; ++g) {
|
||||
std::vector<int32_t> perm((size_t)G);
|
||||
for (int i = 0; i < G; ++i) perm[(size_t)i] = i;
|
||||
for (int i = (int)G - 1; i > 0; --i)
|
||||
std::swap(perm[(size_t)i],
|
||||
perm[st_mix32((uint32_t)(ps * 7919 + g * 104729 + i)) % (uint32_t)(i + 1)]);
|
||||
for (int i = 0; i < G; ++i) pairs[(size_t)(ps * K + g * G + i)] = (int32_t)(g * G + perm[(size_t)i]);
|
||||
}
|
||||
for (int64_t j = 0; j < K / 2; ++j)
|
||||
ang[(size_t)(ps * K / 2 + j)] =
|
||||
(float)(st_mix32((uint32_t)(ps * 31337 + j) ^ 0x5bu) % 6283) / 1000.0f - 3.1415f;
|
||||
}
|
||||
for (int64_t i = 0; i < parts * K; ++i)
|
||||
rs[(size_t)i] = 0.5f + (float)(st_mix32((uint32_t)i ^ 0xc3u) % 1500) / 1000.0f;
|
||||
|
||||
void* d_x = dalloc(hx.size() * 2);
|
||||
void* d_p = dalloc(pairs.size() * 4);
|
||||
void* d_a = dalloc(ang.size() * 4);
|
||||
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);
|
||||
st_memcpy(d_a, ang.data(), ang.size() * 4, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_r, rs.data(), rs.size() * 4, hipMemcpyHostToDevice);
|
||||
std::vector<RadTensor> 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 : 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();
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"),
|
||||
PI("stages", stages), PI("parts", parts) };
|
||||
if (dense) {
|
||||
// The matrices as a container stores them (the "t.dense" table, abi/rad_encoding.h): one
|
||||
// 128x128 f16 matrix a (part, group), row p * ng + g, element [j][i] the image of column i
|
||||
// under the stages, composed in f64 as rad-convert does. Through the row's own layout hook.
|
||||
std::vector<uint16_t> dm((size_t)(parts * ng * G * G));
|
||||
std::vector<double> v((size_t)G);
|
||||
for (int p = 0; p < parts; ++p)
|
||||
for (int64_t g = 0; g < ng; ++g)
|
||||
for (int64_t i = 0; i < G; ++i) {
|
||||
std::fill(v.begin(), v.end(), 0.0);
|
||||
v[(size_t)i] = 1.0;
|
||||
for (int st = 0; st < stages; ++st)
|
||||
for (int64_t j = g * G / 2; j < (g + 1) * G / 2; ++j) { // group g's pairs
|
||||
const int64_t ia = pairs[(size_t)((p * stages + st) * K + 2 * j)] - g * G;
|
||||
const int64_t ib = pairs[(size_t)((p * stages + st) * K + 2 * j + 1)] - g * G;
|
||||
const double t = ang[(size_t)((p * stages + st) * (K / 2) + j)];
|
||||
const double c = std::cos(t), sn = std::sin(t);
|
||||
const double va = v[(size_t)ia], vb = v[(size_t)ib];
|
||||
v[(size_t)ia] = va * c + vb * sn;
|
||||
v[(size_t)ib] = vb * c - va * sn;
|
||||
}
|
||||
for (int64_t j = 0; j < G; ++j)
|
||||
dm[(size_t)(((p * ng + g) * G + j) * G + i)] = rad_f32_to_f16((float)v[(size_t)j]);
|
||||
}
|
||||
Planes pp;
|
||||
pp.enc = rad_enc_plain(RAD_BF16);
|
||||
rad_enc_add_table(&pp.enc, "t.dense", RAD_F16, parts * ng, G * G);
|
||||
pp.data.assign(2, {});
|
||||
pp.rows = { 0, parts * ng };
|
||||
pp.cols = { 0, G * G };
|
||||
pp.data[1].assign((const uint8_t*)dm.data(), (const uint8_t*)(dm.data() + dm.size()));
|
||||
std::vector<RadParam> lp = { PI("n", K), PI("parts", parts) };
|
||||
std::vector<uint8_t> blob;
|
||||
const int rl = stored(r, lp, 1, pp, { "t.dense" }, &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();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
a.world_size = 1;
|
||||
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; }
|
||||
std::vector<uint8_t> hq((size_t)(M * parts * K) * (rot_only ? 2 : 1));
|
||||
std::vector<float> hs((size_t)(M * parts * ng));
|
||||
st_memcpy(hq.data(), d_q, hq.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(hs.data(), d_s, hs.size() * 4, hipMemcpyDeviceToHost);
|
||||
|
||||
double worst_scale = 0, worst_val = 0;
|
||||
std::vector<double> b((size_t)K);
|
||||
for (int64_t i = 0; i < M; ++i)
|
||||
for (int p = 0; p < parts; ++p) {
|
||||
for (int64_t k = 0; k < K; ++k) b[(size_t)k] = (double)xv[(size_t)(i * K + k)] / (double)rs[(size_t)(p * K + k)];
|
||||
for (int st = 0; st < stages; ++st)
|
||||
for (int64_t j = 0; j < K / 2; ++j) {
|
||||
const int64_t ia = pairs[(size_t)((p * stages + st) * K + 2 * j)];
|
||||
const int64_t ib = pairs[(size_t)((p * stages + st) * K + 2 * j + 1)];
|
||||
const double t = ang[(size_t)((p * stages + st) * (K / 2) + j)], c = std::cos(t), sn = std::sin(t);
|
||||
const double va = b[(size_t)ia], vb = b[(size_t)ib];
|
||||
b[(size_t)ia] = va * c + vb * sn;
|
||||
b[(size_t)ib] = vb * c - va * sn;
|
||||
}
|
||||
for (int64_t g = 0; g < ng; ++g) {
|
||||
double amax = 0;
|
||||
for (int k = 0; k < G; ++k) amax = std::max(amax, std::fabs(b[(size_t)(g * G + k)]));
|
||||
if (rot_only) { // f16: relative 2^-11 of the value, 1e-3 of the group max
|
||||
for (int k = 0; k < G; ++k) {
|
||||
const double y = rad_load_f32(hq.data(), RAD_F16, i * parts * K + p * K + g * G + k);
|
||||
worst_val = std::max(worst_val, std::fabs(y - b[(size_t)(g * G + k)]) / (amax + 1e-30));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const double sc = hs[(size_t)(i * parts * ng + p * ng + g)];
|
||||
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(), 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[128];
|
||||
std::snprintf(d, sizeof d, "scale rel %.2e, value/amax %.3f", worst_scale, worst_val);
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
/* PARO'S 5-BIT SKINNY GEMM against what the planes mean: u5 codes (a bit stream along K), an f16 scale
|
||||
* and a zero point 0..31 a 128 of K, an f16 activation, the weight stored through the row's hooks.
|
||||
* `pb1`/`pb2` give a partitioned weight (the activation copies side by side). M past 64 runs the
|
||||
* dispatcher's 64-row chunks. */
|
||||
static void w5a16_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K, int64_t pb1 = 0,
|
||||
int64_t pb2 = 0) {
|
||||
const char* row = "gemm_w5a16_nt_m64";
|
||||
if (!sel(row)) return;
|
||||
const PartCut cut(N, pb1, pb2);
|
||||
const int parts = cut.parts;
|
||||
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;
|
||||
const Planes p = asym_planes(5, N, K);
|
||||
const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero");
|
||||
const int64_t rb = p.row_bytes(ic);
|
||||
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128) };
|
||||
std::vector<uint8_t> 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;
|
||||
std::vector<uint16_t> ha((size_t)(M * PK));
|
||||
std::vector<float> av((size_t)(M * PK));
|
||||
for (int64_t i = 0; i < M; ++i)
|
||||
for (int64_t k = 0; k < PK; ++k) {
|
||||
const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ 0x3cu);
|
||||
const float v = (float)((int)(h % 401) - 200) * 0.01f;
|
||||
rad_store_f32(&ha[(size_t)(i * PK + k)], RAD_F16, 0, v);
|
||||
av[(size_t)(i * PK + k)] = rad_load_f32(&ha[(size_t)(i * PK + k)], RAD_F16, 0);
|
||||
}
|
||||
std::vector<uint16_t> hy((size_t)(M * N), 0);
|
||||
void* d_a = dalloc(ha.size() * 2);
|
||||
void* d_w = dalloc(wq.size());
|
||||
void* d_s = dalloc(ws.size());
|
||||
void* d_y = dalloc(hy.size() * 2);
|
||||
if (!d_a || !d_w || !d_s || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_a, ha.data(), ha.size() * 2, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_s, ws.data(), ws.size(), hipMemcpyHostToDevice);
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_a, RAD_F16, { M, PK }), 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<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
|
||||
PS("dtype", "w5a16") };
|
||||
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;
|
||||
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)
|
||||
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
|
||||
const int pt = cut.part_of(n);
|
||||
double acc = 0;
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, RAD_U5, k);
|
||||
const double z = p.data[(size_t)iz][(size_t)(n * G + k / 128)];
|
||||
const double sc = rad_load_f32(p.data[(size_t)is].data(), RAD_F16, n * G + k / 128);
|
||||
acc += (double)av[(size_t)(i * PK + pt * K + k)] * (q - z) * sc;
|
||||
}
|
||||
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[64];
|
||||
std::snprintf(d, sizeof d, "rel_l2 %.3e", rel);
|
||||
ok(nm, rel < 1e-2, d);
|
||||
}
|
||||
|
||||
|
||||
/* 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<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128),
|
||||
PS("dtype", bits == 5 ? "w5a16" : "w4a16_asym") };
|
||||
std::vector<uint8_t> 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<size_t>(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<Cfg> 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<RadTensor> 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<RadParam> 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 PartCut cut(N, pb1, pb2);
|
||||
const int parts = cut.parts;
|
||||
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;
|
||||
const Planes p = asym_planes(bits, N, K);
|
||||
const int ic = p.find("codes"), is = p.find("scale"), iz = p.find("zero");
|
||||
const int64_t rb = p.row_bytes(ic);
|
||||
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", bits == 4 ? "w4a8i8_asym" : "w5a8i8") };
|
||||
std::vector<uint8_t> 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<uint8_t> ha((size_t)(M * PK));
|
||||
std::vector<float> 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<uint16_t> 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<RadTensor> 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<RadParam> 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 = cut.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 double q = rad_load_f32(p.data[(size_t)ic].data() + n * rb, p.enc.plane[ic].dtype, k);
|
||||
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
|
||||
@@ -13081,6 +13589,17 @@ static void device_phase(const Plugin& pl) {
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true);
|
||||
mxd_overlap_case(pl);
|
||||
/* PARTS (ParoQuant): each part of the weight against its own copy of the activation, with
|
||||
* bounds that do not fall on a tile of any kernel's, two parts and three, at every band. */
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 400, 640, 0, true, {}, 144);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 400, 640, 0, true, {}, 144, 288);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true, {}, 128);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 4, 34816, 5120, 0, true, {}, 17408);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 2, true, {}, 192);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true, {}, 96, 304);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true, {}, 256);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408);
|
||||
/* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or
|
||||
* fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K
|
||||
* on both sides of M=80, and the plain case; then every split and slab forced. */
|
||||
@@ -13522,6 +14041,58 @@ 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);
|
||||
w5a16_numeric(pl, 64, 400, 2560);
|
||||
w5a16_numeric(pl, 5, 400, 640, 144);
|
||||
w5a16_numeric(pl, 40, 512, 2560, 128, 384);
|
||||
w5a16_numeric(pl, 300, 400, 640, 192);
|
||||
w5a16_numeric(pl, 4, 34816, 5120, 17408);
|
||||
w5a16_numeric(pl, 150, 5120, 17408);
|
||||
}
|
||||
|
||||
if (sel("givens_rotate")) {
|
||||
if (!g_case) std::printf("\nParoQuant's rotation to f16, against an f64 rotation\n");
|
||||
givens_numeric(pl, 3, 5120, 1, 8, GvCase::Rotate);
|
||||
givens_numeric(pl, 5, 5120, 2, 8, GvCase::Rotate);
|
||||
givens_numeric(pl, 300, 6144, 2, 8, GvCase::Rotate);
|
||||
}
|
||||
|
||||
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 (const GvCase mode : { GvCase::DenseFp8, GvCase::DenseI8 }) {
|
||||
givens_numeric(pl, 1, 128, 1, 8, mode);
|
||||
givens_numeric(pl, 5, 5120, 2, 8, mode);
|
||||
givens_numeric(pl, 8, 5120, 2, 8, mode);
|
||||
givens_numeric(pl, 16, 5120, 1, 8, mode);
|
||||
givens_numeric(pl, 300, 6144, 2, 8, mode);
|
||||
givens_numeric(pl, 2048, 5120, 1, 8, mode);
|
||||
givens_numeric(pl, 2048, 5120, 2, 8, mode);
|
||||
givens_numeric(pl, 64, 17408, 1, 8, mode);
|
||||
givens_numeric(pl, 2048, 17408, 1, 8, mode);
|
||||
givens_numeric(pl, 7, 5120, 3, 2, mode);
|
||||
}
|
||||
}
|
||||
|
||||
if (sel("gram_accum")) {
|
||||
if (!g_case) std::printf("\nthe GPTQ calibration accumulator, against an f64 host Gram\n");
|
||||
gram_accum_case(pl);
|
||||
|
||||
Reference in new issue
Block a user