From 63d35ff791e218672110d93cfb93a99f32f4da33 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Mon, 5 Oct 2026 11:55:13 +0200 Subject: [PATCH] four-rank Flash-Next: the routed experts in four classes The parity split gave ranks 0..3 30/30/20/20 % of the routed work. The extra block of each five-block expert now goes round all four ranks by expert id mod 4: rank r takes two blocks of class r and one of each other class, a quarter each. The plain experts' extra tiles move to ranks 0 and 1 so they do not stack on the shared expert's. One and two ranks declare as before. --- arch/common/rad_block_moe_fp8.h | 162 ++++++++++++++++++++------ arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 49 ++++++-- docs/ARCHITECTURES.md | 17 +-- tests/arch_test.cpp | 178 ++++++++++++++++++++++++----- 4 files changed, 324 insertions(+), 82 deletions(-) diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index fce97f51..48772c1d 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -45,7 +45,9 @@ * Config::ff_lo). So the arrays are declared in separate loops -- gate_up codes, gate_up scales, * down codes, down scales, each for the even experts and then the odd ones -- and NOT as a group * per expert. Interleaving them would give runs of stride two or four, which the operand cannot - * express; the failure would be a table whose second entry is a scale plane. + * express; the failure would be a table whose second entry is a scale plane. Where four ranks split + * every expert the classes are four, by number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4), and the + * runs sixteen, declared the same way class by class. * * The codes run and the scale run of a projection are two VIEWS of one stored weight -- its codes * plane and its scale plane (RadWeightDecl::source) -- so an expert holds two logical weights, @@ -163,6 +165,19 @@ struct MoeFP8 { * and the sum of the partials is the expert's output. Rounding moves (two partial sums * where there was one), so this is checked by agreement rather than byte for byte. */ int64_t ff_lo[2] = { 0, 0 }, ff_hi[2] = { 0, 0 }; + /* OR BY THE EXPERT'S NUMBER MOD 4, where four ranks split it: expert e's columns + * [ff_lo4[e % 4], ff_hi4[e % 4]), served by `moe_gemm_q_mod4`, and taking precedence over + * the parity slices. hi 0 offers none. + * + * Parity gives the extra block of a five-block expert two places to go, so at four ranks + * two of them carry three blocks of every even/odd pair and two carry two -- and the + * block's all-reduce has the narrow ranks wait for the wide ones. Four classes give it + * four: each rank takes two blocks of one class and one of each other, five of every four + * experts. Any count of quantised experts serves: a layer that keeps two plain bf16 has + * 510, and its first two classes hold one expert more than the last two (the declaration + * gives a table op's first tables the remainder). `n_ff_exp` is the widest slice. "e" is + * the expert's place in the sort, as for the parity classes. */ + int64_t ff_lo4[4] = { 0, 0, 0, 0 }, ff_hi4[4] = { 0, 0, 0, 0 }; int64_t n_ff_shared = 0; /* the shared expert's, per rank; 0 = no shared expert */ /* THE SHARED ARM'S SLICE ON THIS RANK, when its width does not halve into whole fp8 scale * blocks: [shared_lo, shared_hi) of its columns in the model's numbering, with @@ -368,6 +383,9 @@ struct MoeFP8 { std::vector prot; const char* prot_list = nullptr; int64_t n_reg = 0; + /* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by + * number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */ + int ncls = 2; /* THIS LAYER'S gate_up AND down FORMATS (format_of's numbers), resolved by declare(): the * probed layer's for both, except that among the codebook forms at E4M3 scales -- w4nl64a8h, * w4nl32a8h, w5nl64a8h -- each projection of each layer takes its own experts'. */ @@ -653,8 +671,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, "places at most %lld last\n", l, prot.size(), (long long)kMaxProtected); return RAD_E_INVAL; } - /* The quantised GEMM takes its experts as two equal tables by parity. */ - if (n_reg % 2) { + /* The quantised GEMM takes its experts as two equal tables by parity -- at four classes + * (Config::ff_lo4) as four tables, the first n_reg % 4 one expert longer, which any count + * gives. */ + if (!(c.ff_hi[0] > 0 && c.ff_hi4[0] > 0) && n_reg % 2) { fprintf(stderr, "radiance: layer %d keeps %zu experts plain bf16 on this rank, which " "leaves %lld quantised; they come in pairs on a rank so the rest split " "into two equal tables by parity\n", l, prot.size(), (long long)n_reg); @@ -784,21 +804,43 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, if (std::find(prot.begin(), prot.end(), e) == prot.end()) reg.push_back(e); w_gu.resize((size_t)ne); w_gus.resize((size_t)ne); w_dn.resize((size_t)ne); w_dns.resize((size_t)ne); - /* Each parity's width on this rank: the Config's slice when the width is split unevenly, and - * `n_ff_exp` for both otherwise. The buffers between the two GEMMs are the wider one's. */ - const bool split = c.ff_hi[0] > 0; - int64_t wq[2] = { c.n_ff_exp, c.n_ff_exp }; - if (split) - for (int q = 0; q < 2; ++q) wq[q] = c.ff_hi[q] - c.ff_lo[q]; - if (split && (wq[0] <= 0 || wq[1] <= 0 || c.n_ff_exp != (wq[0] > wq[1] ? wq[0] : wq[1]))) { - fprintf(stderr, "radiance: the routed experts' slices [%lld, %lld) and [%lld, %lld) do not " - "describe a width of %lld\n", (long long)c.ff_lo[0], (long long)c.ff_hi[0], - (long long)c.ff_lo[1], (long long)c.ff_hi[1], (long long)c.n_ff_exp); + /* Each class's width on this rank: the Config's slice when the width is split unevenly, and + * `n_ff_exp` for every class otherwise. The buffers between the two GEMMs are the widest + * one's. FOUR CLASSES where the Config offers them (Config::ff_lo4), the parity classes + * otherwise. */ + const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0; + ncls = c.ff_hi4[0] > 0 ? 4 : 2; + if (ncls == 4 && n_reg < 4) { + fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four " + "classes need at least one each\n", l, (long long)n_reg); return RAD_E_INVAL; } - for (int q = 0; q < 2; ++q) + int64_t qlo[4] = { 0, 0, 0, 0 }, qhi[4] = { 0, 0, 0, 0 }; + int64_t wq[4] = { c.n_ff_exp, c.n_ff_exp, c.n_ff_exp, c.n_ff_exp }; + if (split) + for (int q = 0; q < ncls; ++q) { + qlo[q] = ncls == 4 ? c.ff_lo4[q] : c.ff_lo[q]; + qhi[q] = ncls == 4 ? c.ff_hi4[q] : c.ff_hi[q]; + wq[q] = qhi[q] - qlo[q]; + } + if (split) { + int64_t widest = 0; + bool bad = false; + for (int q = 0; q < ncls; ++q) { + bad = bad || wq[q] <= 0; + widest = wq[q] > widest ? wq[q] : widest; + } + if (bad || c.n_ff_exp != widest) { + fprintf(stderr, "radiance: the routed experts' %d class slices, the first [%lld, %lld) " + "and [%lld, %lld), do not describe a width of %lld\n", ncls, + (long long)qlo[0], (long long)qhi[0], (long long)qlo[1], (long long)qhi[1], + (long long)c.n_ff_exp); + return RAD_E_INVAL; + } + } + for (int q = 0; q < ncls; ++q) if (wq[q] % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK || - (split && c.ff_lo[q] % RAD_FP8_BLOCK)) { + (split && qlo[q] % RAD_FP8_BLOCK)) { fprintf(stderr, "radiance: an expert is %lldx%lld per rank, which is not a whole number " "of %dx%d scale blocks\n", (long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK); @@ -858,11 +900,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK; const char* escale = c.expert_g64 ? "scale,scale.1" : "scale"; - /* A slice of each expert: the gate and up rows [lo, hi) of this parity for the gate/up pair, + /* A slice of each expert: the gate and up rows [lo, hi) of this class for the gate/up pair, * columns [lo, hi) for down, and the scale planes the same slice in their own units. */ auto span = [&](rad_weight h, int q, int64_t unit) -> int { if (!split || !h) return RAD_OK; - return rad_weight_shard_span(b, h, c.ff_lo[q] / unit, c.ff_hi[q] / unit); + return rad_weight_shard_span(b, h, qlo[q] / unit, qhi[q] / unit); }; const bool rot = c.expert_rot != 0; if (c.expert_bf16) { @@ -916,9 +958,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, {w.eff.x, w.sorted, w.eoff}, {w.edn}); if (!op_gu || !op_dn) return RAD_E_INVAL; } else { - /* ---- the eight runs, declared as the views the header describes. */ - for (int q = 0; q < 2; ++q) - for (int64_t s = q; s < n_reg; s += 2) { + /* ---- the eight runs -- sixteen at four classes -- declared as the views the header + * describes, class by class. */ + for (int q = 0; q < ncls; ++q) + for (int64_t s = q; s < n_reg; s += ncls) { const int64_t e = reg[(size_t)s]; const int64_t parts[2] = { wq[q], wq[q] }; rad_weight& h = w_gu[(size_t)s]; @@ -930,8 +973,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, if (!h) return RAD_E_INVAL; RAD_ARCH_TRY(span(h, q, 1)); } - for (int q = 0; q < 2; ++q) - for (int64_t s = q; s < n_reg; s += 2) { + for (int q = 0; q < ncls; ++q) + for (int64_t s = q; s < n_reg; s += ncls) { const int64_t e = reg[(size_t)s]; const int64_t parts[2] = { wq[q] / sdiv, wq[q] / sdiv }; rad_weight& h = w_gus[(size_t)s]; @@ -947,8 +990,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, if (!h) return RAD_E_INVAL; RAD_ARCH_TRY(span(h, q, sdiv)); } - for (int q = 0; q < 2; ++q) - for (int64_t s = q; s < n_reg; s += 2) { + for (int q = 0; q < ncls; ++q) + for (int64_t s = q; s < n_reg; s += ncls) { const int64_t e = reg[(size_t)s]; rad_weight& h = w_dn[(size_t)s]; h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l, @@ -958,8 +1001,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, if (!h) return RAD_E_INVAL; RAD_ARCH_TRY(span(h, q, 1)); } - for (int q = 0; q < 2; ++q) - for (int64_t s = q; s < n_reg; s += 2) { + for (int q = 0; q < ncls; ++q) + for (int64_t s = q; s < n_reg; s += ncls) { const int64_t e = reg[(size_t)s]; rad_weight& h = w_dns[(size_t)s]; h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.scale", l, @@ -1004,13 +1047,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, {w.h.x}, {w.hr.q, w.hr.s}); } /* A table op's weights, in its table operands' order: the even experts' codes and scales, then - * the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`). */ + * the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`) -- or at four classes class 0's, + * then 1's, 2's and 3's. */ auto tables = [&](const std::vector& wc, const std::vector& ws) { std::vector tab; tab.reserve((size_t)n_reg * 2); - for (int q = 0; q < 2; ++q) { - for (int64_t s = q; s < n_reg; s += 2) tab.push_back(wc[(size_t)s]); - for (int64_t s = q; s < n_reg; s += 2) tab.push_back(ws[(size_t)s]); + for (int q = 0; q < ncls; ++q) { + for (int64_t s = q; s < n_reg; s += ncls) tab.push_back(wc[(size_t)s]); + for (int64_t s = q; s < n_reg; s += ncls) tab.push_back(ws[(size_t)s]); } return tab; }; @@ -1020,7 +1064,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * width, which its down projection does not read. */ { const std::vector tab = tables(w_gu, w_gus); - rad_op h = rad_decl_op(b, "moe_gemm_q", + rad_op h = ncls == 4 + ? rad_decl_op(b, "moe_gemm_q_mod4", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]), + RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg), + RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]), + RAD_INT("N_1", 2 * wq[1]), RAD_INT("K_1", g.n_embd), + RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd), + RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd), + RAD_INT("parts", 2)), + tab.data(), (int)tab.size()) + : rad_decl_op(b, "moe_gemm_q", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]), RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg), RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), @@ -1038,7 +1093,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, false, rot)); { const std::vector tab = tables(w_dn, w_dns); - rad_op h = rad_decl_op(b, "moe_gemm_q", + rad_op h = ncls == 4 + ? rad_decl_op(b, "moe_gemm_q_mod4", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), + RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg), + RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]), + RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]), + RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]), + RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]), + RAD_INT("parts", 1)), + tab.data(), (int)tab.size()) + : rad_decl_op(b, "moe_gemm_q", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg), RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK), @@ -1095,8 +1161,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, return RAD_E_INVAL; } else { const int64_t nt = full / 64, base = nt / g.world, extra = nt % g.world; - /* Cut by the rank's place (Config::extra_place), not necessarily its index. */ - const int64_t pr = c.extra_place >= 0 ? c.extra_place : (int64_t)g.rank; + /* Cut by the rank's place (Config::extra_place), not necessarily its index -- + * except in a layer served at four classes. The place exists to keep these tiles + * off the ranks holding the routed extra blocks, and at four classes every rank + * holds one; the shared expert's extra block is cut by the same place, so the + * rank's own index keeps the two remainders apart instead. */ + const int64_t pr = (c.extra_place >= 0 && ncls != 4) ? c.extra_place + : (int64_t)g.rank; if (pr >= g.world) return RAD_E_INVAL; const int64_t t0 = pr * base + std::min(pr, extra); const int64_t t1 = t0 + base + (pr < extra ? 1 : 0); @@ -1400,11 +1471,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const /* The two grouped GEMMs, and the weight tables: the FIRST handle of each run and its length. * The runs are contiguous by construction -- see declare -- so `w_gu[q] + i` is expert - * 2 * i + q, and each parity is its own pair of table operands. */ + * 2 * i + q, and each parity is its own pair of table operands; at four classes expert + * 4 * i + q, class q holding ceil((n_reg - q) / 4). */ + const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 }; if (c.expert_bf16) RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.egu, rows * k)); + else if (ncls == 4) + RAD_ISSUE_N(c_, op_gu, rows, + brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd), + brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), + RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]), + brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), + RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]), + RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]), + RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]), + brows(w.egu, rows * k)); else RAD_ISSUE_N(c_, op_gu, rows, brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd), @@ -1419,6 +1502,15 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const if (c.expert_bf16) RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k)); + else if (ncls == 4) + RAD_ISSUE_N(c_, op_dn, rows, + brows(w.eff.q, rows * k), brows(w.eff.s, rows * k), + RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]), + brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), + RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]), + RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]), + RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]), + brows(w.edn, rows * k)); else RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.q, rows * k), brows(w.eff.s, rows * k), diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index bd0477da..4d08c552 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -295,10 +295,12 @@ static int64_t ngram_table_rows(int64_t base, int64_t heads, int64_t divisor) { /* A RANK'S PLACE WHEN A WIDTH THAT DOES NOT DIVIDE IS CUT OVER THE RANKS, the first places taking * one unit more: the ranks in order of how many 128-column blocks of an even/odd pair of routed * experts declare()'s parity split gives each, fewest first, by rank among equals. At four ranks - * and five blocks that is ranks 2, 3, 0, 1 -- ranks 0 and 1 hold the routed extra blocks, and - * cutting the shared expert and the plain experts from rank 0 as well stacks their extra columns on - * the ranks every block's all-reduce already waits for. Where the routed width divides it is the - * rank; declare() asks only above two ranks. */ + * and five blocks that is ranks 2, 3, 0, 1 -- under parity ranks 0 and 1 hold the routed extra + * blocks, and cutting the shared expert from rank 0 as well would stack its extra columns on the + * ranks every block's all-reduce already waits for. The four-class split that four ranks serve + * gives every rank the same routed width, and the shared expert's extra block stays rank 2's: the + * plain experts' extra tiles are cut by rank there (MoeFP8::declare), so the two do not stack. + * Where the routed width divides it is the rank; declare() asks only above two ranks. */ static int64_t narrow_place(int64_t n_ff_all, int world, int rank) { const int64_t nb = n_ff_all / RAD_FP8_BLOCK; if (n_ff_all % RAD_FP8_BLOCK || nb < world || nb % world == 0) return rank; @@ -520,13 +522,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * replicated, every rank computes its slice of every routed expert, and the block's * all-reduce sums the partials. * - * AT FOUR RANKS THE SHARES ARE NOT EQUAL. Parity gives the extra block only two places to - * go, so ranks 0 and 1 compute three blocks of every even/odd pair of experts and ranks 2 - * and 3 compute two, and the all-reduce has ranks 2 and 3 wait for the other two. Equal - * shares need the extra block rotated over four places -- the expert's number mod 4, four - * slice tables where moe_gemm_q takes two. What can move without them does: the shared - * expert's extra block and the plain experts' extra tiles go to ranks 2 and 3 - * (narrow_place), so ranks 0 and 1 take one shared block and two plain tiles. + * AT FOUR RANKS PARITY IS NOT ENOUGH. It gives the extra block only two places to go, so + * ranks 0 and 1 would compute three blocks of every even/odd pair of experts and ranks 2 + * and 3 two, and the all-reduce would have ranks 2 and 3 wait for the other two. So at four + * the extra block is rotated over four places, by the expert's number mod 4: four slice + * tables (`moe_gemm_q_mod4`), and every rank computes five blocks of every four experts. + * A layer keeping two experts plain bf16 has 510 quantised ones, and its first two classes + * are one expert longer. What does not divide elsewhere stays apart: the shared expert's + * extra block is rank 2's (narrow_place) and the plain experts' extra tiles ranks 0 and + * 1's (MoeFP8::declare). * * WHY NOT EXPERT PARALLELISM, which splits the EXPERTS: rank r owns [r*E/W, (r+1)*E/W) * whole. The bytes a rank reads are the same on average either way, but which rank a @@ -596,6 +600,29 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0], (long long)mc.ff_lo[1], (long long)mc.ff_hi[1], (long long)g.n_ff_all, (long long)nb, RAD_FP8_BLOCK, (long long)g.world); + /* AND AT FOUR RANKS FOUR CLASSES, by the expert's number mod 4 (MoeFP8::Config:: + * ff_lo4), which every layer then takes instead: the same cut with the rank's place + * shifted by the class, so the extra block goes round all four ranks instead of + * two. Every block of every expert still has one owner, and each slice is one a + * rank already takes of some parity. */ + if (g.world == 4) { + for (int q = 0; q < 4; ++q) { + const int64_t p = (g.rank - q + 4) % 4; + const int64_t b0 = p * base + std::min(p, extra); + const int64_t b1 = b0 + base + (p < extra ? 1 : 0); + mc.ff_lo4[q] = b0 * RAD_FP8_BLOCK; + mc.ff_hi4[q] = b1 * RAD_FP8_BLOCK; + mc.n_ff_exp = std::max(mc.n_ff_exp, mc.ff_hi4[q] - mc.ff_lo4[q]); + } + rad_note(b, "routed experts at four classes: rank %d computes columns [%lld, " + "%lld) [%lld, %lld) [%lld, %lld) [%lld, %lld) of the experts of " + "number 0, 1, 2 and 3 mod 4 -- %lld blocks of every four experts, " + "as every rank does.", + g.rank, (long long)mc.ff_lo4[0], (long long)mc.ff_hi4[0], + (long long)mc.ff_lo4[1], (long long)mc.ff_hi4[1], + (long long)mc.ff_lo4[2], (long long)mc.ff_hi4[2], + (long long)mc.ff_lo4[3], (long long)mc.ff_hi4[3], (long long)nb); + } } else { fprintf(stderr, "radiance: qwen4exp: an expert is %lld blocks of %d, which %d ranks " "cannot each take a whole block of in both parities. Lower the rank " diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 63bd9bcc..03dd58c5 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -307,13 +307,16 @@ above the block count is refused at declare, by name: a rank with an empty slice and still joins the all-reduce. The shared expert's 640 columns split as evenly as whole blocks allow: five blocks over four ranks is rank 2 `[0, 256)` and one block each on ranks 3, 0 and 1. -**At four ranks the shares are not equal.** Parity gives the extra block only two places to go, so -ranks 0 and 1 compute three blocks of every even/odd pair of routed experts and ranks 2 and 3 -compute two. What does not divide elsewhere is cut from the other end: the shared expert's extra -block is rank 2's, and the protected bf16 experts' ten 64-wide tiles go 2, 2, 3, 3. That takes one -shared block off rank 0, the slowest rank, and leaves ranks 0 and 1 still a routed block per -even/odd pair ahead of ranks 2 and 3 at every block's all-reduce. Equal shares need the extra block -rotated by the expert's number mod 4: four slice tables where `moe_gemm_q` takes two. +**At four ranks the classes are four.** Parity gives the extra block only two places to go, so +ranks 0 and 1 would compute three blocks of every even/odd pair of routed experts and ranks 2 and 3 +two, and every block's all-reduce would have 2 and 3 wait. So at four ranks the cut above is made +per class of the expert's number mod 4, the rank's place shifted by the class: rank `r` takes +`[0, 2)` blocks of class `r` and one block of each other class, five blocks of every four experts +on every rank. That is `moe_gemm_q_mod4`, four slice tables where `moe_gemm_q` takes two +(`docs/OPS.md`), and every slice is one a rank already took of some parity. A layer that keeps two +experts plain bf16 has 510 quantised ones, and its first two classes are one expert longer. What +does not divide elsewhere stays apart: the shared expert's extra block is rank 2's and the +protected bf16 experts' ten 64-wide tiles go 3, 3, 2, 2. Expert parallelism — whole experts a rank — is what this replaced, and why it stays replaced: the recipe protects its bf16 experts in pairs precisely so each rank's quantised count stays even, and sharding experts by rank breaks that parity property the weight tables rest on. diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 39bd2002..6329f19b 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -1846,9 +1846,11 @@ TEST(a_sizing_declare_leaves_the_step_state_alone_and_shrinks_only_rows) { * rank names the container rows it wants -- so it is asserted here as a pair of agreeing spans * whose union is the whole projection. * - an expert of this model is 640 columns = five 128-column scale blocks, which four ranks - * cannot cut evenly, so the split is UNEVEN BY PARITY and it is the width that divides, not the + * cannot cut evenly, so the split is UNEVEN BY CLASS and it is the width that divides, not the * expert set: every rank routes every one of the 512 experts and computes [lo, hi) of each, the - * rank taking the odd block alternating with the expert's parity. Sharding the experts instead + * rank taking the odd block going round with the expert's number mod 4 -- five blocks of every + * four experts on every rank -- and with its parity in a layer whose quantised experts do not + * come in fours. Sharding the experts instead * was tried and is wrong here -- protection is per-rank, so a rank can end up owning one plain * bf16 expert, leaving an odd count of quantised ones, and the grouped GEMM takes its experts as * two EQUAL tables by parity. The recipe protects experts in pairs for exactly that reason. @@ -1939,49 +1941,62 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { CHECK_EQ(pint(ts, "n_expert"), ne_all); CHECK_EQ(pint(ts, "expert_base"), (int64_t)0); } - /* THE WIDTH EACH RANK TAKES OF EACH PARITY, as a span on every expert's down projection -- - * the fixture protects no expert, so an expert's class is its own parity. These six numbers - * per rank are the whole TP4 MoE contract: five blocks of 128, four ranks, and the rank - * taking the odd block alternating with the parity. They are LITERAL here on purpose -- - * recomputing them from the plugin's formula would only prove the test agrees with the - * code, not that either agrees with the model. */ + /* THE WIDTH EACH RANK TAKES OF EACH CLASS, as a span on every expert's down projection -- + * the fixture protects no expert, so an expert's class is its own number mod 4. These + * eight numbers per rank are the whole TP4 MoE contract: five blocks of 128, four ranks, + * and the rank taking the odd block going round with the class. They are LITERAL here on + * purpose -- recomputing them from the plugin's formula would only prove the test agrees + * with the code, not that either agrees with the model. */ const int64_t blk = 128; /* RAD_FP8_BLOCK, the scale block's width */ const int64_t nblk = meta.n_ff / blk; /* five, at the fixture's 640 */ - const int64_t cls_lo[4][2] = { { 0, 512 }, { 256, 0 }, { 384, 256 }, { 512, 384 } }; - const int64_t cls_hi[4][2] = { { 256, 640 }, { 384, 256 }, { 512, 384 }, { 640, 512 } }; + const int64_t cls_lo[4][4] = { { 0, 512, 384, 256 }, { 256, 0, 512, 384 }, + { 384, 256, 0, 512 }, { 512, 384, 256, 0 } }; + const int64_t cls_hi[4][4] = { { 256, 640, 512, 384 }, { 384, 256, 640, 512 }, + { 512, 384, 256, 640 }, { 640, 512, 384, 256 } }; REQUIRE_EQ(nblk, (int64_t)5); - int spanned[2] = { 0, 0 }; + int spanned[4] = { 0, 0, 0, 0 }; for (const RecWeight& w : b[r].weights) { if (w.name.rfind("blk.0.ffn_down_exps.", 0) != 0) continue; if (w.name.compare(w.name.size() - 7, 7, ".weight") != 0) continue; - const int q = atoi(w.name.c_str() + 20) % 2; /* the expert's parity */ + const int q = atoi(w.name.c_str() + 20) % 4; /* the expert's class */ CHECK(w.span_set); CHECK_EQ(w.span_lo, cls_lo[r][q]); CHECK_EQ(w.span_hi, cls_hi[r][q]); ++spanned[q]; } - CHECK_EQ(spanned[0], ne_all / 2); /* every expert of each class is declared */ - CHECK_EQ(spanned[1], ne_all / 2); - /* AND THE FOUR RANKS' SLICES OF ONE PARITY TILE ITS WIDTH EXACTLY: no block unserved (a + for (int q = 0; q < 4; ++q) + CHECK_EQ(spanned[q], ne_all / 4); /* every expert of each class is declared */ + /* AND THE FOUR RANKS' SLICES OF ONE CLASS TILE ITS WIDTH EXACTLY: no block unserved (a * rank silently dropping a fifth of every expert's output), none claimed twice (the * all-reduce then sums that block twice and the number is wrong by its own size). Read off * the declared spans, not off the formula that produced them. */ - for (int q = 0; q < 2; ++q) { + for (int q = 0; q < 4; ++q) { int64_t covered = 0; for (int r2 = 0; r2 < world; ++r2) for (int64_t i = 0; i < nblk; ++i) { const int64_t lo = cls_lo[r2][q], hi = cls_hi[r2][q]; if (lo <= i * blk && i * blk < hi) ++covered; } - CHECK_EQ(covered, nblk); /* per parity, exactly once each */ + CHECK_EQ(covered, nblk); /* per class, exactly once each */ } - /* The gate/up GEMM's two classes follow the same split, doubled because the operand stacks - * gate and up, and the op's buffers take the WIDER class. */ - const RecOp* gu = find_op(b[r], "moe_gemm_q"); + /* AND EVERY RANK TAKES THE SAME WIDTH: five blocks of every four experts -- the point of + * four classes. Two would leave ranks 0 and 1 three blocks of every pair and 2 and 3 two. */ + { + int64_t sum = 0; + for (int q = 0; q < 4; ++q) sum += cls_hi[r][q] - cls_lo[r][q]; + CHECK_EQ(sum, nblk * blk); + } + /* The gate/up GEMM's four classes follow the same split, doubled because the operand + * stacks gate and up, and the op's buffers take the WIDEST class. No parity op is left. */ + const RecOp* gu = find_op(b[r], "moe_gemm_q_mod4"); REQUIRE(gu != nullptr); CHECK_EQ(pint(gu, "N"), 2 * (cls_hi[r][0] - cls_lo[r][0])); - CHECK_EQ(pint(gu, "N_odd"), 2 * (cls_hi[r][1] - cls_lo[r][1])); + CHECK_EQ(pint(gu, "N_1"), 2 * (cls_hi[r][1] - cls_lo[r][1])); + CHECK_EQ(pint(gu, "N_2"), 2 * (cls_hi[r][2] - cls_lo[r][2])); + CHECK_EQ(pint(gu, "N_3"), 2 * (cls_hi[r][3] - cls_lo[r][3])); CHECK_EQ(pint(gu, "n_expert"), ne_all); + CHECK_EQ(gu->w.size(), (size_t)(2 * ne_all)); /* codes and scales, every expert once */ + CHECK_EQ(count_op(b[r], "moe_gemm_q"), 0); /* (4) THE UNFUSED CHAIN: a standalone collective per reduction, and none of the three * fused world-2 forms. */ @@ -2087,6 +2102,110 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { CHECK(qwen4exp_fp8::declare(&b3, &meta, &c3) != RAD_OK); } + /* ---- A LAYER THAT KEEPS EXPERTS PLAIN STAYS AT FOUR CLASSES. Two plain experts leave 510 + * quantised ones, four leave 508; either way the layer is served by `moe_gemm_q_mod4`, the + * class being the expert's PLACE in the sort mod 4 (the plain ones sorted last), and at 510 + * classes 0 and 1 hold 128 experts and 2 and 3 hold 127 -- the declaration hands a table op's + * first tables the remainder. The plain experts' extra tiles go to ranks 0 and 1: every rank + * holds the same routed width, and the shared expert's extra block is rank 2's. */ + { + const RadEncoding w4p = [] { RadEncoding e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); + rad_enc_copy_str(e.transform, "fwht128"); return e; }(); + const RadEncoding plain = rad_enc_plain(RAD_BF16); + /* The parity slices, [lo, hi) by place parity, and the four-class ones by place mod 4. */ + const int64_t par_lo[4][2] = { { 0, 512 }, { 256, 0 }, { 384, 256 }, { 512, 384 } }; + const int64_t par_hi[4][2] = { { 256, 640 }, { 384, 256 }, { 512, 384 }, { 640, 512 } }; + const int64_t c4_lo[4][4] = { { 0, 512, 384, 256 }, { 256, 0, 512, 384 }, + { 384, 256, 0, 512 }, { 512, 384, 256, 0 } }; + const int64_t c4_hi[4][4] = { { 256, 640, 512, 384 }, { 384, 256, 640, 512 }, + { 512, 384, 256, 640 }, { 640, 512, 384, 256 } }; + for (int nprot : { 2, 4 }) { + const std::vector pe = nprot == 2 ? std::vector{ 3, 10 } + : std::vector{ 3, 10, 21, 40 }; + for (int r = 0; r < world; ++r) { + RadBuilder bp; + for (int e : pe) { + bp.encs.push_back({ "blk.1.ffn_gate_up_exps." + std::to_string(e) + ".weight", + plain }); + bp.encs.push_back({ "blk.1.ffn_down_exps." + std::to_string(e) + ".weight", + plain }); + } + bp.encs.push_back({ "ffn_gate_up_exps", w4p }); + bp.encs.push_back({ "ffn_down_exps", w4p }); + RadBuildCtx cp = build_ctx(r, world); + cp.max_tok = 2048; cp.max_seqs = 8; cp.max_spec = 3; cp.max_ctx = 200000; + REQUIRE_EQ(qwen4exp_fp8::declare(&bp, &meta, &cp), RAD_OK); + const int ncls = 4; + const int64_t n_reg = ne_all - nprot; + /* layer 1's quantised GEMMs, and nobody else's */ + int l1_ops = 0, other_ops = 0; + for (const RecOp& o : bp.ops) { + if (o.op != "moe_gemm_q" && o.op != "moe_gemm_q_mod4") continue; + bool l1 = false; + for (rad_weight wh : o.w) + l1 = l1 || bp.weights[wh - 1].name.rfind("blk.1.", 0) == 0; + if (!l1) { CHECK_EQ(o.op, std::string("moe_gemm_q_mod4")); ++other_ops; continue; } + ++l1_ops; + CHECK_EQ(o.op, std::string(ncls == 4 ? "moe_gemm_q_mod4" : "moe_gemm_q")); + CHECK_EQ(pint(&o, "n_expert"), n_reg); + CHECK_EQ(o.w.size(), (size_t)(2 * n_reg)); + /* the four runs, read off the declaration: codes then scales, class by class, + * each class the places q, q + 4, ... -- 128, 128, 127, 127 at 510 */ + size_t at = 0; + for (int q = 0; q < 4; ++q) { + const int64_t nq = (n_reg + 3 - q) / 4; + for (int half = 0; half < 2; ++half) + for (int64_t j = 0; j < nq && at < o.w.size(); ++j, ++at) { + const std::string& wn = bp.weights[o.w[at] - 1].name; + const int e = atoi(wn.c_str() + wn.find("_exps.") + 6); + int place = e; + for (int x : pe) place -= x < e ? 1 : 0; + CHECK_EQ(place, (int)(q + 4 * j)); + CHECK((wn.find(".scale") != std::string::npos) == (half == 1)); + } + } + CHECK_EQ(at, o.w.size()); + } + CHECK_EQ(l1_ops, 2); + CHECK(other_ops > 0); + /* every quantised expert of layer 1 by its place: the class's slice */ + int seen = 0; + for (const RecWeight& w : bp.weights) { + if (w.name.rfind("blk.1.ffn_down_exps.", 0) != 0) continue; + if (w.name.compare(w.name.size() - 7, 7, ".weight") != 0) continue; + if (w.d.dtype == RAD_BF16) continue; /* the plain ones, below */ + const int e = atoi(w.name.c_str() + 20); + int place = e; + for (int x : pe) place -= x < e ? 1 : 0; + CHECK(w.span_set); + if (ncls == 4) { + CHECK_EQ(w.span_lo, c4_lo[r][place % 4]); + CHECK_EQ(w.span_hi, c4_hi[r][place % 4]); + } else { + CHECK_EQ(w.span_lo, par_lo[r][place % 2]); + CHECK_EQ(w.span_hi, par_hi[r][place % 2]); + } + ++seen; + } + CHECK_EQ(seen, (int)n_reg); + /* the plain experts' tiles: by narrow_place at two classes, by rank at four */ + const int64_t p2_lo[4] = { 384, 512, 0, 192 }, p2_hi[4] = { 512, 640, 192, 384 }; + const int64_t p4_lo[4] = { 0, 192, 384, 512 }, p4_hi[4] = { 192, 384, 512, 640 }; + int pseen = 0; + for (const RecWeight& w : bp.weights) { + if (w.name.rfind("blk.1.ffn_", 0) != 0 || w.d.dtype != RAD_BF16) continue; + if (w.name.find("_exps.") == std::string::npos) continue; + if (w.name.compare(w.name.size() - 7, 7, ".weight") != 0) continue; + CHECK(w.span_set); + CHECK_EQ(w.span_lo, ncls == 4 ? p4_lo[r] : p2_lo[r]); + CHECK_EQ(w.span_hi, ncls == 4 ? p4_hi[r] : p2_hi[r]); + ++pseen; + } + CHECK_EQ(pseen, 2 * nprot); + } + } + } + /* ---- THE PLAIN bf16 EXPERTS AT FOUR RANKS. * * They are declared beside the quantised ones by a SECOND grouped GEMM, over their own slice of @@ -2098,18 +2217,19 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { * it refused the model on the ranks where that number was wrong -- two of four, which then * never arrived at the all-reduce's rendezvous and took the whole launch down with it. * - * Ten tiles over four ranks is 2, 2, 3, 3: an UNEVEN share, still whole tiles, every tile owned - * once. Ranks 2 and 3 compute 192 columns of every protected expert and ranks 0 and 1 compute - * 128, because ranks 0 and 1 take the routed experts' extra blocks (narrow_place). Two - * protected experts so the even-count rule the parity tables need holds, as the production - * recipe's pairs make it hold. */ + * Ten tiles over four ranks is 3, 3, 2, 2: an UNEVEN share, still whole tiles, every tile owned + * once. Ranks 0 and 1 compute 192 columns of every protected expert and ranks 2 and 3 compute + * 128: the routed experts are split in four classes, so every rank holds the same routed + * width, and rank 2 holds the shared expert's extra block (narrow_place). Two protected + * experts, as the production recipe's pairs have it. */ { const RadEncoding w4p = [] { RadEncoding e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); rad_enc_copy_str(e.transform, "fwht128"); return e; }(); const RadEncoding plain = rad_enc_plain(RAD_BF16); - /* [lo, hi) of the plain expert's columns, per rank -- literal, for the reason given above. */ - const int64_t p_lo[4] = { 384, 512, 0, 192 }; - const int64_t p_hi[4] = { 512, 640, 192, 384 }; + /* [lo, hi) of the plain expert's columns, per rank -- literal, for the reason given above. + * The layer is served at four classes, so the extra tiles are cut by rank: 3, 3, 2, 2. */ + const int64_t p_lo[4] = { 0, 192, 384, 512 }; + const int64_t p_hi[4] = { 192, 384, 512, 640 }; for (int r = 0; r < world; ++r) { RadBuilder bp; bp.encs = { { "blk.1.ffn_gate_up_exps.3.weight", plain },