From b87010c7ddcd0655db645025b6d2d36af0650490 Mon Sep 17 00:00:00 2001 From: Asim Siddiqui Date: Thu, 5 Nov 2026 17:55:58 +1100 Subject: [PATCH] libref: w4a4 reference implementation and dequant_w4 op libref side of the w4a4 work; the libr3d kernels ship separately (submitted as PR 403). - ref_moe_gemm_w4a4_shape; ref_moe_gemm_w4a8_shape now N_odd/K_odd-aware (ref_shapes.cpp) - dequant_w4 schema with pDequantW4/oDequantW4 (ref_registry.cpp) - ref_dequant_w4 zero-row guard (ref_quant.cpp) - w4a4 reference GEMM and op declarations (ref_moe.cpp, ref_ops.h) - dequant_w4 in kOps plus sweep geometry (tests/ref_test.cpp) --- libref/ref_moe.cpp | 224 +++++++++++++++++++++++++++++++++++++++- libref/ref_ops.h | 6 ++ libref/ref_quant.cpp | 60 +++++++++++ libref/ref_registry.cpp | 9 +- libref/ref_shapes.cpp | 70 +++++++++++++ tests/ref_test.cpp | 4 +- 6 files changed, 370 insertions(+), 3 deletions(-) diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index d1b593ce..9684bf86 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -17,6 +17,8 @@ #include "ref_gemm.h" #include "ref_ops.h" #include "ref_planes.h" +#include +#include #include #include @@ -707,9 +709,229 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { } int ref_moe_gemm(const RadArgs* a, RadStream) { return moe_gemm_impl(a, false); } -int ref_moe_gemm_q(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true); } +int ref_moe_gemm_q(const RadArgs* a, RadStream s) { + const char* dt = p_str(a, "dtype", ""); + if (dt && std::strcmp(dt, "w4a8") == 0) return ref_moe_gemm_w4a8(a, s); + if (dt && std::strcmp(dt, "w4a4") == 0) return ref_moe_gemm_w4a4(a, s); + return moe_gemm_impl(a, true); +} int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true, 4); } +/* ------------------------------------------------------------------ moe_gemm_w4a8 */ +/* moe_gemm_q dtype w4a8: y[i, :] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^T. The two's-complement + * int4 experts (nibbles, -8..7) carry one bf16 scale per (row, 128 of K); the output is bf16 in + * sorted order. The experts are two tables by parity (the even in `w` / `w_scale`, the odd in + * `w_odd` / `w_odd_scale`, expert e at entry e/2 of class e%2). Two activation arms: + * * int8 a: each 128-block accumulates its raw product sum in i32 (exact), then folds + * (sub * a_scale) * w_scale in f32 in ascending block order -- the exact arithmetic and order + * the libr3d kernel runs, so the two agree bit for bit. + * * E4M3 a: the a and w codes decode exactly to f32 and the 128-block dot is summed in f32, the + * scales folded the same way; the kernel's f16 wave-matrix arm matches this to the f16 store + * ulp. + * A row no expert owns (a dropped slot) is left as the caller set it. */ +int ref_moe_gemm_w4a8(const RadArgs* a, RadStream) { + if (!have(a, 9)) return RAD_E_INVAL; + const RadTensor* A = &a->t[0]; + const RadTensor* AS = &a->t[1]; + const RadTensor* W = &a->t[2]; + const RadTensor* WS = &a->t[3]; + const RadTensor* ST = &a->t[4]; + const RadTensor* OF = &a->t[5]; + const RadTensor* WO = &a->t[6]; + const RadTensor* WOS = &a->t[7]; + const RadTensor* Y = &a->t[8]; + const bool e4m3 = (A->dtype == RAD_F8E4M3); + if (A->dtype != RAD_I8 && !e4m3) return RAD_E_DTYPE; + if (AS->dtype != RAD_F32 || W->dtype != RAD_I4 || WS->dtype != RAD_BF16 || Y->dtype != RAD_BF16) + return RAD_E_DTYPE; + if (e4m3 && (WO->dtype != RAD_I4 || WOS->dtype != RAD_BF16)) return RAD_E_DTYPE; + + const char* ord = p_str(a, "a_order", "token"); + const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0; + if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED; + + const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] * 2 : 0); + const int64_t top_k = p_int(a, "top_k", 1); + if (n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; + const int64_t N = W->rank >= 3 ? W->shape[1] : 0; + const int64_t K = W->rank >= 3 ? W->shape[2] : 0; + const int64_t T = Y->rank >= 2 ? Y->shape[0] : 0; + if (N <= 0 || K <= 0 || T <= 0 || K % 128) return RAD_E_SHAPE; + if (p_int(a, "N", N) != N || p_int(a, "K", K) != K) return RAD_E_SHAPE; + + const int64_t n_even = (n_expert + 1) / 2, n_odd = n_expert / 2; + if (W->rank < 3 || W->shape[0] < n_even || W->shape[1] < N || W->shape[2] < K) return RAD_E_SHAPE; + if (WS->rank < 3 || WS->shape[0] < n_even || WS->shape[1] < N || WS->shape[2] < K / 128) + return RAD_E_SHAPE; + if (n_odd > 0) { + if (WO->rank < 3 || WO->shape[0] < n_odd || WO->shape[1] < N || WO->shape[2] < K) + return RAD_E_SHAPE; + if (WOS->rank < 3 || WOS->shape[0] < n_odd || WOS->shape[1] < N || WOS->shape[2] < K / 128) + return RAD_E_SHAPE; + } + const int64_t M = A->rank >= 2 ? A->shape[0] : 0; + const int64_t ar = sorted_a ? T : M; + if (M <= 0 || numel(AS) < ar * (K / 128) || numel(ST) < T || numel(OF) < n_expert + 1) + return RAD_E_SHAPE; + + const int64_t a_ld = A->rank >= 2 ? A->stride[0] : K; + const int64_t y_ld = Y->rank >= 2 ? Y->stride[0] : N; + const int64_t w_ld = W->stride[1]; // nibbles per weight row + const int64_t ws_ld = WS->stride[1]; // scales per weight row + const int8_t* ap = (const int8_t*)A->data; + const uint8_t* ap8 = (const uint8_t*)A->data; + const float* asp = (const float*)AS->data; + const int32_t* st = (const int32_t*)ST->data; + const int32_t* of = (const int32_t*)OF->data; + const uint8_t* wp = (const uint8_t*)W->data; + const uint16_t* wsp = (const uint16_t*)WS->data; + const uint8_t* wop = (const uint8_t*)WO->data; + const uint16_t* wosp = (const uint16_t*)WOS->data; + uint16_t* yp = (uint16_t*)Y->data; + + for (int64_t i = 0; i < T; ++i) { + const int32_t f = st[i]; + const int64_t src = sorted_a ? i : (f >= 0 ? (int64_t)f / top_k : -1); + if (src < 0 || (!sorted_a && (int64_t)f / top_k >= M)) continue; // a dropped slot + int64_t e = 0; + while (e + 1 < n_expert && of[e + 1] <= i) ++e; + if (i < of[e] || i >= of[e + 1]) continue; // no expert owns this row + const int64_t cls = e & 1, e2 = e >> 1; + const uint8_t* wt = cls ? wop : wp; + const uint16_t* wst = cls ? wosp : wsp; + const int64_t wrow0 = (size_t)e2 * (size_t)N * w_ld / 2; + const int64_t wsrow0 = (size_t)e2 * (size_t)N * ws_ld; + for (int64_t n = 0; n < N; ++n) { + const uint8_t* wrow = wt + wrow0 + (size_t)n * w_ld / 2; + const uint16_t* wsrow = wst + wsrow0 + (size_t)n * ws_ld; + const float* asr = asp + src * (K / 128); + float acc = 0.f; + for (int64_t b = 0; b < K / 128; ++b) { + const int64_t k0 = b * 128; + float term; + float wscale; + const uint32_t ws_bits = (uint32_t)wsrow[b] << 16; /* bf16 -> f32: align to high 16 bits */ + std::memcpy(&wscale, &ws_bits, 4); + if (e4m3) { + float dot = 0.f; + for (int64_t k = 0; k < 128; ++k) + dot += fp8e4m3_to_f32(ap8[(size_t)src * a_ld + k0 + k]) * w4_code(wrow, k0 + k); + term = dot * asr[b] * wscale; + } else { + int32_t sub = 0; + for (int64_t k = 0; k < 128; ++k) + sub += (int32_t)ap[(size_t)src * a_ld + k0 + k] * (int32_t)w4_code(wrow, k0 + k); + term = (float)sub * asr[b] * wscale; + } + acc += term; + } + yp[i * y_ld + n] = f32_to_bf16(acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ moe_gemm_w4a4 */ +/* moe_gemm_q dtype w4a4: y[i, :] = a[sorted_tok[i] / top_k, :] @ w[e(i)]^T. Both the activation and + * the experts are two's-complement int4 (nibbles, -8..7) packed two per byte; the activation carries + * one f32 scale per (row, 128 of K), each expert one bf16 scale per (row, 128 of K); the output is + * bf16 in sorted order. The experts are two tables by parity (the even in `w` / `w_scale`, the odd in + * `w_odd` / `w_odd_scale`, expert e at entry e/2 of class e%2). Each 128-block accumulates its raw + * product sum in i32 (exact: both codes widen to int8), then folds (sub * a_scale) * w_scale in f32 + * in ascending block order -- the exact arithmetic and order the libr3d kernel runs, so the two agree + * bit for bit. A row no expert owns (a dropped slot) is left as the caller set it. */ +int ref_moe_gemm_w4a4(const RadArgs* a, RadStream) { + if (!have(a, 9)) return RAD_E_INVAL; + const RadTensor* A = &a->t[0]; + const RadTensor* AS = &a->t[1]; + const RadTensor* W = &a->t[2]; + const RadTensor* WS = &a->t[3]; + const RadTensor* ST = &a->t[4]; + const RadTensor* OF = &a->t[5]; + const RadTensor* WO = &a->t[6]; + const RadTensor* WOS = &a->t[7]; + const RadTensor* Y = &a->t[8]; + if (A->dtype != RAD_I4) return RAD_E_DTYPE; + if (AS->dtype != RAD_F32 || W->dtype != RAD_I4 || WS->dtype != RAD_BF16 || Y->dtype != RAD_BF16) + return RAD_E_DTYPE; + if (WO->dtype != RAD_I4 || WOS->dtype != RAD_BF16) return RAD_E_DTYPE; + + const char* ord = p_str(a, "a_order", "token"); + const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0; + if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED; + + const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] * 2 : 0); + const int64_t top_k = p_int(a, "top_k", 1); + if (n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; + const int64_t N = W->rank >= 3 ? W->shape[1] : 0; + const int64_t K = W->rank >= 3 ? W->shape[2] : 0; + const int64_t T = Y->rank >= 2 ? Y->shape[0] : 0; + if (N <= 0 || K <= 0 || T <= 0 || K % 128) return RAD_E_SHAPE; + if (p_int(a, "N", N) != N || p_int(a, "K", K) != K) return RAD_E_SHAPE; + + const int64_t n_even = (n_expert + 1) / 2, n_odd = n_expert / 2; + if (W->rank < 3 || W->shape[0] < n_even || W->shape[1] < N || W->shape[2] < K) return RAD_E_SHAPE; + if (WS->rank < 3 || WS->shape[0] < n_even || WS->shape[1] < N || WS->shape[2] < K / 128) + return RAD_E_SHAPE; + if (n_odd > 0) { + if (WO->rank < 3 || WO->shape[0] < n_odd || WO->shape[1] < N || WO->shape[2] < K) + return RAD_E_SHAPE; + if (WOS->rank < 3 || WOS->shape[0] < n_odd || WOS->shape[1] < N || WOS->shape[2] < K / 128) + return RAD_E_SHAPE; + } + const int64_t M = A->rank >= 2 ? A->shape[0] : 0; + const int64_t ar = sorted_a ? T : M; + if (M <= 0 || numel(AS) < ar * (K / 128) || numel(ST) < T || numel(OF) < n_expert + 1) + return RAD_E_SHAPE; + + const int64_t a_ld = A->rank >= 2 ? A->stride[0] : K / 2; // BYTES per activation row (K int4) + const int64_t y_ld = Y->rank >= 2 ? Y->stride[0] : N; + const int64_t w_ld = W->stride[1]; // nibbles per weight row + const int64_t ws_ld = WS->stride[1]; // scales per weight row + const uint8_t* ap = (const uint8_t*)A->data; + const float* asp = (const float*)AS->data; + const int32_t* st = (const int32_t*)ST->data; + const int32_t* of = (const int32_t*)OF->data; + const uint8_t* wp = (const uint8_t*)W->data; + const uint16_t* wsp = (const uint16_t*)WS->data; + const uint8_t* wop = (const uint8_t*)WO->data; + const uint16_t* wosp = (const uint16_t*)WOS->data; + uint16_t* yp = (uint16_t*)Y->data; + + for (int64_t i = 0; i < T; ++i) { + const int32_t f = st[i]; + const int64_t src = sorted_a ? i : (f >= 0 ? (int64_t)f / top_k : -1); + if (src < 0 || (!sorted_a && (int64_t)f / top_k >= M)) continue; // a dropped slot + int64_t e = 0; + while (e + 1 < n_expert && of[e + 1] <= i) ++e; + if (i < of[e] || i >= of[e + 1]) continue; // no expert owns this row + const int64_t cls = e & 1, e2 = e >> 1; + const uint8_t* wt = cls ? wop : wp; + const uint16_t* wst = cls ? wosp : wsp; + const int64_t wrow0 = (size_t)e2 * (size_t)N * w_ld / 2; + const int64_t wsrow0 = (size_t)e2 * (size_t)N * ws_ld; + for (int64_t n = 0; n < N; ++n) { + const uint8_t* wrow = wt + wrow0 + (size_t)n * w_ld / 2; + const uint16_t* wsrow = wst + wsrow0 + (size_t)n * ws_ld; + const float* asr = asp + src * (K / 128); + float acc = 0.f; + for (int64_t b = 0; b < K / 128; ++b) { + const int64_t k0 = b * 128; + float wscale; + const uint32_t ws_bits = (uint32_t)wsrow[b] << 16; /* bf16 -> f32: high 16 bits */ + std::memcpy(&wscale, &ws_bits, 4); + int32_t sub = 0; + for (int64_t k = 0; k < 128; ++k) + sub += (int32_t)w4_code(ap + (size_t)src * a_ld, k0 + k) + * (int32_t)w4_code(wrow, k0 + k); + acc += (float)sub * asr[b] * wscale; + } + yp[i * y_ld + n] = f32_to_bf16(acc); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ moe_gather */ /* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)]. * diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 1cee5e10..5c76d9d6 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -146,6 +146,7 @@ int ref_gram_accum (const RadArgs*, RadStream); int ref_rmsnorm_had_quant_i8(const RadArgs*, RadStream); int ref_gated_had_quant_i8 (const RadArgs*, RadStream); int ref_dequant (const RadArgs*, RadStream); +int ref_dequant_w4 (const RadArgs*, RadStream); /* ---- gemm and the vocabulary edges */ int ref_gemm_nt (const RadArgs*, RadStream); @@ -286,6 +287,8 @@ int ref_router_gemm_topk_scatter(const RadArgs*, RadStream); int ref_moe_gemm (const RadArgs*, RadStream); int ref_moe_gemm_q (const RadArgs*, RadStream); int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream); +int ref_moe_gemm_w4a8 (const RadArgs*, RadStream); +int ref_moe_gemm_w4a4 (const RadArgs*, RadStream); /* The layout hooks of moe_gemm_q and moe_gemm_q_mod4: a codebook expert's views of several planes * in the joined form of abi/rad_planes.h, checked against `dtype` (ref_moe.cpp). */ int ref_moe_cb_layout (const RadParam*, int, int, const RadEncoding*, const int*, @@ -437,6 +440,7 @@ REF_SHAPE_FN(ref_gram_accum); REF_SHAPE_FN(ref_rmsnorm_had_quant_i8); REF_SHAPE_FN(ref_gated_had_quant_i8); REF_SHAPE_FN(ref_dequant); +REF_SHAPE_FN(ref_dequant_w4); REF_SHAPE_FN(ref_gemm_nt); REF_SHAPE_FN(ref_gemm_nt_bias); @@ -562,6 +566,8 @@ REF_SHAPE_FN(ref_router_gemm_topk_scatter); REF_SHAPE_FN(ref_moe_gemm); REF_SHAPE_FN(ref_moe_gemm_q); REF_SHAPE_FN(ref_moe_gemm_q_mod4); +REF_SHAPE_FN(ref_moe_gemm_w4a8); +REF_SHAPE_FN(ref_moe_gemm_w4a4); REF_SHAPE_FN(ref_scale_rows); REF_SHAPE_FN(ref_moe_gather); REF_SHAPE_FN(ref_row_topk); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 240e47e6..f1a061c3 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -273,6 +273,66 @@ int ref_dequant(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ dequant_w4 + * The packed 4-bit weight back to a plain row-major bf16 [N, K]. The fragment order is + * [t][kb][lh][r][s] with eight nibbles along i, where t = n/16, r = n%16, kb = k/64, + * s = (k%64)/16, and the k inside the step is 4*lh + _KOFF[i] with _KOFF = {0,8,1,9,2,10,3,11}. + * The scale dword at [t][g][r] holds the f16 scale low and -(1024+zero) high. */ +static const int kKOFF[8] = {0, 8, 1, 9, 2, 10, 3, 11}; +static float f16_bits_to_f32(uint16_t h) { + uint32_t sign = (uint32_t)(h >> 15) << 31; + uint32_t exp = (uint32_t)(h >> 10) & 0x1fu; + uint32_t mant = (uint32_t)(h & 0x3ffu); + uint32_t f32; + if (exp == 0) { + if (mant == 0) f32 = sign; + else { while (!(mant & 0x400u)) { mant <<= 1; --exp; } f32 = sign | ((exp + 126u) << 23) | ((mant & 0x3ffu) << 13); } + } else if (exp == 31) { + f32 = sign | 0x7f800000u | (mant << 13); + } else { + f32 = sign | ((exp + 112u) << 23) | (mant << 13); + } + float f; std::memcpy(&f, &f32, 4); return f; +} + +int ref_dequant_w4(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *wq = &a->t[0], *ws = &a->t[1], *y = &a->t[2]; + const int64_t N = y->shape[0], K = y->shape[1]; + const int64_t group = p_int(a, "group", 128); + const int64_t twos = p_int(a, "twos", 1); + if (N <= 0 || K <= 0 || N % 16 || K % 64 || group < 1 || K % group) return RAD_E_SHAPE; + + const uint32_t* Wq = (const uint32_t*)wq->data; + const uint32_t* Ws = (const uint32_t*)ws->data; + const int64_t nkb = K / 64, ng = K / group; + const int64_t ys = y->stride[1]; + + for (int64_t idx = 0; idx < N * K / 8; ++idx) { + const int s = (int)(idx & 3); + const int r = (int)((idx >> 2) & 15); + const int lh = (int)((idx >> 6) & 1); + const int kb = (int)((idx >> 7) % nkb); + const int t = (int)((idx >> 7) / nkb); + const int row_n = t * 16 + r; + const uint32_t w = Wq[idx]; + + const int kbase = kb * 64 + s * 16 + 4 * lh; + const uint32_t sz = Ws[(size_t)(t * ng + kbase / group) * 16 + r]; + const float sc = f16_bits_to_f32((uint16_t)(sz & 0xFFFFu)); + const float nz = f16_bits_to_f32((uint16_t)(sz >> 16)); + const float zero = -nz - 1024.f; + + for (int i = 0; i < 8; i++) { + const int n = (int)((w >> (4 * i)) & 0xF); + const float q = twos ? (float)((n ^ 8) - 8) : (float)n; + const int k = kbase + kKOFF[i]; + stt(y, (size_t)row_n * K + k, (q - (twos ? 0.f : zero)) * sc); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ quant_act_fp8 * * The oracle for the block-scaled FP8 family, the activation format the production checkpoints diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index a0ebf280..3c90c101 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -650,7 +650,7 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_ static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"), OPD("sorted_tok"), OPD("expert_offset"), WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") }; -/* The same op over four classes by expert number mod 4: `w`/`w_scale` class 0 at [N, K], + /* The same op over four classes by expert number mod 4: `w`/`w_scale` class 0 at [N, K], * `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry e / 4 of class e % 4; how four ranks * share the extra block of a five-block expert (as in libr4d's schema). */ static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), @@ -681,6 +681,9 @@ static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"), P_STR("dtype") }; static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") }; +static const RadParamSpec pDequantW4[] = { P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), + P_INT("twos") }; +static const RadOperandSpec oDequantW4[] = { WGT("wq"), WGT("ws"), OUT("y") }; static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("val") }; @@ -1733,6 +1736,9 @@ static const RadOpSchema kSchemas[] = { "(idx, val) form the single-rank top-R produces. `gathered` is [M, world_size * R, 2] pairs, " "rank r's at [r*R, (r+1)*R); id -1 is a pad and is dropped. Ties break on the LOWER id, which is " "what makes the merged answer agree with a top-R over the unsharded plane." }, +{ "dequant_w4", ARR(pDequantW4), ARR(oDequantW4), + "Packed int4 weight to row-major bf16. Each 32-bit word holds 8 codes; the scale is " + "f16 in the low 16 bits, the zero point -(1024+zero) as f16 in the high 16 bits." }, { "pair_argmax", ARR(pPairArgmax), ARR(oPairArgmax), "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in the first " "f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties to the lower " @@ -2539,6 +2545,7 @@ SIMPLE("ref_gated_had_quant_i8", "gated_had_quant_i8", "quant", "gated product, rotation and int8 in one pass", "float in, i8 out, f32 scale", ref_gated_had_quant_i8), SIMPLE("ref_dequant", "dequant", "quant", "group-scaled dequantisation", DT_ANY, ref_dequant), +SIMPLE("ref_dequant_w4", "dequant_w4", "quant", "packed int4 weight to row-major bf16", DT_ANY, ref_dequant_w4), SIMPLE("ref_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate", DT_FLOAT, ref_gemm_nt), SIMPLE("ref_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT, diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 25a81b40..27fecdd6 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1336,6 +1336,17 @@ int ref_dequant_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("dequant", operand, out); } +int ref_dequant_w4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + const int64_t group = gi(p, n_p, "group", 128); + if (N < 1 || K < 1 || N % 16 || K % 64 || group < 1 || K % group) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_I4, { N * K / 8 }); /* wq -- packed int4 */ + o.t(RAD_F32, { N * K / group }); /* ws -- scale (f16 in a dword, but declared f32) */ + o.t(RAD_BF16, { N, K }); /* y */ + return o.finish("dequant_w4", operand, out); +} + /* ================================================================== gemm */ int ref_gemm_nt_f32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -2115,6 +2126,10 @@ static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { * `w` is described stacked [ne, N, K], since a fixture cannot hold a pointer table; expert_entry() * reads both forms. */ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + if (const char* dk = gs(p, n_p, "dtype")) { + if (!std::strcmp(dk, "w4a8")) return ref_moe_gemm_w4a8_shape(p, n_p, operand, out); + if (!std::strcmp(dk, "w4a4")) return ref_moe_gemm_w4a4_shape(p, n_p, operand, out); + } const int64_t M = gi(p, n_p, "M", 0); const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0); const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0); @@ -2195,6 +2210,61 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes return o.finish("moe_gemm_q_mod4", operand, out); } +/* The grouped int4 GEMM: an int8 activation with an f32 scale per (row, 128 of K), two's- + * complement int4 experts (nibbles, -8..7) with an f32 scale per (row, 128 of K); one weight + * table, token-order a only. */ +int ref_moe_gemm_w4a8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0); + const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0); + const int64_t ne = gi(p, n_p, "n_expert", 0); + const int64_t k = gi(p, n_p, "top_k", 0); + if (M <= 0 || N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || K0 % 128 || K1 % 128 || + ne <= 0 || k <= 0) + return RAD_E_UNSUPPORTED; + const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; + const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2; + const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; + Opd o; + o.t((uint32_t)RAD_I8, { AR, K }); /* a -- int8 (the E4M3 arm is 8-bit too) */ + o.t((uint32_t)RAD_F32, { AR, K / 128 }); /* a_scale */ + o.t((uint32_t)RAD_I4, { ne0, N0, K0 }); /* w -- even experts, nibbles */ + o.t((uint32_t)RAD_BF16, { ne0, N0, K0 / 128 }); /* w_scale */ + o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ + o.t((uint32_t)RAD_I4, { ne1, N1, K1 }); /* w_odd -- odd experts */ + o.t((uint32_t)RAD_BF16, { ne1, N1, K1 / 128 }); /* w_odd_scale */ + o.t((uint32_t)RAD_BF16, { M * k, N }); /* y -- in sorted order */ + return o.finish("moe_gemm_q", operand, out); +} + +/* The same over a two's-complement int4 activation (two nibbles per byte): the w4a8 grid with an + * I4 a, so the activation row is K/2 bytes. */ +int ref_moe_gemm_w4a4_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t N0 = gi(p, n_p, "N", 0), K0 = gi(p, n_p, "K", 0); + const int64_t N1 = gi(p, n_p, "N_odd", N0), K1 = gi(p, n_p, "K_odd", K0); + const int64_t ne = gi(p, n_p, "n_expert", 0); + const int64_t k = gi(p, n_p, "top_k", 0); + if (M <= 0 || N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || K0 % 128 || K1 % 128 || + ne <= 0 || k <= 0) + return RAD_E_UNSUPPORTED; + const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; + const int64_t ne0 = (ne + 1) / 2, ne1 = ne / 2; + const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; + Opd o; + o.t((uint32_t)RAD_I4, { AR, K }); /* a -- int4, two nibbles per byte */ + o.t((uint32_t)RAD_F32, { AR, K / 128 }); /* a_scale */ + o.t((uint32_t)RAD_I4, { ne0, N0, K0 }); /* w -- even experts, nibbles */ + o.t((uint32_t)RAD_BF16, { ne0, N0, K0 / 128 }); /* w_scale */ + o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ + o.t((uint32_t)RAD_I4, { ne1, N1, K1 }); /* w_odd -- odd experts */ + o.t((uint32_t)RAD_BF16, { ne1, N1, K1 / 128 }); /* w_odd_scale */ + o.t((uint32_t)RAD_BF16, { M * k, N }); /* y -- in sorted order */ + return o.finish("moe_gemm_q", operand, out); +} + int ref_moe_gather_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const int64_t k = gi(p, n_p, "top_k", 0); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 22f5572f..650715d6 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -1221,7 +1221,7 @@ TEST(op_vocabulary) { "dflash_tree", "attn_paged_tree", "attn_paged_anchor_window", "rmsnorm_had_quant_i8", "gated_had_quant_i8", - "dequant", + "dequant", "dequant_w4", "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", /* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */ "lora_shrink", "lora_expand", "lora_expand_mm", @@ -10356,6 +10356,8 @@ std::vector geometries() { G("givens_rotate", "M", 3, a.i("M", R).i("n", 8).i("group", 8).s("dtype", "f32") .i("stages", 2).i("parts", 1)), G("dequant", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")), + G("dequant_w4", "N", 16, a.i("N", R).i("K", 64).i("group", 64).i("twos", 1) + .s("dtype", "w4a8")), G("rmsnorm_quant_fp8", "M", 3, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16) .s("dtype", "bf16")), G("gated_quant_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "bf16")