From bc2e6ba614b9b224f8fe99b1c88f6808d33b9609 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Mon, 5 Oct 2026 11:54:32 +0200 Subject: [PATCH] moe_gemm_q_mod4: the quantised grouped GEMM over four classes of experts moe_gemm_q over four tables instead of two: expert e is entry e / 4 of class e % 4. A separate op, because the declaration divides a table op's weights over its table operands by count. The arguments are repacked to fit four classes in 256 bytes; moe_gemm_q's arithmetic is unchanged. Where weights do not divide evenly over the tables, the first tables take one more each (510 experts: 128/128/127/127). libref and libavx serve the op. --- core/build/rad_builder.cpp | 29 +++--- docs/OPS.md | 22 ++++- libavx/avx_cases.cpp | 11 +++ libavx/avx_isa.h | 1 + libavx/avx_moe.cpp | 58 +++++++---- libavx/avx_registry.cpp | 17 ++++ libr4d/r4d_layout.cpp | 93 +++++++++++++++--- libr4d/r4d_moe.hip | 193 ++++++++++++++++++++++++------------- libr4d/r4d_plugin.h | 9 ++ libr4d/r4d_rows.cpp | 55 +++++++++++ libr4d/r4d_selftest.cpp | 64 ++++++++++++ libr4d/r4d_shapes.cpp | 43 +++++++++ libref/ref_moe.cpp | 59 ++++++++---- libref/ref_ops.h | 2 + libref/ref_registry.cpp | 21 ++++ libref/ref_shapes.cpp | 38 ++++++++ tests/ref_test.cpp | 56 ++++++++++- 17 files changed, 634 insertions(+), 137 deletions(-) diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index bec46cbb..3d63b4e2 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -685,20 +685,25 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, * say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed * weight positions have taken one each is split evenly across the table positions, in * declaration order. That is exactly right for the case tables exist for -- `moe_gemm_q`'s - * codes and scale planes are one of each per expert, always the same count -- and a division - * that does not come out whole is refused here rather than silently mis-grouped, which is the - * only failure the rule can have. */ - int per_tab = 0; + * codes and scale planes are one of each per expert, always the same count. + * + * WHERE IT DOES NOT COME OUT WHOLE, THE FIRST POSITIONS TAKE ONE MORE. A grouped GEMM whose + * experts are classes by number mod C -- `moe_gemm_q_mod4` -- gives its first `n % C` classes + * one expert more than the rest, and its tables are each class's codes then its scales, so + * that is exactly the first `2 * (n % C)` positions. Any other grouping is still refused, at + * issue, by the run checks: a table that is not one contiguous run of one shape. A list + * shorter than the tables is refused here. */ + int per_tab = 0, tab_extra = 0; if (n_tab > 0) { const int rest = n_w - w_max; - if (rest <= 0 || rest % n_tab != 0) { + if (rest < n_tab) { err(RAD_E_SCHEMA, "op '%s': %d weight operands declared; the schema has %d fixed weight operands and " - "%d weight TABLE operands, so %d must divide evenly among the tables and it does " - "not. A table takes one weight per expert and every table of one op takes the same " - "number", opname, n_w, w_max, n_tab, rest); + "%d weight TABLE operands, so %d leaves a table empty. A table takes one weight " + "per expert", opname, n_w, w_max, n_tab, rest); } else { per_tab = rest / n_tab; + tab_extra = rest % n_tab; } } else if (n_w < w_req || n_w > w_max) { err(RAD_E_SCHEMA, "op '%s': %d weight operands declared, but the schema has %d (%d " @@ -727,14 +732,16 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p, oi.weights.assign(w, w + n_w); /* The many-to-one map from declared weight to schema operand position, built here so the * layout pass, the converter and the issue path all read one answer. A fixed weight position - * takes one; a table position takes `per_tab` in a row. */ + * takes one; a table position takes `per_tab` in a row, and the first `tab_extra` of them one + * more. */ oi.weight_opd.assign((size_t)n_w, -1); { - int wi = 0; + int wi = 0, ti = 0; for (int k = 0; sc->operands && k < sc->n_operands && wi < n_w; ++k) { const int role = sc->operands[k].role; if (role == RAD_OPD_WTAB) { - for (int j = 0; j < per_tab && wi < n_w; ++j) oi.weight_opd[(size_t)wi++] = k; + const int run = per_tab + (ti++ < tab_extra ? 1 : 0); + for (int j = 0; j < run && wi < n_w; ++j) oi.weight_opd[(size_t)wi++] = k; } else if (role == RAD_OPD_WEIGHT) { oi.weight_opd[(size_t)wi++] = k; } diff --git a/docs/OPS.md b/docs/OPS.md index 9f454d75..773a7024 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -127,9 +127,12 @@ hand it. **How the declaration divides.** An op may carry several table operands — `moe_gemm_q` has four, the codes and the scale planes of its even experts and of its odd ones. Whatever is left after the fixed weight positions have taken one each -is split EVENLY across the table positions, in declaration order, and a division that does not come -out whole is refused at declare. That is exactly right for the case tables exist for: every table of -one MoE op takes one weight per expert. +is split EVENLY across the table positions, in declaration order, and where it does not come out +whole the first positions take one more each: `moe_gemm_q_mod4`'s first `n_expert % 4` classes hold +one expert more than the rest, and their codes and scales are its first table positions. A list too +short to give every table an entry is refused at declare, and a run that is not one contiguous, +same-shaped table is refused at issue. That is exactly right for the case tables exist for: every +table of one MoE op takes one weight per expert of its class. ## What the loader enforces @@ -553,6 +556,7 @@ every other rank waits out inside the block's all-reduce. | op | params | operands | |---|---|---| | `moe_gemm_q` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_odd`/opt `K_odd`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_odd`wt, `w_odd_scale`wt → `y` | +| `moe_gemm_q_mod4` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_1`/opt `K_1`/opt `N_2`/opt `K_2`/opt `N_3`/opt `K_3`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_1`wt, `w_1_scale`wt, `w_2`wt, `w_2_scale`wt, `w_3`wt, `w_3_scale`wt → `y` | | `scale_rows` | `M`(range) `n` `act` `dtype` | `x`, `s`, `add`? → `y` | The `wt` suffix is the table form and `w` alone is an ordinary weight operand; `moe_gemm`'s row @@ -571,6 +575,18 @@ columns of each output part and writes zeros after them, so the gated quantiser one layout for every row. Under the equal-division rule above the op's weight list is the even class's codes, its scales, then the odd class's codes and scales. +**`moe_gemm_q_mod4` is the same GEMM over four classes, by the expert's number mod 4.** +`w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting +to `N`, `K`); expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / +4)` of them. Four ranks splitting a five-block expert cannot share the extra block evenly over two +classes -- whichever two ranks take it carry three blocks of every even/odd pair against the other +two's two -- and over four they can: rank `r` takes two blocks of class `r` and one of each other, +five of every four experts on every rank. It is a separate op and not a parameter on `moe_gemm_q` +because the declaration divides a table op's weights over its table operands by count alone: the +operand list is the class count. Everything else -- `parts`, the zero fill of a narrower class, `a_order` +-- is `moe_gemm_q`'s, and the weight list is class 0's codes and scales, then class 1's, 2's and +3's. + ### `a_order`: which rows a grouped GEMM's activation has A routed block runs two `moe_gemm_q` ops and **they disagree about what a row of `a` is**, which is diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index ad745531..0bb671c7 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -250,6 +250,17 @@ std::vector build_cases() { add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 256), HI("K_odd", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), HS("a_order", "sorted"), HS("dtype", "w8a8") }); + /* Four classes at three widths -- a four-rank slice of a five-block expert is two blocks + * of one class and one of each other -- over ten experts, so classes 2 and 3 hold one + * fewer than 0 and 1: the gate/up pair and the down projection. */ + add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 128), HI("K", 128), HI("N_1", 256), + HI("N_2", 128), HI("N_3", 128), HI("parts", 2), + HI("n_expert", 10), HI("top_k", 2), HI("group", 128), + HS("a_order", "token"), HS("dtype", "w8a8") }); + add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 64), HI("K", 128), HI("K_1", 128), + HI("K_2", 256), HI("K_3", 128), HI("n_expert", 10), + HI("top_k", 2), HI("group", 128), HS("a_order", "sorted"), + HS("dtype", "w8a8") }); } add("moe_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("expert_base", 0) }); diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 3cb20906..90304d89 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -104,6 +104,7 @@ int avx_isa_force(int level); /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ + X(moe_gemm_q_mod4) \ /* ---- gated delta net */ \ X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \ X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index 73660220..aad45cbc 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -294,8 +294,8 @@ AVX_KERNEL(moe_scatter) { * whose meaning changes with its extent is exactly the shape a checker cannot see: if both * implementations gather they agree with each other, and a harness that sizes the operand the way * the gather wants never exercises the other reading. */ -static int moe_gemm_impl(const RadArgs* a, bool quant) { - const int n_opd = quant ? 9 : 5; +static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { + const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5; if (!rad_args_have(a, n_opd)) return RAD_E_INVAL; const RadTensor* A = &a->t[0]; const RadTensor* as_ = quant ? rad_arg_in(a, 1) : nullptr; @@ -303,12 +303,18 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { const RadTensor* ws_ = quant ? rad_arg_in(a, 3) : nullptr; const RadTensor* sorted = &a->t[quant ? 4 : 2]; const RadTensor* off = &a->t[quant ? 5 : 3]; - const RadTensor* Y = &a->t[quant ? 8 : 4]; + const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4]; /* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY, expert e at entry e / 2 of class - * e % 2; the plain arm's are one. */ + * e % 2 -- or for `moe_gemm_q_mod4` four, entry e / 4 of class e % 4; the plain arm's are + * one. */ const bool two = quant; + const int nc = quant ? ncls : 1; const RadTensor* W1 = two ? &a->t[6] : W; const RadTensor* ws1_ = two ? rad_arg_in(a, 7) : nullptr; + const RadTensor* Wq[4] = { W, W1, quant && nc == 4 ? &a->t[8] : W, + quant && nc == 4 ? &a->t[10] : W }; + const RadTensor* wsq[4] = { ws_, ws1_, quant && nc == 4 ? rad_arg_in(a, 9) : nullptr, + quant && nc == 4 ? rad_arg_in(a, 11) : nullptr }; const char* ord = p_str(a, "a_order", "token"); const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0; @@ -316,19 +322,28 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { const int64_t N0 = p_int(a, "N", W->rank >= 3 ? W->shape[1] : 0); const int64_t K0 = p_int(a, "K", W->rank >= 3 ? W->shape[2] : 0); - const int64_t N1 = two ? p_int(a, "N_odd", N0) : N0; - const int64_t K1 = two ? p_int(a, "K_odd", K0) : K0; + /* Each class's geometry, defaulting to class 0's: N_odd/K_odd at two, N_q/K_q at four. */ + static const char* const kN4[4] = { "N", "N_1", "N_2", "N_3" }; + static const char* const kK4[4] = { "K", "K_1", "K_2", "K_3" }; + int64_t Nq[4] = { N0, N0, N0, N0 }, Kq[4] = { K0, K0, K0, K0 }; + for (int q = 1; q < nc; ++q) { + Nq[q] = p_int(a, nc == 4 ? kN4[q] : "N_odd", N0); + Kq[q] = p_int(a, nc == 4 ? kK4[q] : "K_odd", K0); + } const int64_t parts = two ? p_int(a, "parts", 1) : 1; const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0); const int64_t top_k = p_int(a, "top_k", 1); - if (N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || parts <= 0 || n_expert <= 0 || top_k <= 0) - return RAD_E_SHAPE; - if (N0 % parts || N1 % parts) return RAD_E_SHAPE; - /* The output is the wider class's width, the activation the longer class's K. */ - const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; - const int64_t ne0 = two ? (n_expert + 1) / 2 : n_expert, ne1 = two ? n_expert / 2 : 0; - if (W->rank < 3 || W->shape[0] < ne0) return RAD_E_SHAPE; - if (two && (W1->rank < 3 || W1->shape[0] < ne1)) return RAD_E_SHAPE; + if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; + /* The output is the widest class's width, the activation the longest class's K; class q + * holds ceil((n - q) / nc) experts. */ + int64_t N = 0, K = 0; + for (int q = 0; q < nc; ++q) { + if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE; + if (Nq[q] > N) N = Nq[q]; + if (Kq[q] > K) K = Kq[q]; + const int64_t neq = (n_expert + nc - 1 - q) / nc; + if (neq > 0 && (Wq[q]->rank < 3 || Wq[q]->shape[0] < neq)) return RAD_E_SHAPE; + } const int64_t T = numel(Y) / N; if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE; @@ -371,11 +386,11 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { * be read as a table at all, which is refused BEFORE any parallel region because an OpenMP * body cannot return. */ for (int64_t e = 0; e < n_expert; ++e) { - const bool odd = two && (e & 1); - const RadTensor* tw = odd ? W1 : W; - const RadTensor* ts = odd ? ws1_ : ws_; - const int64_t ix = two ? e / 2 : e; - const int64_t n = odd ? N1 : N0, k = odd ? K1 : K0; + const int q = (int)(e % nc); + const RadTensor* tw = Wq[q]; + const RadTensor* ts = wsq[q]; + const int64_t ix = e / nc; + const int64_t n = Nq[q], k = Kq[q]; we[e] = expert_entry(tw, ix); if (!we[e].data) return RAD_E_STRIDE; if (we[e].rank < 2 || we[e].shape[0] < n || we[e].shape[1] < k) return RAD_E_SHAPE; @@ -427,8 +442,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { for (int64_t i = 0; i < T; ++i) { if (atok[i] < 0) { stt(Y, i * y_rs + n * y_cs, 0.0f); continue; } const int64_t e = aexp[i]; - const bool odd = two && (e & 1); - const int64_t fc = (odd ? N1 : N0) / parts, ke = odd ? K1 : K0; + const int q = (int)(e % nc); + const int64_t fc = Nq[q] / parts, ke = Kq[q]; if (j >= fc) { stt(Y, i * y_rs + n * y_cs, 0.0f); continue; } const int64_t wr = pp * fc + j; /* The expert's weight row is packed when the expert CHANGES, which -- because the @@ -454,6 +469,7 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { AVX_KERNEL(moe_gemm) { return moe_gemm_impl(a, false); } AVX_KERNEL(moe_gemm_q) { return moe_gemm_impl(a, true); } +AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); } /* ------------------------------------------------------------------ moe_gather */ /* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)]. diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 17d687eb..718dda0b 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -263,6 +263,18 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), 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 over four classes by the expert's number mod 4, `w_q` class q at [N_q, K_q]. Mirrors + * libref's and libr4d's schema exactly. */ +static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), + P_INT("n_expert"), P_INT("top_k"), P_INT("group"), + P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), + P_INTO("K_1"), P_INTO("N_2"), P_INTO("K_2"), + P_INTO("N_3"), P_INTO("K_3"), P_INTO("parts") }; +static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), + WTAB("w_scale"), OPD("sorted_tok"), + OPD("expert_offset"), WTAB("w_1"), + WTAB("w_1_scale"), WTAB("w_2"), WTAB("w_2_scale"), + WTAB("w_3"), WTAB("w_3_scale"), OUT("y") }; /* `shared` + `shared_gate` present = the shared arm folded in: y = narrow(shared * * act(gate)) + narrow(gathered), the unfused pair's two narrows carried in the stores. `act` is @@ -500,6 +512,8 @@ static const RadOpSchema kSchemas[] = { { "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm), "grouped GEMM over the expert-sorted rows." }, { "moe_gemm_q", ARR(pMoeGemmQ), ARR(oMoeGemmQ), "grouped GEMM over the expert-sorted rows, quantised operands." }, +{ "moe_gemm_q_mod4", ARR(pMoeGemmQMod4), ARR(oMoeGemmQMod4), + "grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4." }, { "moe_gather", ARR(pMoeGather), ARR(oMoeGather), "weighted scatter back to token order." }, { "row_topk", ARR(pRowTopk), ARR(oRowTopk), "exact per-row top-R." }, { "row_topk_merge", ARR(pRowTopkMerge), ARR(oRowTopkMerge), @@ -685,6 +699,9 @@ SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted r L(moe_gemm)), SIMPLE("avx_moe_gemm_q", "moe_gemm_q", "moe", "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT, L(moe_gemm_q)), +SIMPLE("avx_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", + "grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4", + DT_FLOAT, L(moe_gemm_q_mod4)), SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT, L(moe_gather)), SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)), diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index e520a8fe..700a4ce9 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -256,6 +256,29 @@ int moe_view(const RadParam* p, int n_p, int operand, MoeView* v) { } return RAD_OK; } + +/* `moe_gemm_q_mod4`'s four classes: operands 6/7, 8/9 and 10/11 are classes 1, 2 and 3 at + * N_1/K_1, N_2/K_2 and N_3/K_3, answered as 2/3 at that geometry -- the same view, one class + * further along. */ +int moe_view_mod4(const RadParam* p, int n_p, int operand, MoeView* v) { + if (n_p < 0 || n_p > 32 || (n_p > 0 && !p)) return RAD_E_INVAL; + v->n = n_p; + v->operand = operand; + for (int i = 0; i < n_p; ++i) v->p[i] = p[i]; + if (operand < 6 || operand > 11) return RAD_OK; + static const char* const kN[4] = { "N", "N_1", "N_2", "N_3" }; + static const char* const kK[4] = { "K", "K_1", "K_2", "K_3" }; + const int q = (operand - 4) / 2; /* 6/7 -> 1, 8/9 -> 2, 10/11 -> 3 */ + v->operand = 2 + (operand & 1); + const long long nq = r4d_pgeti_or(p, n_p, kN[q], -1); + const long long kq = r4d_pgeti_or(p, n_p, kK[q], -1); + for (int i = 0; i < n_p; ++i) { + if (!v->p[i].key) continue; + if (nq > 0 && std::strcmp(v->p[i].key, "N") == 0) v->p[i].ival = nq; + if (kq > 0 && std::strcmp(v->p[i].key, "K") == 0) v->p[i].ival = kq; + } + return RAD_OK; +} } /* namespace */ /* ================================================================== the hooks @@ -819,21 +842,24 @@ void moew5_row(const uint8_t* s, uint8_t* d, int64_t K, uint8_t* nib, bool forwa } } /* namespace */ -extern "C" int r4d_rad_layout_moe_w4(const RadParam* p, int n_p, int operand, - const RadEncoding* enc, const int* sel, - const RadTensor* pl, int n, RadLayout* out) { +namespace { +using MoeViewFn = int (*)(const RadParam*, int, int, MoeView*); + +int moew4_layout_by(MoeViewFn view, const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, + RadLayout* out) { MoeView v; - const int rc = moe_view(p, n_p, operand, &v); + const int rc = view(p, n_p, operand, &v); return rc != RAD_OK ? rc : moew4_enc_layout(v.p, v.n, v.operand, enc, sel, pl, n, out, nullptr); } -extern "C" int r4d_rad_relayout_moe_w4(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) { +int moew4_relayout_by(MoeViewFn view, 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) { MoeView v; RadLayout L; WGeom g; - int rc = moe_view(p, n_p, operand, &v); + int rc = view(p, n_p, operand, &v); if (rc == RAD_OK) rc = moew4_enc_layout(v.p, v.n, v.operand, enc, sel, pl, n, &L, &g); if (rc != RAD_OK) return rc; if (dst_bytes != L.bytes) return RAD_E_SHAPE; @@ -857,13 +883,13 @@ extern "C" int r4d_rad_relayout_moe_w4(const RadParam* p, int n_p, int operand, return RAD_OK; } -extern "C" int r4d_rad_unrelayout_moe_w4(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) { +int moew4_unrelayout_by(MoeViewFn view, 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) { MoeView v; RadLayout L; WGeom g; - int rc = moe_view(p, n_p, operand, &v); + int rc = view(p, n_p, operand, &v); if (rc == RAD_OK) rc = moew4_enc_layout(v.p, v.n, v.operand, enc, sel, pl, n, &L, &g); if (rc != RAD_OK) return rc; if (src_bytes != L.bytes) return RAD_E_SHAPE; @@ -887,6 +913,41 @@ extern "C" int r4d_rad_unrelayout_moe_w4(const RadParam* p, int n_p, int operand return RAD_OK; } +} /* namespace */ + +extern "C" int r4d_rad_layout_moe_w4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return moew4_layout_by(moe_view, p, n_p, operand, enc, sel, pl, n, out); +} +extern "C" int r4d_rad_relayout_moe_w4(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) { + return moew4_relayout_by(moe_view, p, n_p, operand, enc, sel, pl, n, dst, dst_bytes); +} +extern "C" int r4d_rad_unrelayout_moe_w4(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) { + return moew4_unrelayout_by(moe_view, p, n_p, operand, enc, sel, src, src_bytes, pl, n); +} +extern "C" int r4d_rad_layout_moe_w4_mod4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + return moew4_layout_by(moe_view_mod4, p, n_p, operand, enc, sel, pl, n, out); +} +extern "C" int r4d_rad_relayout_moe_w4_mod4(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) { + return moew4_relayout_by(moe_view_mod4, p, n_p, operand, enc, sel, pl, n, dst, dst_bytes); +} +extern "C" int r4d_rad_unrelayout_moe_w4_mod4(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) { + return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n); +} + extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { @@ -895,3 +956,11 @@ extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand, return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl, n, out); } +extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + MoeView v; + const int rc = moe_view_mod4(p, n_p, operand, &v); + return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl, + n, out); +} diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 261d8f6d..99197259 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -823,15 +823,26 @@ __device__ __forceinline__ uint4 w4_load(const uint8_t* __restrict__ src, bool l * separate operands because every entry of one table has one geometry. Expert e is entry e / 2 of * class e % 2. The classes differ when a rank holds an uneven slice of each expert's width -- three * 128-column blocks of one parity and two of the other -- and are the same geometry otherwise. + * `moe_gemm_q_mod4` has four, by the expert's number mod 4: expert e is entry e / 4 of class e % 4, + * which is what lets four ranks take the extra block of a five-block expert in turn. * * `n` is the weight's rows and `k` its K; `w_ld` the packed byte pitch of a weight row and `s_ld` * the scale plane's row pitch in elements. */ struct MoeCls { - const void* const* w; size_t w_s0; - const void* const* s; size_t s_s0; + const void* const* w; + const void* const* s; + uint32_t w_s0, s_s0; /* bytes an entry of a stacked plane; 0 marks a pointer table */ uint32_t n, k, w_ld, s_ld; - uint32_t tab[4]; /* W4: the code table, r4d_args.h's kW4IntPerm, kW4nlPerm or kW5nlMagPerm */ }; +/* W4: the code table, r4d_args.h's kW4IntPerm, kW4nlPerm or kW5nlMagPerm -- one for every class, + * since every class is one format. + * + * FOUR CLASSES AND THE TABLE MUST FIT RAD_KPARAM_BLOB (256 bytes) BESIDE EVERYTHING ELSE, because + * a kernel's arguments are packed into one descriptor whether it is launched or described: four + * classes at 40 bytes, the five operand pointers and the map, eight words and this. That is why a + * class carries 32-bit entry strides and no table of its own, and why `mode` packs three small + * values into one word. */ +struct MoeTab { uint32_t v[4]; }; /* W4 IS THE WEIGHT'S FORM: 0 block E4M3, 1 four-bit with one bf16 scale a (row, 128 of K), 2 the * same codes with one E4M3 scale a (row, 64 of K) times the fixed kW4G64Scale (w4nl64a8h), 3 the @@ -843,12 +854,14 @@ template __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( const uint8_t* __restrict__ Aq, const float* __restrict__ As, - const MoeCls c_even, const MoeCls c_odd, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, - uint16_t* __restrict__ Y, - uint32_t T, uint32_t N, uint32_t parts, uint32_t n_expert, uint32_t top_k, uint32_t a_sorted, - uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, - const uint32_t* __restrict__ map) { + uint16_t* __restrict__ Y, const uint32_t* __restrict__ map, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t top_k, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + /* `mode`: bit 0 `a_sorted`, bits 1-2 the class shift (1 for two classes, 2 for four), bits + * 8 up `parts`. */ + const uint32_t a_sorted = mode & 1u, cshift = (mode >> 1) & 3u, parts = mode >> 8; constexpr uint32_t FM = MT * 16, FN = NTL * 16; constexpr uint32_t NTHR = WGM * WGN * kWave; constexpr uint32_t WM = MT / WGM, WN = NTL / WGN; @@ -1014,8 +1027,10 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( if (ES && run != jrun) { rs = re; ++run; continue; } /* The expert's class, and where this block's columns sit in its weight. Block-uniform: a - * pad tile zeroes the run's rows and moves on without touching LDS or a barrier. */ - const MoeCls& C = (e & 1u) ? c_odd : c_even; + * pad tile zeroes the run's rows and moves on without touching LDS or a barrier. `cshift` + * is 1 for two classes and 2 for four; c_2 and c_3 are never read at two. */ + const uint32_t cls = e & ((1u << cshift) - 1u); + const MoeCls& C = cls == 0u ? c_even : cls == 1u ? c_odd : cls == 2u ? c_2 : c_3; const uint32_t fc = C.n / parts; if (j0 >= fc) { const uint32_t nr = re - rs; @@ -1033,8 +1048,8 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( const uint32_t kb_n = wn0 / kBlock; /* the weight scale's N row for this block */ if constexpr (W4) (void)kb_n; /* w4 scales vary per ROW, not per N block */ - const uint8_t* Wp = wtab_at(C.w, C.w_s0, e >> 1); - const uint16_t* Wsp = (const uint16_t*)wtab_at(C.s, C.s_s0, e >> 1); + const uint8_t* Wp = wtab_at(C.w, C.w_s0, e >> cshift); + const uint16_t* Wsp = (const uint16_t*)wtab_at(C.s, C.s_s0, e >> cshift); /* SK: A WAVE WHOSE M TILES ARE ALL PAST THE RUN has nothing to accumulate. Under AL the * run is the block's rows [rs, re) from its first row, so that is a wave-uniform test; @@ -1152,9 +1167,9 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( const uint32_t r = sn + p * kRPP; if (r >= FN) continue; if constexpr (W4 == 4) - stage8_store(s_b, r, sk, w5_expand(bpre4[p], spre[p], C.tab)); + stage8_store(s_b, r, sk, w5_expand(bpre4[p], spre[p], tab.v)); else if constexpr (W4) - stage8_store(s_b, r, sk, w4_expand(bpre4[p], C.tab)); + stage8_store(s_b, r, sk, w4_expand(bpre4[p], tab.v)); else stage8_store(s_b, r, sk, bpre8[p]); } @@ -2117,42 +2132,56 @@ static int g_moe_prefill_form = 0; /* Both instantiations, from one body. The only things that differ are the weight table's dtype and * its two pitches, so the fp8 launcher and the w4 one are the same forty lines with three values * swapped -- and writing them twice is how a shape check drifts between two paths that must agree. - */ + * + * `ncls` is the op's class count: 2 for `moe_gemm_q`, whose odd class is operands 6 and 7 at + * N_odd/K_odd, and 4 for `moe_gemm_q_mod4`, whose classes 1..3 are operands 6/7, 8/9 and 10/11 at + * N_1/K_1, N_2/K_2 and N_3/K_3, with `y` after them at 12. Everything else is one body. */ template -static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { +static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { int emit_rc = RAD_OK; + if (ncls != 2 && ncls != 4) return R4D_NO(RAD_E_INVAL); const RadTensor* Aq = r4d_opt(a, 0); const RadTensor* As = r4d_opt(a, 1); - const RadTensor* W = r4d_opt(a, 2); - const RadTensor* Ws = r4d_opt(a, 3); const RadTensor* sorted = r4d_opt(a, 4); const RadTensor* off = r4d_opt(a, 5); - const RadTensor* W1 = r4d_opt(a, 6); - const RadTensor* Ws1 = r4d_opt(a, 7); - const RadTensor* Y = r4d_opt(a, 8); - if (!Aq || !As || !W || !Ws || !sorted || !off || !Y || !W1 || !Ws1) - return R4D_NO(RAD_E_INVAL); + const RadTensor* Wc[4] = { r4d_opt(a, 2), r4d_opt(a, 6), + ncls == 4 ? r4d_opt(a, 8) : nullptr, + ncls == 4 ? r4d_opt(a, 10) : nullptr }; + const RadTensor* Wsc[4] = { r4d_opt(a, 3), r4d_opt(a, 7), + ncls == 4 ? r4d_opt(a, 9) : nullptr, + ncls == 4 ? r4d_opt(a, 11) : nullptr }; + const RadTensor* Y = r4d_opt(a, ncls == 4 ? 12 : 8); + if (!Aq || !As || !sorted || !off || !Y) return R4D_NO(RAD_E_INVAL); + for (int q = 0; q < ncls; ++q) + if (!Wc[q] || !Wsc[q]) return R4D_NO(RAD_E_INVAL); if (!Aq->data || !As->data || !sorted->data || !off->data || !Y->data) return R4D_NO(RAD_E_INVAL); - /* Each class's weight geometry, the odd one defaulting to the even one's; the output is as - * wide as the wider class and the activation as long as the longer K. */ - const long long N0 = r4d_geti_or(a, "N", 0); - const long long K0 = r4d_geti_or(a, "K", 0); - const long long N1 = r4d_geti_or(a, "N_odd", N0); - const long long K1 = r4d_geti_or(a, "K_odd", K0); + /* Each class's weight geometry, the others defaulting to class 0's; the output is as wide as + * the widest class and the activation as long as the longest K. */ + static const char* const kNk[4][2] = { { "N", "K" }, { "N_1", "K_1" }, { "N_2", "K_2" }, + { "N_3", "K_3" } }; + long long Nc[4] = { 0, 0, 0, 0 }, Kc[4] = { 0, 0, 0, 0 }; + Nc[0] = r4d_geti_or(a, "N", 0); + Kc[0] = r4d_geti_or(a, "K", 0); + for (int q = 1; q < ncls; ++q) { + Nc[q] = r4d_geti_or(a, ncls == 4 ? kNk[q][0] : "N_odd", Nc[0]); + Kc[q] = r4d_geti_or(a, ncls == 4 ? kNk[q][1] : "K_odd", Kc[0]); + } const long long parts = r4d_geti_or(a, "parts", 1); const long long n_expert = r4d_geti_or(a, "n_expert", 0); const long long top_k = r4d_geti_or(a, "top_k", 0); const long long group = r4d_geti_or(a, "group", kBlock); - if (N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || parts <= 0 || n_expert <= 0 || top_k <= 0) - return R4D_NO(RAD_E_SHAPE); + if (parts <= 0 || n_expert <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE); if (group != (long long)kBlock) return R4D_NO(RAD_E_SHAPE); - /* A part of either class is whole 64-column tiles, so a tile is all weight or all padding. */ - if (K0 % kBlock || K1 % kBlock || N0 % (64 * parts) || N1 % (64 * parts)) - return R4D_NO(RAD_E_SHAPE); - const long long N = N0 > N1 ? N0 : N1; - const long long K = K0 > K1 ? K0 : K1; + long long N = 0, K = 0; + for (int q = 0; q < ncls; ++q) { + if (Nc[q] <= 0 || Kc[q] <= 0) return R4D_NO(RAD_E_SHAPE); + /* A part of every class is whole 64-column tiles, so a tile is all weight or all padding. */ + if (Kc[q] % kBlock || Nc[q] % (64 * parts)) return R4D_NO(RAD_E_SHAPE); + if (Nc[q] > N) N = Nc[q]; + if (Kc[q] > K) K = Kc[q]; + } if (Aq->dtype != RAD_F8E4M3 || As->dtype != RAD_F32 || Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (sorted->dtype != RAD_I32 || off->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); @@ -2192,9 +2221,10 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { auto cls_of = [&](const RadTensor* w, const RadTensor* ws, long long cnt, long long n, long long k, MoeCls* c) -> int { long long w_ld = 0, ws_ld = 0; + size_t w_s0 = 0, s_s0 = 0; int rc = wtab_of(w, W4 == 4 ? (uint32_t)R4D_DT_MOEW5 : W4 ? (uint32_t)R4D_DT_MOEW4 : (uint32_t)RAD_F8E4M3, - W4 == 4 ? 5 : W4 ? 4 : 8, cnt, n, k, &c->w, &c->w_s0, &w_ld); + W4 == 4 ? 5 : W4 ? 4 : 8, cnt, n, k, &c->w, &w_s0, &w_ld); if (rc != RAD_OK) return rc; if constexpr (W4 >= 2) { /* One E4M3 byte per (row, group of 64 or 32 K), and the stored row is exactly those @@ -2203,7 +2233,7 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { * its row stride is k, the stored row k/64 or k/32 (r4d_layout.cpp). A tile's scales * are one sixteen- or thirty-two-bit word, so the kernel's pitch is k/128 words. */ rc = wtab_of(ws, RAD_F8E4M3, 8, cnt, n, k / (kBlock / (W4 == 3 ? 4 : 2)), &c->s, - &c->s_s0, &ws_ld); + &s_s0, &ws_ld); if (rc != RAD_OK) return rc; /* A 5-bit row is its nibbles then its sign bits, so its pitch is whole bytes of both; * the kernel finds the signs K/2 bytes in. */ @@ -2212,27 +2242,42 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { ws_ld = k / kBlock; } else if constexpr (W4) { /* The scale plane is one bf16 per (row, group of 128 K) -- not per 128x128 tile. */ - rc = wtab_of(ws, RAD_BF16, 16, cnt, n, k / kBlock, &c->s, &c->s_s0, &ws_ld); + rc = wtab_of(ws, RAD_BF16, 16, cnt, n, k / kBlock, &c->s, &s_s0, &ws_ld); if (rc != RAD_OK) return rc; if (w_ld % 2) return R4D_NO(RAD_E_STRIDE); w_ld /= 2; } else { rc = wtab_of(ws, RAD_BF16, 16, cnt, (n + kBlock - 1) / kBlock, k / kBlock, &c->s, - &c->s_s0, &ws_ld); + &s_s0, &ws_ld); if (rc != RAD_OK) return rc; } + /* A stacked entry is one expert's plane, far below 4 GiB; a pointer table is 0. */ + if (w_s0 > 0xFFFFFFFFull || s_s0 > 0xFFFFFFFFull) return R4D_NO(RAD_E_STRIDE); + c->w_s0 = (uint32_t)w_s0; + c->s_s0 = (uint32_t)s_s0; c->n = (uint32_t)n; c->k = (uint32_t)k; c->w_ld = (uint32_t)w_ld; c->s_ld = (uint32_t)ws_ld; - for (int i = 0; i < 4; ++i) c->tab[i] = tab[i]; return RAD_OK; }; - MoeCls ce{}, co{}; - int rc = cls_of(W, Ws, (n_expert + 1) / 2, N0, K0, &ce); - if (rc != RAD_OK) return rc; - rc = cls_of(W1, Ws1, n_expert / 2, N1, K1, &co); - if (rc != RAD_OK) return rc; + /* Class q holds the experts e with e % ncls == q, entry e / ncls: ceil((n - q) / ncls) of + * them. At two classes the last two are never read and stay zero. */ + MoeCls cl[4]{}; + for (int q = 0; q < ncls; ++q) { + const int rc = cls_of(Wc[q], Wsc[q], (n_expert + ncls - 1 - q) / ncls, Nc[q], Kc[q], + &cl[q]); + if (rc != RAD_OK) return rc; + } + const MoeCls& ce = cl[0]; + const MoeCls& co = cl[1]; + const MoeCls& c2 = cl[2]; + const MoeCls& c3 = cl[3]; + const uint32_t cshift = ncls == 4 ? 2u : 1u; + if (parts > 0xFFFFFF) return R4D_NO(RAD_E_SHAPE); + const uint32_t mode = (a_sorted ? 1u : 0u) | (cshift << 1) | ((uint32_t)parts << 8); + MoeTab tabv{}; + for (int i = 0; i < 4; ++i) tabv.v[i] = tab[i]; /* THE BAND: a decode step takes the (tile, run) form -- one 16-row tile of runs spread over * blocks, see the kernel's ES note -- and anything with runs of several rows takes the aligned @@ -2245,11 +2290,11 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { const unsigned tiles = (unsigned)((T + 15) / 16); emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel<1, 4, 1, 4, W4, true>), dim3(tiles * 16u, ny), dim3(4 * kWave), 0, - (const uint8_t*)Aq->data, (const float*)As->data, ce, co, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, - (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)parts, - (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), - (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, nullptr); + (uint16_t*)Y->data, nullptr, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else { /* THE PREFILL FORM IS ALIGNED TO RUNS when the scratch for a map is there, and uniform * when it is not. A caller that never asked the scratch hook -- a tool replaying a @@ -2274,39 +2319,37 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk) { if (wide_n) emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), dim3((unsigned)cap, nyw), dim3(8 * kWave), 0, - (const uint8_t*)Aq->data, (const float*)As->data, ce, co, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, - (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)parts, - (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), - (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, - (const uint32_t*)map); + (uint16_t*)Y->data, (const uint32_t*)map, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); else emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), dim3((unsigned)cap, ny), dim3(4 * kWave), 0, - (const uint8_t*)Aq->data, (const float*)As->data, ce, co, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, - (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)parts, - (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), - (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, - (const uint32_t*)map); + (uint16_t*)Y->data, (const uint32_t*)map, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else if (wide_n) { emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), nyw), dim3(8 * kWave), 0, - (const uint8_t*)Aq->data, (const float*)As->data, ce, co, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, - (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)parts, - (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), - (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, nullptr); + (uint16_t*)Y->data, nullptr, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } else { emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel), dim3((unsigned)((T + kPrefillRows - 1) / kPrefillRows), ny), dim3(4 * kWave), 0, - (const uint8_t*)Aq->data, (const float*)As->data, ce, co, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, (const int32_t*)sorted->data, (const int32_t*)off->data, - (uint16_t*)Y->data, (uint32_t)T, (uint32_t)N, (uint32_t)parts, - (uint32_t)n_expert, (uint32_t)top_k, (uint32_t)(a_sorted ? 1 : 0), - (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, nullptr); + (uint16_t*)Y->data, nullptr, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); } } if (emit_rc != RAD_OK) return emit_rc; @@ -2356,6 +2399,20 @@ static int rad_moe_gemm_w4a8_body(const RadArgs* a, const R4dSink& sk) { } R4D_ENTRY(r4d_rad_moe_gemm_w4a8, rad_moe_gemm_w4a8_body) +/* `moe_gemm_q_mod4`: the same launches over four classes, by the expert's number mod 4. The run + * map and its scratch are the two-class op's -- they depend on the offsets and nothing else. */ +extern "C" int r4d_rad_moe_gemm_q_mod4(const RadArgs* a, RadStream s) { + return moe_gemm_launch<0>(a, r4d_stream_sink(s), 4); +} +static int rad_moe_gemm_w4a8_mod4_body(const RadArgs* a, const R4dSink& sk) { + const char* wdt = r4d_gets(a, "dtype"); + if (wdt && !std::strcmp(wdt, "w4nl64a8h")) return moe_gemm_launch<2>(a, sk, 4); + if (wdt && !std::strcmp(wdt, "w4nl32a8h")) return moe_gemm_launch<3>(a, sk, 4); + if (wdt && !std::strcmp(wdt, "w5nl64a8h")) return moe_gemm_launch<4>(a, sk, 4); + return moe_gemm_launch<1>(a, sk, 4); +} +R4D_ENTRY(r4d_rad_moe_gemm_w4a8_mod4, rad_moe_gemm_w4a8_mod4_body) + /* `moe_gemm` at bf16: operands a, w (one table), sorted_tok, expert_offset -> y. The band and the * three forms are moe_gemm_launch's and are chosen by the same rule from the same arguments, so the * scratch hook that sizes the run map is the same function too. diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index e58bac6b..d0cc1854 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -230,6 +230,11 @@ int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs*); * section for the stored plane. */ int r4d_rad_moe_gemm_w4a8 (const RadArgs*, RadStream); int r4d_rad_moe_gemm_w4a8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +/* `moe_gemm_q_mod4`: the same two kernels over four classes of experts, by the expert's number + * mod 4. The scratch hooks are the two-class ones. */ +int r4d_rad_moe_gemm_q_mod4 (const RadArgs*, RadStream); +int r4d_rad_moe_gemm_w4a8_mod4 (const RadArgs*, RadStream); +int r4d_rad_moe_gemm_w4a8_mod4_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* `moe_gemm` at bf16: one weight table of the checkpoint's own row-major planes, no scales. The * same grouping and the same three forms; its scratch hook sizes the same run map. */ int r4d_rad_moe_gemm_bf16 (const RadArgs*, RadStream); @@ -325,11 +330,14 @@ R4D_HOOKS(mtp_e4m3) R4D_HOOKS(w4) R4D_HOOKS(w2a8) R4D_HOOKS(moe_w4) +R4D_HOOKS(moe_w4_mod4) #undef R4D_HOOKS int r4d_rad_layout_fp8_rowmajor(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_layout_moe_fp8(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); +int r4d_rad_layout_moe_fp8_mod4(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); int r4d_rad_layout_w8a16(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_layout_w8a8(const RadParam*, int, int, const RadEncoding*, const int*, @@ -466,6 +474,7 @@ int r4d_shape_router_topk (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_router_topk_scatter(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_moe_scatter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gemm_q (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_moe_gemm_q_mod4(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gather (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk_merge (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 918cb204..696c5418 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -877,6 +877,34 @@ static const RadOperandSpec oMoeGemmQ[] = { { "w_odd_scale", RAD_OPD_WTAB, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +/* THE SAME GEMM OVER FOUR CLASSES, BY THE EXPERT'S NUMBER MOD 4: `w`/`w_scale` hold class 0 at + * [N, K] and `w_q`/`w_q_scale` class q at [N_q, K_q], expert e being entry e / 4 of class e % 4. + * Four ranks splitting a five-block expert cannot share the extra block evenly over two classes -- + * whichever two ranks take it carry three blocks of every even/odd pair against the others' two -- + * and over four they can: rank r takes two blocks of class r and one of each other, five of every + * four experts. A separate op and not a parameter on `moe_gemm_q`, because the declaration divides + * a table op's weights over its table operands by count alone (core/build/rad_builder.cpp): the + * operand list is the class count. `y` follows the last class. */ +static const RadParamSpec pMoeGemmQMod4[] = { + P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_INT("group"), + P_STR("a_order"), P_STR("dtype"), P_INTO("N_1"), P_INTO("K_1"), P_INTO("N_2"), P_INTO("K_2"), + P_INTO("N_3"), P_INTO("K_3"), P_INTO("parts"), +}; +static const RadOperandSpec oMoeGemmQMod4[] = { + { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 1 }, + { "w", RAD_OPD_WTAB, 0 }, + { "w_scale", RAD_OPD_WTAB, 0 }, + { "sorted_tok", RAD_OPD_IN, 0 }, + { "expert_offset", RAD_OPD_IN, 0 }, + { "w_1", RAD_OPD_WTAB, 0 }, + { "w_1_scale", RAD_OPD_WTAB, 0 }, + { "w_2", RAD_OPD_WTAB, 0 }, + { "w_2_scale", RAD_OPD_WTAB, 0 }, + { "w_3", RAD_OPD_WTAB, 0 }, + { "w_3_scale", RAD_OPD_WTAB, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STR("dtype"), /* The shared arm's gate, and it is present exactly when `shared` and `shared_gate` are. @@ -1990,6 +2018,11 @@ static const RadOpSchema kSchemas[] = { "[N, K] and `w_odd`/`w_odd_scale` the odd ones at [N_odd, K_odd], expert e at entry " "e/2. The output is max(N, N_odd) wide in `parts` stacked parts, and a class narrower " "than that fills each part's leading columns and zeros the rest."), + SCHEMA("moe_gemm_q_mod4", pMoeGemmQMod4, oMoeGemmQMod4, + "moe_gemm_q over FOUR weight-table classes by the expert's number mod 4: `w`/`w_scale` " + "hold class 0 at [N, K] and `w_q`/`w_q_scale` class q at [N_q, K_q], expert e at entry " + "e/4 of class e%4. The output is as wide as the widest class in `parts` stacked parts, " + "and a narrower class fills each part's leading columns and zeros the rest."), SCHEMA("moe_gather", pMoeGather, oMoeGather, "scatters the sorted expert output back to token order and weights it. The sum over a " "token's slots runs in ASCENDING SLOT order, which is what makes it reproducible -- " @@ -4314,6 +4347,28 @@ static const RadKernelInfo kKernels[] = { r4d_rad_layout_moe_w4, r4d_rad_relayout_moe_w4, nullptr, r4d_rad_unrelayout_moe_w4, nullptr, r4d_rad_moe_gemm_w4a8_describe }, +{ "moe_gemm_fp8a8_mod4", "moe_gemm_q_mod4", "moe", + "moe_gemm_fp8a8 over four classes of experts by number mod 4: the same kernel, each run reading " + "its class's table", + "as moe_gemm_fp8a8, every class", + "as moe_gemm_fp8a8", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeGemmQ), NOTUNE, + nullptr, nullptr, r4d_rad_moe_gemm_q_mod4, r4d_rad_moe_gemm_q_scratch, + r4d_rad_layout_moe_fp8_mod4, nullptr, + r4d_shape_moe_gemm_q_mod4, nullptr }, + +{ "moe_gemm_w4a8_mod4", "moe_gemm_q_mod4", "moe", + "moe_gemm_w4a8 over four classes of experts by number mod 4: the same kernel, each run reading " + "its class's table", + "as moe_gemm_w4a8, every class", + "as moe_gemm_w4a8", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeGemmW4), NOTUNE, + nullptr, nullptr, r4d_rad_moe_gemm_w4a8_mod4, r4d_rad_moe_gemm_w4a8_scratch, + r4d_rad_layout_moe_w4_mod4, r4d_rad_relayout_moe_w4_mod4, nullptr, + r4d_rad_unrelayout_moe_w4_mod4, nullptr, r4d_rad_moe_gemm_w4a8_mod4_describe }, + { "moe_gemm_bf16", "moe_gemm", "moe", "the grouped GEMM with unquantised experts: one run of expert-sorted rows a block, bf16 WMMA over " "an LDS-staged 64-deep K pass with the next one prefetched in registers", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 8c63b82e..45d46600 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -6049,6 +6049,7 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int } const int f_lo = pl.pin_moe ? 1 : 0, f_hi = pl.pin_moe ? 3 : 0; + std::vector two_cls[4]; /* each form's bytes, for the four-class pass below */ for (int form = f_lo; form <= f_hi; ++form) { const std::string label = what + " " + kForm[form]; if (pl.pin_moe) pl.pin_moe(form); @@ -6091,6 +6092,69 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int } ok(label.c_str(), bad == 0, std::to_string(bad) + " of " + std::to_string(Tr * N) + " elements off, worst " + std::to_string(worst) + first); + two_cls[form] = got; + } + + /* AND THE SAME EXPERTS AS FOUR CLASSES, by number mod 4 (`moe_gemm_q_mod4`). Each parity table + * read at twice its stride is two of them -- from its first entry, the experts 0, 4, 8, ... of + * its parity's numbers mod 4, and from its second the others -- so classes 0 and 2 are the even + * table's halves and 1 and 3 the odd one's, at the even and the odd geometry. The same experts + * at the same geometry, read in the same order: every form must give the two-class op's bytes, + * byte for byte. What this checks is the class and entry each run resolves to. */ + const RadKernelInfo* r4 = find(pl, "moe_gemm_w4a8_mod4"); + const std::string what4 = what + ", four classes"; + if (!r4) { + ok(what4.c_str(), false, "row moe_gemm_w4a8_mod4 absent"); + return; + } + auto halves = [](const RadTensor& t, int bits, RadTensor* lo, RadTensor* hi) { + const int64_t n = t.shape[0]; + *lo = t; + *hi = t; + lo->shape[0] = (n + 1) / 2; + hi->shape[0] = n / 2; + lo->stride[0] = t.stride[0] * 2; + hi->stride[0] = t.stride[0] * 2; + hi->data = (char*)t.data + t.stride[0] * bits / 8; + }; + const int wbits = w5 ? 5 : 4, sbits = g64 ? 8 : 16; + RadTensor c4w[4], c4s[4]; + halves(ts[2], wbits, &c4w[0], &c4w[2]); + halves(ts[3], sbits, &c4s[0], &c4s[2]); + halves(ts[6], wbits, &c4w[1], &c4w[3]); + halves(ts[7], sbits, &c4s[1], &c4s[3]); + std::vector ts4 = { ts[0], ts[1], c4w[0], c4s[0], ts[4], ts[5], c4w[1], c4s[1], + c4w[2], c4s[2], c4w[3], c4s[3], ts[8] }; + std::vector ps4 = { + PI("M", M), PI("N", sh.N0), PI("K", sh.K0), PI("N_1", sh.N1), PI("K_1", sh.K1), + PI("N_2", sh.N0), PI("K_2", sh.K0), PI("N_3", sh.N1), PI("K_3", sh.K1), + PI("parts", sh.parts), PI("n_expert", ne), PI("top_k", top_k), PI("group", group), + PS("a_order", "token"), PS("dtype", dt), + }; + RadArgs a4; + std::memset(&a4, 0, sizeof(a4)); + a4.t = ts4.data(); a4.n_t = (int)ts4.size(); + a4.p = ps4.data(); a4.n_p = (int)ps4.size(); + for (int form = f_lo; form <= f_hi; ++form) { + const std::string label = what4 + " " + kForm[form]; + if (two_cls[form].empty()) continue; /* the two-class launch failed, and said so */ + if (pl.pin_moe) pl.pin_moe(form); + { + std::vector junk((size_t)(Tr * N), 0x7f7fu); + st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); + } + a4.scratch = form == 3 ? nullptr : d_map; + a4.scratch_bytes = form == 3 ? 0 : map_bytes; + const int rc = r4->launch(&a4, nullptr); + st_stream_sync(nullptr); + if (pl.pin_moe) pl.pin_moe(0); + if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } + std::vector got((size_t)(Tr * N)); + st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); + int64_t diff = 0; + for (size_t i = 0; i < got.size(); ++i) diff += got[i] != two_cls[form][i]; + ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + + " elements differ from the two-class op's"); } } diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 122b1515..4dcf2994 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1308,6 +1308,49 @@ extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* The four-class form: class q holds the experts e with e % 4 == q at [N_q, K_q], defaulting to + * class 0's, ceil((n - q) / 4) of them; `y` follows the last class. */ +extern "C" int r4d_shape_moe_gemm_q_mod4(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + int64_t Nc[4], Kc[4]; + Nc[0] = pi(p, n_p, "N"); + Kc[0] = pi(p, n_p, "K"); + Nc[1] = pi(p, n_p, "N_1", Nc[0]); Kc[1] = pi(p, n_p, "K_1", Kc[0]); + Nc[2] = pi(p, n_p, "N_2", Nc[0]); Kc[2] = pi(p, n_p, "K_2", Kc[0]); + Nc[3] = pi(p, n_p, "N_3", Nc[0]); Kc[3] = pi(p, n_p, "K_3", Kc[0]); + const int64_t ne = pi(p, n_p, "n_expert"); + const int64_t k = pi(p, n_p, "top_k"); + int64_t g = pi(p, n_p, "group"); + if (ne <= 0 || k <= 0) return RAD_E_UNSUPPORTED; + if (g <= 0) g = 128; + int64_t N = 0, K = 0; + for (int q = 0; q < 4; ++q) { + if (Nc[q] <= 0 || Kc[q] <= 0) return RAD_E_UNSUPPORTED; + if (Nc[q] > N) N = Nc[q]; + if (Kc[q] > K) K = Kc[q]; + } + int64_t nq[4]; + for (int q = 0; q < 4; ++q) nq[q] = (ne + 3 - q) / 4; + const uint32_t D = dt_act(p, n_p, "dtype"); + const char* ord = rad_param_gets(p, n_p, "a_order", nullptr); + const int64_t AR = (ord && !std::strcmp(ord, "sorted")) ? M * k : M; + auto wq = [&](int q) { return opd((uint32_t)RAD_F8E4M3, nq[q], Nc[q], Kc[q]); }; + auto sq = [&](int q) { + return opd((uint32_t)RAD_BF16, nq[q], (Nc[q] + g - 1) / g, (Kc[q] + g - 1) / g); + }; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_F8E4M3, AR, K), /* a -- see `a_order` */ + opd((uint32_t)RAD_F32, AR, (K + g - 1) / g), /* a_scale */ + wq(0), sq(0), /* w, w_scale -- class 0 */ + opd_idx(M * k, 0, M * k, -1), /* sorted_tok */ + opd_idx(ne + 1, 0, M * k + 1, -1), /* expert_offset */ + wq(1), sq(1), wq(2), sq(2), wq(3), sq(3), /* classes 1, 2, 3 */ + opd(D, M * k, N), /* y -- in SORTED order */ + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); const int64_t k = pi(p, n_p, "top_k"); diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index 0b677820..c130799f 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -173,8 +173,8 @@ int ref_moe_scatter(const RadArgs* a, RadStream) { * here. Only the WEIGHT scale grid is block-shaped -- one scale per 128x128 tile of an expert -- * while the activation's is per row per group of K, which is `rblk = 1`, which is what * make_scales derives on its own from the two extents. */ -static int moe_gemm_impl(const RadArgs* a, bool quant) { - const int n_opd = quant ? 9 : 5; +static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { + const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5; if (!have(a, n_opd)) return RAD_E_INVAL; const RadTensor* A = &a->t[0]; const RadTensor* as_ = quant ? t_in(a, 1) : nullptr; @@ -182,12 +182,18 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { const RadTensor* ws_ = quant ? t_in(a, 3) : nullptr; const RadTensor* sorted = &a->t[quant ? 4 : 2]; const RadTensor* off = &a->t[quant ? 5 : 3]; - const RadTensor* Y = &a->t[quant ? 8 : 4]; - /* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- and the - * plain arm's are one, which is the same walk with every expert in the first class. */ + const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4]; + /* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- or, for + * `moe_gemm_q_mod4`, four by the expert's number mod 4; the plain arm's are one, which is the + * same walk with every expert in the first class. */ const RadTensor* W1 = quant ? &a->t[6] : W; const RadTensor* ws1_ = quant ? t_in(a, 7) : nullptr; const bool two = quant; + const int nc = quant ? ncls : 1; + const RadTensor* Wq[4] = { W, W1, quant && nc == 4 ? &a->t[8] : W, + quant && nc == 4 ? &a->t[10] : W }; + const RadTensor* wsq[4] = { ws_, ws1_, quant && nc == 4 ? t_in(a, 9) : nullptr, + quant && nc == 4 ? t_in(a, 11) : nullptr }; /* "sorted" means `a` already has one row per (token, slot) in the scatter's order, which is * what the DOWN projection of a routed block reads -- its input is the first projection's @@ -199,19 +205,29 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { const int64_t N0 = p_int(a, "N", W->rank >= 3 ? W->shape[1] : 0); const int64_t K0 = p_int(a, "K", W->rank >= 3 ? W->shape[2] : 0); - const int64_t N1 = two ? p_int(a, "N_odd", N0) : N0; - const int64_t K1 = two ? p_int(a, "K_odd", K0) : K0; + /* Each class's geometry, defaulting to class 0's: N_odd/K_odd at two classes, N_q/K_q at + * four. */ + static const char* const kN4[4] = { "N", "N_1", "N_2", "N_3" }; + static const char* const kK4[4] = { "K", "K_1", "K_2", "K_3" }; + int64_t Nq[4] = { N0, N0, N0, N0 }, Kq[4] = { K0, K0, K0, K0 }; + for (int q = 1; q < nc; ++q) { + Nq[q] = p_int(a, nc == 4 ? kN4[q] : "N_odd", N0); + Kq[q] = p_int(a, nc == 4 ? kK4[q] : "K_odd", K0); + } const int64_t parts = two ? p_int(a, "parts", 1) : 1; const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0); const int64_t top_k = p_int(a, "top_k", 1); - if (N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || parts <= 0 || n_expert <= 0 || top_k <= 0) - return RAD_E_SHAPE; - if (N0 % parts || N1 % parts) return RAD_E_SHAPE; - /* The output is the wider class's width, the activation the longer class's K. */ - const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1; - const int64_t ne0 = two ? (n_expert + 1) / 2 : n_expert, ne1 = two ? n_expert / 2 : 0; - if (W->rank < 3 || W->shape[0] < ne0) return RAD_E_SHAPE; - if (two && (W1->rank < 3 || W1->shape[0] < ne1)) return RAD_E_SHAPE; + if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE; + /* The output is the widest class's width, the activation the longest class's K. Class q + * holds ceil((n - q) / nc) experts. */ + int64_t N = 0, K = 0; + for (int q = 0; q < nc; ++q) { + if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE; + if (Nq[q] > N) N = Nq[q]; + if (Kq[q] > K) K = Kq[q]; + const int64_t neq = (n_expert + nc - 1 - q) / nc; + if (neq > 0 && (Wq[q]->rank < 3 || Wq[q]->shape[0] < neq)) return RAD_E_SHAPE; + } const int64_t T = numel(Y) / N; if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE; @@ -235,17 +251,17 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { /* Per-expert readings, built once outside the row loop: a table lookup and a Scales are cheap, * and doing them per row would be T of them against n_expert. A null `data` means the operand * could not be read as a table at all, which is refused before the loop because an OpenMP body - * cannot return. Expert e is entry e / 2 of class e % 2 when there are two classes. */ + * cannot return. Expert e is entry e / nc of class e % nc. */ std::vector we((size_t)n_expert), wse((size_t)n_expert); std::vector mw((size_t)n_expert); std::vector SW((size_t)n_expert); std::vector en((size_t)n_expert), ek((size_t)n_expert); for (int64_t e = 0; e < n_expert; ++e) { - const bool odd = two && (e & 1); - const RadTensor* tw = odd ? W1 : W; - const RadTensor* ts = odd ? ws1_ : ws_; - const int64_t ix = two ? e / 2 : e; - const int64_t n = odd ? N1 : N0, k = odd ? K1 : K0; + const int q = (int)(e % nc); + const RadTensor* tw = Wq[q]; + const RadTensor* ts = wsq[q]; + const int64_t ix = e / nc; + const int64_t n = Nq[q], k = Kq[q]; en[(size_t)e] = n; ek[(size_t)e] = k; we[(size_t)e] = expert_entry(tw, ix); @@ -301,6 +317,7 @@ static int moe_gemm_impl(const RadArgs* a, bool quant) { 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_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true, 4); } /* ------------------------------------------------------------------ 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 23eb896d..16e541e0 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -120,6 +120,7 @@ int ref_router_topk (const RadArgs*, RadStream); int ref_moe_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_scale_rows (const RadArgs*, RadStream); int ref_moe_gather (const RadArgs*, RadStream); int ref_row_topk (const RadArgs*, RadStream); @@ -231,6 +232,7 @@ REF_SHAPE_FN(ref_router_topk); REF_SHAPE_FN(ref_moe_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_scale_rows); REF_SHAPE_FN(ref_moe_gather); REF_SHAPE_FN(ref_row_topk); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 96ec77d0..77ee84e9 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -344,6 +344,19 @@ 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 the expert's 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 take turns with the extra block of a five-block expert. libr4d's schema states the same. */ +static const RadParamSpec pMoeGemmQMod4[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), + P_INT("top_k"), P_INT("group"), P_STR("a_order"), + P_STR("dtype"), P_INTO("N_1"), P_INTO("K_1"), + P_INTO("N_2"), P_INTO("K_2"), P_INTO("N_3"), + P_INTO("K_3"), P_INTO("parts") }; +static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), + WTAB("w_scale"), OPD("sorted_tok"), + OPD("expert_offset"), WTAB("w_1"), + WTAB("w_1_scale"), WTAB("w_2"), WTAB("w_2_scale"), + WTAB("w_3"), WTAB("w_3_scale"), OUT("y") }; /* `shared` and `shared_gate` PRESENT = the shared arm folded in, `y = bf16(shared * act(gate)) + * bf16(gathered)`, which is scale_rows' fused gate-and-add taken one op further back. `act` is @@ -770,6 +783,11 @@ static const RadOpSchema kSchemas[] = { "two tables by parity: `w` the even ones at [N, K], `w_odd` the odd ones at [N_odd, K_odd], " "expert e at entry e/2. The output is max(N, N_odd) wide in `parts` stacked parts, and a " "narrower class fills each part's leading columns and zeros the rest." }, +{ "moe_gemm_q_mod4", ARR(pMoeGemmQMod4), ARR(oMoeGemmQMod4), + "moe_gemm_q over FOUR weight-table classes by the expert's number mod 4: `w` class 0 at [N, K], " + "`w_q` class q at [N_q, K_q], expert e at entry e/4 of class e%4. The output is as wide as the " + "widest class in `parts` stacked parts, and a narrower class fills each part's leading columns " + "and zeros the rest." }, { "moe_gather", ARR(pMoeGather), ARR(oMoeGather), "Scatters the sorted expert output back and weights it. The sum over a token's slots runs in " "ASCENDING SLOT order, which is what makes it reproducible." }, @@ -1048,6 +1066,9 @@ SIMPLE("ref_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted r ref_moe_gemm), SIMPLE("ref_moe_gemm_q", "moe_gemm_q", "moe", "grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT, ref_moe_gemm_q), +SIMPLE("ref_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe", + "grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4", + DT_FLOAT, ref_moe_gemm_q_mod4), SIMPLE("ref_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT, ref_moe_gather), SIMPLE("ref_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT, ref_rope_table), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 03de5000..58423ef0 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1145,6 +1145,44 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("moe_gemm_q", operand, out); } +/* The four-class form: class q at [N_q, K_q], defaulting to class 0's, holds the experts e with + * e % 4 == q -- ceil((n - q) / 4) of them -- and `y` follows the last class. */ +int ref_moe_gemm_q_mod4_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 Nq[4] = { N0, gi(p, n_p, "N_1", N0), gi(p, n_p, "N_2", N0), gi(p, n_p, "N_3", N0) }; + const int64_t Kq[4] = { K0, gi(p, n_p, "K_1", K0), gi(p, n_p, "K_2", K0), gi(p, n_p, "K_3", K0) }; + const int64_t ne = gi(p, n_p, "n_expert", 0); + const int64_t k = gi(p, n_p, "top_k", 0); + int64_t g = gi(p, n_p, "group", 0); + if (M <= 0 || ne <= 0 || k <= 0) return RAD_E_UNSUPPORTED; + int64_t N = 0, K = 0; + for (int q = 0; q < 4; ++q) { + if (Nq[q] <= 0 || Kq[q] <= 0) return RAD_E_UNSUPPORTED; + if (Nq[q] > N) N = Nq[q]; + if (Kq[q] > K) K = Kq[q]; + } + if (g <= 0) g = K; + const uint32_t D = act_dt(p, n_p); + Opd o; + const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; + auto cls = [&](int q) { + const int64_t nq = (ne + 3 - q) / 4; + o.t((uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] }); + o.t(D, { nq, (Nq[q] + g - 1) / g, (Kq[q] + g - 1) / g }); + }; + o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */ + o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */ + cls(0); /* w, w_scale -- class 0 */ + o.t_idx({ M * k }, M * k, -1, 0); /* sorted_tok */ + o.t_idx({ ne + 1 }, M * k + 1, -1, 0); /* expert_offset */ + cls(1); + cls(2); + cls(3); + o.t(D, { M * k, N }); /* y -- in SORTED order */ + return o.finish("moe_gemm_q_mod4", 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 ba0d8d83..e9dd89f7 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -269,7 +269,8 @@ TEST(op_vocabulary) { "dequant", "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", - "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gather", "row_topk", + "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", + "row_topk", "row_topk_merge", "logit_rerank", "gdn_conv_prep", "gdn_conv_update", "gdn_kkt_solve", "gdn_chunk_scan", "gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm", @@ -1925,6 +1926,59 @@ TEST(op_router_topk) { CHECK_NEAR(w2.at(1), 0.26894142f, 1e-6); } +/* THE FOUR-CLASS GROUPED GEMM: expert e is entry e / 4 of class e % 4, each class at its own + * width, and a narrower class's columns past its width are zero. Ten experts, so classes 0 and 1 + * hold three and 2 and 3 hold two -- the shape a layer with 510 quantised experts has -- and class + * 1 is the wide one, as it is on rank 1. Every value is a small integer, so the sums are exact. */ +TEST(op_moe_gemm_q_mod4) { + const int64_t K = 3, top_k = 2, M = 3, ne = 10; + const int64_t Nq[4] = { 2, 4, 2, 2 }; + auto wv = [](int64_t e, int64_t n, int64_t k) { return (float)(e * 100 + n * 10 + k); }; + std::vector w, ws; + w.reserve(4); + ws.reserve(4); + for (int q = 0; q < 4; ++q) { + const int64_t cnt = (ne + 3 - q) / 4; + w.emplace_back(RAD_F32, std::vector{ cnt, Nq[q], K }); + std::vector v; + for (int64_t j = 0; j < cnt; ++j) + for (int64_t n = 0; n < Nq[q]; ++n) + for (int64_t k = 0; k < K; ++k) v.push_back(wv(q + 4 * j, n, k)); + w.back().f(v); + /* One unit scale an expert: the arithmetic under test is which weight a row reads. */ + ws.emplace_back(RAD_F32, std::vector{ cnt, 1, 1 }); + ws.back().f(std::vector((size_t)cnt, 1.0f)); + } + T act(RAD_F32, {M, K}); + act.f({ 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + T as(RAD_F32, {M, 1}); + as.f({ 1, 1, 1 }); + /* Rows by expert: 1 owns rows 0-1, 2 row 2, 6 row 3, 9 rows 4-5, the rest none. */ + const std::vector eoff = { 0, 0, 2, 3, 3, 3, 3, 4, 4, 4, 6 }; + const std::vector flat = { 0, 2, 1, 4, 3, 5 }; + T sorted(RAD_I32, {6}); sorted.n(flat); + T off(RAD_I32, {ne + 1}); off.n(eoff); + T y(RAD_F32, {6, 4}); + A a; + a.t(act).t(as).t(w[0]).t(ws[0]).t(sorted).t(off).t(w[1]).t(ws[1]).t(w[2]).t(ws[2]).t(w[3]) + .t(ws[3]).t(y) + .i("M", M).i("N", Nq[0]).i("K", K).i("N_1", Nq[1]).i("K_1", K).i("N_2", Nq[2]).i("K_2", K) + .i("N_3", Nq[3]).i("K_3", K).i("n_expert", ne).i("top_k", top_k).s("a_order", "token") + .s("dtype", "f32"); + CHECK_OK(run("moe_gemm_q_mod4", a)); + for (int64_t i = 0; i < 6; ++i) { + int64_t e = 0; + while (eoff[(size_t)(e + 1)] <= i) ++e; + const int64_t tok = flat[(size_t)i] / top_k; + for (int64_t n = 0; n < 4; ++n) { + float want = 0.0f; + if (n < Nq[e % 4]) + for (int64_t k = 0; k < K; ++k) want += act.at(tok * K + k) * wv(e, n, k); + CHECK_EQ(y.at(i * 4 + n), want); + } + } +} + TEST(op_moe_chain) { /* Two tokens, two experts, top_k 2 -- every token visits every expert, so the whole chain is * checkable without any routing subtlety. */