From eb14e4f64282350d362badb78816a0e189e76515 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:15 +0200 Subject: [PATCH] glm5next: the MLA row form, opt-in with RADIANCE_GLM_MLA_ROWS=1 -- a prefill-sized step by rows over the ranks, each rank with all 64 heads From GlmTp::kSplitRows each rank runs its run of the step's rows (GlmTp::run_of: ceil(T / world) rows, the last run shorter) through q_b, absorption, attention with all 64 heads (mla_attn_rows_bf16), expansion and o, and an all_gather of whole runs takes the all-reduce's place. The latent cache and the DSA selection are whole on every rank, so nothing is exchanged before the attention; each rank sends its run to seven peers, half the bytes of the two-shot all-reduce, through the same exchange instance. In a 4096-row chunk at 16k of context a rank's attention drops from 14.0 to 3.9 ms a layer on the kernel bench. The price is q_b, kv_b and o at full width on every rank: 120 MiB a layer, 1.29 GiB a card over the 11 trunk layers, and about 0.1 GiB of activations; the MTP layer keeps its heads. The full-width weights are whole views (RadWeightDecl::source) of blk.N.attn_q_b, attn_kv_b and attn_output, the head form's container entries, so they take the stored encoding (fp8a8f32, bf16) and need no name map; LinearFP8 gets `stored` for that, served by its block-fp8 branch only, and LinearFP8::step writes a run of rows from a given output row. The head form stays the default, unset or RADIANCE_GLM_MLA_ROWS=0, and declares none of it: that graph is the one before this change, byte for byte (the pinned hashes). The row form is not bit-identical to the head form, and GLM-5.3 turns that into a measurable divergence: over a 43k-position KL corpus at TP8 (English prose, German prose, code) the row form scores a mean KL of 0.033 against the head form (median 0.004, top-1 agreement 93.5 %), with greedy text unchanged. The projections are not the cause: q_b and o over a rank's rows give the head form's bytes (r4d_emu), and o summed as eight rank partials in the all-reduce's order (RADIANCE_GLM_MLA_ROWS=2, a test form, GlmMla::Form::rows_sliced_o) scores 0.032. The attention's rounding is: the rows kernel parts from the paired union tile in about 0.1 % of every row's outputs by one bf16 step (the union pairing sums a pair's second row in another order), and the 16-head tile, which parts in the same share of every second row only, halves the KL to 0.015. A bit-identical row form would run the union tile eight times a row over its own group of eight heads, without this kernel's gain, or need a rows kernel with the union's arithmetic; neither is here, so the form is opt-in. Measured on eight R9700 at Gen5 links, the same build: a 20k-token prefill 5074 tok/s in the row form against 4270 in the head form, BetterBench prefill at 22k 4984 against 4151, single stream 181.8 against 180.2 tok/s, eight streams 468 against 454. glm5next_test declares the block at one to eight ranks and checks the full-width views and their sources, the fp8a8f32 GEMMs, the gather's bound against the all-reduce's, each rank's operands at 300 rows (runs of 38, the last 34 at eight ranks) and the head form at 255; the o-slices form's eight GEMMs and seven adds; the model's counts and the TP8 pin under RADIANCE_GLM_MLA_ROWS=1 (0x1d378152c40f8834 / 0x82ed1094dbf4b637), with the default pins unchanged; and the row rule against both formulas it replaced. plugin_test resolves every band of every op the row form adds at eight ranks against libr4d, with no card. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_glm_mla.h | 191 ++++++++++++++++- arch/common/rad_fp8.h | 38 +++- arch/common/rad_glm_tp.h | 7 +- arch/glm5next/glm5next.cpp | 48 ++++- docs/ARCHITECTURES.md | 86 +++++--- docs/GUIDE.md | 1 + docs/OPS.md | 3 +- tests/glm5next_test.cpp | 359 +++++++++++++++++++++++++++++--- tests/plugin_test.cpp | 60 ++++++ 9 files changed, 717 insertions(+), 76 deletions(-) diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index 7c54e67d..f7ee83fa 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -3,14 +3,23 @@ * complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent * for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual. * - * Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and - * kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are - * replicated. */ + * Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the + * rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent + * cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead + * (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b, + * absorption, attention, expansion and the output projection with all 64 heads, then an + * all_gather lays the runs out as the whole step. The latent cache and the selection are whole on + * every rank already, so the split needs no other exchange. The gather moves half the bytes of + * the head form's all-reduce, and the attention loads each key once for all 64 heads of a row. + * The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q + * unset declares neither them nor the form. */ #ifndef RAD_BLOCK_GLM_MLA_H #define RAD_BLOCK_GLM_MLA_H #include "rad_fp8.h" #include "rad_glm_tp.h" +#include #include +#include namespace rad { namespace arch { @@ -88,11 +97,33 @@ struct MlaLatent { }; struct GlmMla { + /* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every + * step size and spares the full-width weights' VRAM; `rows` is the row form; `rows_sliced_o` + * the row form with o summed as the head form sums it (a test of how much of the two forms' + * difference is o's rounding). The plugin chooses; the block takes the choice through which + * RowsWire buffers it is given. */ + enum class Form { heads, rows, rows_sliced_o }; + /* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold + * world * rows_for(T) rows, since every rank's run is gathered at full length. */ + struct RowsWire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0; + ActFP8 attn{}; + /* Form::rows_sliced_o only: o in the head form's world K slices, each rounded to bf16 + * ([world * rows, 4096]), summed in f32 in ascending slice order as the exact all-reduce + * folds ranks (two [rows, 4096] f32 planes), rounded once. */ + rad_buf slices = 0, acc = 0, widened = 0; + }; struct Wire { ActFP8 input{}, q_low{}, attn{}; rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0; MlaLatent::Wire core{}; + RowsWire rows{}; }; + /* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */ + static constexpr int64_t kOutRowBytes = 4096 * 2; + static int64_t rows_for(int64_t T, int world) { + return GlmTp::run_rows(T, world, kOutRowBytes); + } Geom g{}; Wire w{}; int layer = 0; @@ -103,6 +134,12 @@ struct GlmMla { MlaLatent core{}; rad_weight q_gain = 0, kv_gain = 0; rad_op op_kv_norm = 0, op_store = 0, op_ar = 0; + LinearFP8 rows_q_b{}, rows_output{}; + QuantFP8 rows_quant{}; + rad_weight rows_kv_b = 0; + rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0; + std::vector rows_o_slices; + rad_op op_slice_first = 0, op_slice_widen = 0, op_slice_add = 0, op_slice_narrow = 0; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* prefix, rad_kvgroup group, bool reduce = true, bool defer_finish = false) { @@ -160,7 +197,126 @@ struct GlmMla { GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); if (reduce) op_ar = GlmTp::reduce(b, g, w.out); - return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL; + if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL; + return reduce ? declare_rows(b, nm, prefix) : RAD_OK; + } + /* Declared whatever the step size, as every TP split here is: arena levels declare again at a + * smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's, + * so both share one exchange instance and its scratch. */ + int declare_rows(RadBuilder* b, Names& nm, const char* prefix) { + const auto& r = w.rows; + if (!r.q || g.world < 2) return RAD_OK; + if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL; + const int64_t R = rows_for(g.max_tok, g.world); + const auto wg = grp_layer(layer); + /* Whole views of the head form's container entries: one stored weight each, whose + * encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */ + rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer); + RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536, + RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + w.q_low, r.q, R)); + rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer), + nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16, + { 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg); + if (!rows_kv_b) return RAD_E_INVAL; + auto project = [&](const char* mode, rad_buf in, rad_buf out) { + return rw(b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64), + RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512), + RAD_STR("mode", mode), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(rows_kv_b)), + { in }, { out }); + }; + op_rows_absorb = project("absorb", r.q, r.q_latent); + op_rows_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512), + RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks), + RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.q_latent, w.core.selected, w.core.length }, { r.attn_latent }); + op_rows_expand = project("expand", r.attn_latent, r.attn.x); + RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384)); + if (r.slices) { + RAD_ARCH_TRY(declare_o_slices(b, nm, prefix, R)); + } else { + rows_output.stored = nm.f("blk.%d.attn_output.weight", layer); + RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), + 4096, 16384, RAD_SHARD_NONE, wg, + { nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, + r.out, R)); + } + op_rows_gather = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.out }, { w.out }); + return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK + : RAD_E_INVAL; + } + /* The test form of o: slice k is the head form's rank k slice of the stored weight's columns, + * a GEMM over the matching columns of the quantised input. */ + int declare_o_slices(RadBuilder* b, Names& nm, const char* prefix, int64_t R) { + const auto& r = w.rows; + if (!r.acc || !r.widened) return RAD_E_INVAL; + const int64_t K = 16384 / g.world; + rows_o_slices.assign((size_t)g.world, LinearFP8{}); + for (int k = 0; k < g.world; ++k) { + auto& lin = rows_o_slices[(size_t)k]; + lin.stored = nm.f("blk.%d.attn_output.weight", layer); + RAD_ARCH_TRY(lin.declare(b, nm, g, nm.f("blk.%d.attn_output_rows%d", layer, k), 4096, + K, RAD_SHARD_COL, grp_layer(layer), + { nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.slices, R, + {}, k * K, (k + 1) * K)); + } + auto cast = [&](const char* from, const char* to, rad_buf x, rad_buf y) { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 4096), + RAD_STR("from", from), RAD_STR("to", to)), + RAD_NOWEIGHTS), + { x }, { y }); + }; + op_slice_first = cast("bf16", "f32", r.slices, r.acc); + op_slice_widen = cast("bf16", "f32", r.slices, r.widened); + op_slice_add = rw(b, + RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 4096), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { r.acc, r.widened }, { r.acc }); + op_slice_narrow = cast("f32", "bf16", r.acc, r.out); + return op_slice_first && op_slice_widen && op_slice_add && op_slice_narrow ? RAD_OK + : RAD_E_INVAL; + } + void step_o_slices(RadCtx* ctx, int64_t run, int64_t n) const { + const auto& r = w.rows; + const int64_t K = 16384 / g.world, G = K / RAD_FP8_BLOCK; + for (int k = 0; k < g.world; ++k) { + const auto& lin = rows_o_slices[(size_t)k]; + RAD_ISSUE_N(ctx, lin.op, n, bcol(r.attn.q, k * K, K, n), bcol(r.attn.s, k * G, G, n), + RAD_W(lin.w), RAD_W(lin.ws), brow_slice(r.slices, k * run, n, 4096), + RAD_NONE, RAD_NONE); + } + RAD_ISSUE_N(ctx, op_slice_first, n, brow_slice(r.slices, 0, n, 4096), brows(r.acc, n)); + for (int k = 1; k < g.world; ++k) { + RAD_ISSUE_N(ctx, op_slice_widen, n, brow_slice(r.slices, k * run, n, 4096), + brows(r.widened, n)); + RAD_ISSUE_N(ctx, op_slice_add, n, brows(r.acc, n), brows(r.widened, n), + brows(r.acc, n)); + } + RAD_ISSUE_N(ctx, op_slice_narrow, n, brows(r.acc, n), brows(r.out, n)); + } + /* From the TP split threshold, and while the last rank's run is not empty (always at that + * threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */ + bool rows_take(int64_t T) const { + return op_rows_gather && GlmTp::splits(T, g.world) && + (g.world - 1) * rows_for(T, g.world) < T; } void prepare(RadCtx* ctx, const RadBatch* batch) const { const auto* kb = kv_batch(batch, kv); @@ -173,17 +329,42 @@ struct GlmMla { kv_a.step(ctx, w.input, w.kv_raw, T); q_norm.step(ctx, T); RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T)); - q_b.step(ctx, w.q_low, w.core.q, T); + if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T); RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); } void finish(RadCtx* ctx, const RadBatch* batch) const { const int64_t T = batch->n_tok; + if (rows_take(T)) { + finish_rows(ctx, T); + return; + } core.step(ctx, T); attn_quant.step(ctx, T); output.step(ctx, w.attn, w.out, T); if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); } + /* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the + * gather sends its unwritten tail rows, which land past T. */ + void finish_rows(RadCtx* ctx, int64_t T) const { + const auto& r = w.rows; + const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes); + const int64_t first = run.first, n = run.rows; + rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0); + RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n)); + RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer), + brow_slice(w.core.selected, first, n, core.c.blocks), + brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n)); + RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b), + brows(r.attn.x, n)); + rows_quant.step(ctx, n); + if (r.slices) + step_o_slices(ctx, run.run, n); + else + rows_output.step(ctx, r.attn, r.out, n); + RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run), + brows(w.out, g.world * run.run)); + } }; } } // namespace rad::arch diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 9c17bae6..cb69f55e 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -745,6 +745,10 @@ struct LinearFP8 { * this is set; otherwise the linear reads unwritten arena bytes. */ bool reads_x = false; bool mapped = false; /* probe() made the name map; declare() does not make it again */ + /* The stored weight this linear's views take when it is not `.weight`: a second linear + * over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set + * before declare(); no name map is made, and only block fp8 is served this way. */ + const char* stored = nullptr; /* The weight's access class (rad_builder.h): read every pass by default; a linear run once a * request (an encoder's) says so, which lets placement keep it off the card. Set before * declare(). */ @@ -1039,9 +1043,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* Name map first: the weight's encoding, looked up through it, picks the branch below. */ const char* wn = nm.f("%s.weight", base); - if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); + if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src)); + const char* sw = stored ? stored : wn; RadEncoding enc{}; - const bool known = weight_enc(b, wn, &enc); + const bool known = weight_enc(b, sw, &enc); const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; @@ -1051,6 +1056,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * constraints. */ bf16 = g.w_bf16 || plain; if (bf16) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (known && !plain) { char en[256]; rad_enc_format(&enc, en, sizeof en); @@ -1089,6 +1099,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool rot8 = known && linear_is_w8h(enc); i8 = known && (linear_is_w8(enc) || rot8); if (i8) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (a.q8_fed && rot8 != a.q8_rot) { fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its " "producer wrote %s\n", wn, rot8 ? " rotated" : " plain", @@ -1148,6 +1163,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * codes, and (scale, zero) as `b_scale`. */ paro5 = known && linear_is_paro_w5(enc); if (paro5) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5; if (!a.x) { fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's " @@ -1214,6 +1234,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * whole 128s, the scale group. */ w4 = known && linear_is_w4(enc); if (w4) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (!a.x) { fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, " "and its input has none\n", wn); @@ -1284,6 +1309,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha paro = known && linear_is_paro_mxfp4(enc); mx = known && (linear_is_mxfp4(enc) || paro); if (mx) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (paro) { /* The rotation is applied to the activation, so this linear needs the input's bf16 * plane (probe() set reads_x) and quantises it itself. */ @@ -1395,10 +1425,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32; /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in * the checkpoint or made so by rad-convert's recipe. */ - w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, + w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, rp.w, rp.n); ws_row_div = RAD_FP8_BLOCK; - ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16, + ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n); if (!w || !ws) return RAD_E_INVAL; /* An uneven slice; the scale plane takes the same slice in blocks. */ diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h index 39a3d589..64d93c16 100644 --- a/arch/common/rad_glm_tp.h +++ b/arch/common/rad_glm_tp.h @@ -13,9 +13,10 @@ * row-interleaved all_gather, bit for bit the replicated projection * * The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered - * row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside - * its page tables, so its runs are multiples of four rows. The last rank's run may be short, or - * lie wholly past a small step (`run_of`). */ + * row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs + * are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its + * runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small + * step (`run_of`). */ #ifndef RAD_GLM_TP_H #define RAD_GLM_TP_H #include "rad_arch.h" diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index e2cfdc04..92aeb3c6 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -28,11 +28,27 @@ #include #include #include +#include +#include #include namespace glm5next { using namespace rad::arch; +/* The deployment switch of this plugin, read once a declare; docs/GUIDE.md lists it. + * RADIANCE_GLM_MLA_ROWS unset or 0 keeps the MLA's head form at every step size and declares none + * of the row form's full-width weights (1.29 GiB a card at eight ranks); 1 is the row form from + * GlmTp::kSplitRows; 2 is the row form with o summed as the head form sums it, a test of the two + * forms' difference (GlmMla::Form). The row form is opt-in: it is not bit-identical to the head + * form, and this model turns the rounding difference of a fraction of the attention outputs into + * a KL of 0.015 to 0.03 against it (docs/ARCHITECTURES.md). */ +static GlmMla::Form mla_form() { + const char* e = std::getenv("RADIANCE_GLM_MLA_ROWS"); + if (e && !std::strcmp(e, "1")) return GlmMla::Form::rows; + if (e && !std::strcmp(e, "2")) return GlmMla::Form::rows_sliced_o; + return GlmMla::Form::heads; +} + struct Layer { bool full = false, draft = false; ManifoldConn attn_hc{}, ffn_hc{}; @@ -46,6 +62,7 @@ struct Layer { struct Model { Names nm{}; Geom g{}; + GlmMla::Form form = GlmMla::Form::rows; std::vector layers; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; /* The streams and the step's stream-wide buffers. */ @@ -102,7 +119,9 @@ static int stream_buffers(RadBuilder* b, Model& m) { m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 }); m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 }); m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 }); - m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 }); + /* Rounded up to whole runs: the MLA row form gathers every rank's run at full length. */ + m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, + { g.world * GlmMla::rows_for(T, g.world), 4096 }); m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 }); @@ -132,9 +151,9 @@ static int kda_buffers(RadBuilder* b, Model& m) { kw.core.out = bf("recurrent_out", W); return RAD_OK; } -/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under - * TP the selection planes hold every rank's run of rows, which can reach past the step - * (DsaCache::part_rows). */ +/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then + * the row form's (Model::form). Under TP the selection planes hold every rank's run of rows, + * which can reach past the step (DsaCache::part_rows). */ static int mla_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; @@ -160,6 +179,21 @@ static int mla_buffers(RadBuilder* b, Model& m) { const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T; aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 }); aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ }); + if (g.world > 1 && m.form != GlmMla::Form::heads) { + auto& rows = aw.rows; + const int64_t R = GlmMla::rows_for(T, g.world); + rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 }); + rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 }); + RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R)); + rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 }); + if (m.form == GlmMla::Form::rows_sliced_o) { + rows.slices = decl_b(b, nm.f("rows_o_slices"), RAD_BF16, { g.world * R, 4096 }); + rows.acc = decl_b(b, nm.f("rows_o_sum"), RAD_F32, { R, 4096 }); + rows.widened = decl_b(b, nm.f("rows_o_slice_f32"), RAD_F32, { R, 4096 }); + } + } return RAD_OK; } static int indexer_buffers(RadBuilder* b, Model& m) { @@ -292,7 +326,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096)); if (lay.full) { - RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true)); + // The MTP layer keeps the head form: its row form would cost another 126 MB a card. + auto aw = m.aw; + if (draft) aw.rows = {}; + RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true)); DsaCache::Config c; c.blocks = (g.max_ctx + 3) / 4 + 1; c.work = (g.max_tok + 3) / 4 + g.max_seqs; @@ -398,6 +435,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c auto& g = m.g; m.nm = Names(ctx->scope); auto& nm = m.nm; + m.form = mla_form(); RAD_ARCH_TRY(geometry(g, meta, ctx, world)); RAD_ARCH_TRY(stream_buffers(b, m)); RAD_ARCH_TRY(kda_buffers(b, m)); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 9cde6552..1eb618fa 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -427,18 +427,19 @@ declared beside it when the container carries the tower and the deployment asks 654df43; for the tower and its processor, transformers' `glm5_next`. The plugin is one file over blocks in `arch/common`, one block a file; it declares the buffers -the blocks share, places them and issues the step's order. +the blocks share, places them and issues the step's order, and reads its one deployment switch +(`RADIANCE_GLM_MLA_ROWS`, docs/GUIDE.md) once a declare. | file | block | what | |---|---|---| | `rad_block_glm_mhc.h` | `ManifoldConn` | the four-stream residual's read and write | | `rad_block_glm_kda.h` | `GlmKda`, `KdaState` | the 34 linear layers and their recurrence | -| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers and their absorbed core | +| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers, in the head form or the row form | | `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection | | `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` | | `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 | | `rad_block_glm_vision.h` | `GlmVision`, `MediaRows` | the tower, and its rows over the embeddings | -| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection | +| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the one row rule, the split thresholds, the column split of a replicated f32 projection | ``` 45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16) @@ -534,45 +535,66 @@ at eight ranks each card holds 22.06 GiB of them, 19.67 GiB the routed experts. layer's latent, index and tail for every row and runs its MoE on the proposal rows only. **Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp` -declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and -8, the connection, router and index-gate splits at 1, 2, 4 and 8, the indexer's row split at 2 -and 8, the row rule at every world, each issue's operand count against the loaded kernel -libraries' schemas, and every declared weight against the served container's names and encodings. +declares and steps the whole plugin at 1 and 8 against pinned graph and step hashes (the head form, +the row form), the connection, router and index-gate splits at 1, 2, 4 and 8, +the indexer's row split at 2 and 8, the MLA row split at 1, 2, 4 and 8, the row rule at every +world, each issue's operand count against the loaded kernel libraries' schemas, and every declared +weight against the served container's names and encodings. -One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated -piece of work splits by rows over the ranks instead, each rank taking one run of ceil(T / world) -rows rounded up to whole 16-byte words of the row it gathers, because an `all_gather` moves whole -words: multiples of four rows for the indexer's one i32 length a row. The last run may be short; -a rank whose run lies wholly past a small step takes the first run and computes dead rows, so -every plane it gathers is written (`GlmTp::run_of`). The indexer also splits a smaller step, from -16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in -decode, the collective costs more than it saves and every rank runs the replicated form. +One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated or +head-split piece of work splits by rows over the ranks instead, each rank taking one run of +ceil(T / world) rows rounded up to whole 16-byte words of the row it gathers, because an +`all_gather` moves whole words: whole rows for the MLA's 4096-wide bf16 output, multiples of four +rows for the indexer's one i32 length a row. The last run may be short; a rank whose run lies +wholly past a small step takes the first run and computes dead rows, so every plane it gathers is +written (`GlmTp::run_of`). The indexer alone also splits a smaller step, from 16 rows once rows x +live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in decode, the collective +costs more than it saves and every rank runs the replicated or head-split form. - The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums them. The dense feed-forward splits its 12288 the same way. - MLA splits by whole heads: the rows of q_b and kv_b (8 heads a rank at eight) and the columns - of o. q_a, kv_a and the latent are replicated. + of o. q_a, kv_a and the latent are replicated. With `RADIANCE_GLM_MLA_ROWS=1`, from the + threshold, it splits by rows instead (`GlmMla::Form::rows`): each rank takes its run under the row rule, the last run shorter, + through q_b, absorption, attention with all 64 heads + (`mla_attn_rows_bf16`, docs/OPS.md), expansion and o, and an `all_gather` of whole runs takes the + all-reduce's place. The latent cache and the DSA selection are whole on every rank, so nothing + is exchanged before the attention. Each rank sends its run to seven peers, half the bytes of the + two-shot all-reduce, and the gather shares that all-reduce's exchange instance. The price is + q_b, kv_b and o at full width on every rank, 120 MiB a layer and 1.29 GiB a card over the 11 + trunk layers (the MTP layer keeps its heads), about 0.1 GiB of activations besides; `2` is the + row form with o summed as the head form sums it (`GlmMla::Form::rows_sliced_o`), a test of the + two forms' difference. The head form is the default because the row form is not bit-identical + to it, and this model turns that into a measurable divergence: against the head form over a + 43k-position corpus the row form scores a mean KL of 0.033 (median 0.004, top-1 agreement + 93.5 %), greedy text unchanged. The projections are not the cause (q_b and o give the head + form's bytes when o is summed as eight rank partials, and the KL stays at 0.032); the + attention's rounding is: the rows kernel parts from the paired tile in about 0.1 % of every + row's outputs by one bf16 step, and the 16-head tile, which parts in the same share of every + second row only, halves the KL to 0.015. Measured + on eight R9700 at Gen5 links, the same build: a 20k-token prefill 5074 tok/s in the row form + against 4270 in the head form; BetterBench single stream 181.8 against 180.2 tok/s, eight + parallel 468 against 454. - KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two rank-128 projections into the gates are replicated. - The indexer's key side is replicated: every rank keeps the whole index cache and its tail. Its query side splits by rows from the threshold: each rank scores its run under the row rule, - R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache - (`dsa_score` with `row_part`, the last run's rows past the step scoring `-inf`) and selects for - the rows of its run that exist, under the bounds the scorer rebased to the run's first row - (`cu_part`, docs/OPS.md); two `all_gather`s lay the runs' page tables and lengths end to end, - 513 and 1 i32 a row, 8 MiB a layer at a 4096-row chunk. The run's queries are all a rank needs, - so the query projection, its quantiser and the head gates run on the run's rows too, and the - gates need no gather; the bf16 projection stays on the step's rows where a run would be 64 rows - or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection - is the same kernels' answer to the same operands, so the joined table is bit-identical to one - rank's and MLA reads it unchanged. The scoring grows with the context (every row scores every - complete block of its sequence), so this is where long prompts gain: the score plane shrinks to - one run (256 MiB to 32 MiB at 64k of context and a 4096-row chunk). A smaller step splits too - from 16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`): eight sequences - verifying five drafts from about 22k of context, where the scoring of 48 rows outweighs the two - gathers; a single sequence's decode never does, and below both thresholds the indexer runs - whole. + R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache (`dsa_score` with `row_part`, + the last run's rows past the step scoring `-inf`) and selects for the rows of its run that exist, + under the bounds the scorer rebased to the run's first row (`cu_part`, docs/OPS.md); two + `all_gather`s lay the runs' page tables and lengths end to end, 513 and 1 i32 a row, 8 MiB a layer + at a 4096-row chunk. The run's queries are all a rank needs, so the query projection, its + quantiser and the head gates run on the run's rows too, and the gates need no gather; the bf16 + projection stays on the step's rows where a run would be 64 rows or fewer, the skinny band whose + split count a tuned configuration may set. Each row's selection is the same kernels' answer to + the same operands, so the joined table is bit-identical to one rank's and MLA reads it unchanged. + The scoring grows with the context (every row scores every complete block of its sequence), so + this is where long prompts gain: the score plane shrinks to one run (256 MiB to 32 MiB at 64k of + context and a 4096-row chunk). A smaller step splits too from 16 rows once rows x live blocks + reach 2^18 (`GlmTp::kSplitWork`): eight sequences verifying five drafts from about 22k of + context, where the scoring of 48 rows outweighs the two gathers; a single sequence's decode never + does, and below both thresholds the indexer runs whole. - The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. - The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 00968f9a..77f9f020 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3129,6 +3129,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | +| `RADIANCE_GLM_MLA_ROWS` | `arch/glm5next`'s MLA form in a prefill-sized pass. Unset or `0`: split by heads at every pass, the default, holding none of the full-width projections the row form needs. `1`: split by rows from 256 rows, faster in prefill, for 1.29 GiB a card at TP8 and not bit-identical to the default. `2`: the row form with o summed as the head form sums it, a test of the two forms' difference (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_AR_FENCE_FROM` | four-rank all-reduces of at least this many elements take a full fence before their flag (default 131072: prefill chunks, never decode or verify); cures a rare fresh-start divergence on the 31B at tp 4; `0` turns it off | | `RADIANCE_PREFETCH` | `0` declares none of the weight reads the Gemma 4 31B and its DFlash2 drafter issue beside each all-reduce at decode and verify heights (libr4d `prefetch`: the next GEMM's leading weight bytes read into the on-die cache while the collective leaves the memory idle); on by default at more than one rank where the kernel library serves the op | diff --git a/docs/OPS.md b/docs/OPS.md index feb942c2..30f22814 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2858,7 +2858,8 @@ through a lane swap instead of LDS. The next chunk's keys are fetched while the multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a -workgroup), which no constraint routes to it. +workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor +parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`). `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index c646a1c1..e3d5427c 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -331,9 +331,301 @@ TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { } } +/* GLM's MLA from the TP split threshold: each rank runs its run of the step's rows with all 64 + * heads, through q_b, kv_b and o at full width, and an all_gather lays the runs out, instead of + * its heads over every row and an all-reduce. Runs are ceil(T / world) rows, the last one short; + * the gather sends whole runs into an output of world runs. Below the threshold, and at TP1, the + * head form is unchanged, as it is unless the row form is opted into (the default). */ +TEST(glm_mla_splits_a_prefill_by_rows_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.kv_block = 4; + // The container's MLA entries; the row form's names are not among them. + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "attn_q_a.weight", fp8 }, + { "attn_kv_a.weight", fp8 }, + { "attn_q_b.weight", fp8 }, + { "attn_output.weight", fp8 }, + { "attn_kv_b.weight", rad_enc_plain(RAD_BF16) } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.max_ctx = 4096; + g.eps = 1e-5; + g.world = world; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + const int64_t T = 512, R = GlmMla::rows_for(T, world), H = 64 / world; + auto act = [&](ActFP8& a, const char* name, int64_t rows, int64_t width) { + a.x = decl_b(&b, name, RAD_BF16, { rows, width }); + return a.declare_qs(&b, nm, g, name, width, rows); + }; + GlmMla::Wire w; + REQUIRE_EQ(act(w.input, "normalized", T, 4096), RAD_OK); + w.q_raw = decl_b(&b, "q_raw", RAD_BF16, { T, 1536 }); + w.kv_raw = decl_b(&b, "kv_raw", RAD_BF16, { T, 512 }); + REQUIRE_EQ(act(w.q_low, "q_low", T, 1536), RAD_OK); + w.latent = decl_b(&b, "latent", RAD_BF16, { T, 512 }); + w.out = decl_b(&b, "attn_delta", RAD_BF16, { world * R, 4096 }); + w.core.q = decl_b(&b, "query", RAD_BF16, { T, 16384 / world }); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { T, H, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { T, H, 512 }); + REQUIRE_EQ(act(w.attn, "expanded", T, 16384 / world), RAD_OK); + w.core.out = w.attn.x; + w.core.selected = decl_b(&b, "selected", RAD_I32, { T, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { T }); + w.rows.q = decl_b(&b, "rows_query", RAD_BF16, { R, 16384 }); + w.rows.q_latent = decl_b(&b, "rows_q_latent", RAD_BF16, { R, 64, 512 }); + w.rows.attn_latent = decl_b(&b, "rows_attn_latent", RAD_BF16, { R, 64, 512 }); + REQUIRE_EQ(act(w.rows.attn, "rows_expanded", R, 16384), RAD_OK); + w.rows.out = decl_b(&b, "rows_out", RAD_BF16, { R, 4096 }); + GlmMla mla; + REQUIRE_EQ(mla.declare(&b, nm, g, 3, w, "model.layers.3.self_attn", kv), RAD_OK); + const bool rows = world > 1; + CHECK_EQ(mla.op_rows_gather != 0, rows); + CHECK_EQ(count_op(b, "all_gather"), rows ? 1 : 0); + CHECK_EQ(count_op(b, "mla_attn"), rows ? 2 : 1); + const RecWeight* head_q = find_w(b, "blk.3.attn_q_b.weight"); + REQUIRE(head_q); + CHECK_EQ(head_q->d.shape[0], 16384 / world); + if (!rows) { + CHECK(!find_w(b, "blk.3.attn_q_b_rows.weight")); + continue; + } + const RecWeight* q_b = find_w(b, "blk.3.attn_q_b_rows.weight"); + const RecWeight* kv_b = find_w(b, "blk.3.attn_kv_b_rows.weight"); + const RecWeight* o = find_w(b, "blk.3.attn_output_rows.weight"); + REQUIRE(q_b && kv_b && o); + CHECK_EQ(q_b->d.shard, RAD_SHARD_NONE); + CHECK_EQ(q_b->d.shape[0], 16384); + CHECK_EQ(q_b->d.shape[1], 1536); + CHECK_EQ(kv_b->d.shard, RAD_SHARD_NONE); + CHECK_EQ(kv_b->d.dtype, RAD_BF16); + CHECK_EQ(kv_b->d.shape[0], 32768); + CHECK_EQ(kv_b->d.shape[1], 512); + CHECK_EQ(o->d.shard, RAD_SHARD_NONE); + CHECK_EQ(o->d.shape[0], 4096); + CHECK_EQ(o->d.shape[1], 16384); + // The full-width weights are whole views of the head form's container entries, so + // they take its encoding (block fp8 at f32 scales) and need no name map of their own. + const auto source = [](const RecWeight* w) { + return std::string(w && w->d.source ? w->d.source : ""); + }; + CHECK_EQ(source(q_b), "blk.3.attn_q_b.weight"); + CHECK_EQ(source(find_w(b, "blk.3.attn_q_b_rows.scale")), "blk.3.attn_q_b.weight"); + CHECK_EQ(source(kv_b), "blk.3.attn_kv_b.weight"); + CHECK_EQ(source(o), "blk.3.attn_output.weight"); + CHECK_EQ(source(find_w(b, "blk.3.attn_output_rows.scale")), "blk.3.attn_output.weight"); + CHECK_EQ(find_w(b, "blk.3.attn_q_b_rows.scale")->d.dtype, RAD_F32); + for (const auto& map : b.maps) CHECK(map.declared.find("_rows") == std::string::npos); + CHECK_EQ(pstr(&b.ops[mla.rows_q_b.op - 1], "dtype"), "fp8a8f32"); + CHECK_EQ(pstr(&b.ops[mla.rows_output.op - 1], "dtype"), "fp8a8f32"); + CHECK_EQ(pstr(&b.ops[mla.q_b.op - 1], "dtype"), "fp8a8f32"); + const RecOp* attn = &b.ops[mla.op_rows_attn - 1]; + CHECK_EQ(pint(attn, "heads"), 64); + CHECK_EQ(pint(attn, "blocks"), 513); + CHECK_EQ(param(attn, "M")->ihi, R); + CHECK(attn->reads == + std::vector({ w.rows.q_latent, w.core.selected, w.core.length })); + const RecOp* gather = &b.ops[mla.op_rows_gather - 1]; + const RecOp* reduce = &b.ops[mla.op_ar - 1]; + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pstr(gather, "dtype"), "bf16"); + CHECK(!param(gather, "row")); + // The all-reduce's message bound, so the two share one exchange instance. + CHECK_EQ(param(gather, "numel")->ihi, param(reduce, "numel")->ihi); + CHECK(gather->reads == std::vector({ w.rows.out })); + CHECK(gather->writes == std::vector({ w.out })); + std::vector slots(T); + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots.data(); + RadBatch batch{}; + batch.kv = &kb; + batch.n_kv_groups = 1; + for (int64_t steps : { 300, 255 }) { + batch.n_tok = steps; + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + mla.prepare(&ctx, &batch); + mla.finish(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + auto issued = [&](rad_op op) { + return std::count_if(ctx.issues.begin(), ctx.issues.end(), + [&](const RecIssue& i) { return i.op == op; }); + }; + const bool split = steps >= GlmTp::kSplitRows; + CHECK_EQ(issued(mla.q_b.op), split ? 0 : 1); + CHECK_EQ(issued(mla.core.op_attn), split ? 0 : 1); + CHECK_EQ(issued(mla.op_ar), split ? 0 : 1); + CHECK_EQ(issued(mla.op_rows_attn), split ? 1 : 0); + CHECK_EQ(issued(mla.op_rows_gather), split ? 1 : 0); + if (!split) continue; + const int64_t run = (steps + world - 1) / world, first = rank * run, + n = std::min(run, steps - first); + for (const auto& i : ctx.issues) { + if (i.op == mla.rows_q_b.op) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[0].handle, w.q_low.q); + CHECK_EQ(i.opd[0].offset, first * 1536); + CHECK_EQ(i.opd[0].rows, n); + CHECK_EQ(i.opd[2].handle, mla.rows_q_b.w); + CHECK_EQ(i.opd[4].handle, w.rows.q); + CHECK_EQ(i.opd[4].offset, 0); + CHECK_EQ(i.opd[4].rows, n); + } else if (i.op == mla.op_rows_attn) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[1].kind, RAD_OPK_KV); + CHECK_EQ(i.opd[2].handle, w.core.selected); + CHECK_EQ(i.opd[2].offset, first * 513); + CHECK_EQ(i.opd[2].rows, n); + CHECK_EQ(i.opd[3].handle, w.core.length); + CHECK_EQ(i.opd[3].offset, first); + CHECK_EQ(i.opd[3].rows, n); + CHECK_EQ(i.opd[4].handle, w.rows.attn_latent); + } else if (i.op == mla.rows_output.op) { + CHECK_EQ(i.n, n); + CHECK_EQ(i.opd[2].handle, mla.rows_output.w); + CHECK_EQ(i.opd[4].handle, w.rows.out); + CHECK_EQ(i.opd[4].offset, 0); + } else if (i.op == mla.op_rows_gather) { + CHECK_EQ(i.n, run * 4096); + CHECK_EQ(i.opd[0].handle, w.rows.out); + CHECK_EQ(i.opd[0].rows, run); + CHECK_EQ(i.opd[1].handle, w.out); + CHECK_EQ(i.opd[1].rows, world * run); + } + } + // Eight ranks at 300 rows: runs of 38, the last 34. + if (world == 8) CHECK_EQ(n, rank == 7 ? 34 : 38); + } + } +} + +/* RADIANCE_GLM_MLA_ROWS=2, a test form: the row form's o as the head form computes it, eight + * column slices of the stored weight (each rank's), each GEMM rounded to bf16, then widened and + * added in f32 in ascending slice order and rounded once, as the exact all-reduce folds. */ +TEST(glm_mla_row_form_can_sum_o_as_the_head_form_does) { + using namespace rad::arch; + const int world = 8, rank = 3; + RadBuilder b; + b.kv_block = 4; + // The container's MLA entries; the row form's names are not among them. + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "attn_q_a.weight", fp8 }, + { "attn_kv_a.weight", fp8 }, + { "attn_q_b.weight", fp8 }, + { "attn_output.weight", fp8 }, + { "attn_kv_b.weight", rad_enc_plain(RAD_BF16) } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.max_ctx = 4096; + g.eps = 1e-5; + g.world = world; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + const int64_t T = 512, R = GlmMla::rows_for(T, world), H = 64 / world; + auto act = [&](ActFP8& a, const char* name, int64_t rows, int64_t width) { + a.x = decl_b(&b, name, RAD_BF16, { rows, width }); + return a.declare_qs(&b, nm, g, name, width, rows); + }; + GlmMla::Wire w; + REQUIRE_EQ(act(w.input, "normalized", T, 4096), RAD_OK); + w.q_raw = decl_b(&b, "q_raw", RAD_BF16, { T, 1536 }); + w.kv_raw = decl_b(&b, "kv_raw", RAD_BF16, { T, 512 }); + REQUIRE_EQ(act(w.q_low, "q_low", T, 1536), RAD_OK); + w.latent = decl_b(&b, "latent", RAD_BF16, { T, 512 }); + w.out = decl_b(&b, "attn_delta", RAD_BF16, { world * R, 4096 }); + w.core.q = decl_b(&b, "query", RAD_BF16, { T, 16384 / world }); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { T, H, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { T, H, 512 }); + REQUIRE_EQ(act(w.attn, "expanded", T, 16384 / world), RAD_OK); + w.core.out = w.attn.x; + w.core.selected = decl_b(&b, "selected", RAD_I32, { T, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { T }); + w.rows.q = decl_b(&b, "rows_query", RAD_BF16, { R, 16384 }); + w.rows.q_latent = decl_b(&b, "rows_q_latent", RAD_BF16, { R, 64, 512 }); + w.rows.attn_latent = decl_b(&b, "rows_attn_latent", RAD_BF16, { R, 64, 512 }); + REQUIRE_EQ(act(w.rows.attn, "rows_expanded", R, 16384), RAD_OK); + w.rows.out = decl_b(&b, "rows_out", RAD_BF16, { R, 4096 }); + w.rows.slices = decl_b(&b, "rows_o_slices", RAD_BF16, { world * R, 4096 }); + w.rows.acc = decl_b(&b, "rows_o_sum", RAD_F32, { R, 4096 }); + w.rows.widened = decl_b(&b, "rows_o_slice_f32", RAD_F32, { R, 4096 }); + GlmMla mla; + REQUIRE_EQ(mla.declare(&b, nm, g, 3, w, "model.layers.3.self_attn", kv), RAD_OK); + REQUIRE_EQ(mla.rows_o_slices.size(), (size_t)8); + CHECK(!find_w(b, "blk.3.attn_output_rows.weight")); + for (int k = 0; k < 8; ++k) { + const RecWeight* w = find_w(b, "blk.3.attn_output_rows" + std::to_string(k) + ".weight"); + REQUIRE(w); + CHECK_EQ(w->d.shard, RAD_SHARD_COL); + CHECK_EQ(w->d.shape[1], 2048); + CHECK(w->span_set); + CHECK_EQ(w->span_lo, k * 2048); + CHECK_EQ(w->span_hi, (k + 1) * 2048); + CHECK_EQ(std::string(w->d.source), "blk.3.attn_output.weight"); + } + std::vector slots(300); + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots.data(); + RadBatch batch{}; + batch.kv = &kb; + batch.n_kv_groups = 1; + batch.n_tok = 300; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 3; + ctx.world = 8; + mla.finish_rows(&ctx, 300); + std::vector order; + for (const auto& i : ctx.issues) order.push_back(i.op); + const int64_t run = 38; + int gemm = 0, adds = 0; + for (const auto& i : ctx.issues) { + for (int k = 0; k < 8; ++k) + if (i.op == mla.rows_o_slices[(size_t)k].op) { + ++gemm; + CHECK_EQ(i.opd[0].offset, k * 2048); + CHECK_EQ(i.opd[0].cols, 2048); + CHECK_EQ(i.opd[1].offset, k * 16); + CHECK_EQ(i.opd[1].cols, 16); + CHECK_EQ(i.opd[4].offset, k * run * 4096); + CHECK_EQ(i.opd[4].rows, run); + } + adds += i.op == mla.op_slice_add; + } + CHECK_EQ(gemm, 8); + CHECK_EQ(adds, 7); + CHECK_EQ(ctx.issues.back().op, mla.op_rows_gather); + CHECK_EQ(ctx.issues[ctx.issues.size() - 2].op, mla.op_slice_narrow); +} + TEST( glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { using namespace rad::arch; + // With the row form opted into; unset again however the case leaves. + struct RowsOn { + RowsOn() { setenv("RADIANCE_GLM_MLA_ROWS", "1", 1); } + ~RowsOn() { unsetenv("RADIANCE_GLM_MLA_ROWS"); } + } rows_on; const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; const char* vals[] = { "1", "4", "288", "2048" }; @@ -433,9 +725,10 @@ TEST( CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); // The split is declared on every rank whatever its step size; only rank 0 issues it here. const bool split = world > 1; - // 43 routers (MTP included), the 90 mHC reads, and each of the 12 indexers' page - // tables and lengths; the index head gates follow the indexer's rows, ungathered. - CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 : 0); + // 43 routers (MTP included), the 90 mHC reads, each of the 12 indexers' page + // tables and lengths (the index head gates follow the indexer's rows, + // ungathered), and the 11 MLA row forms (the MTP layer keeps its heads). + CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 + 11 : 0); CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); ctx.issues.clear(); batch.draft_pass = -1; @@ -482,12 +775,17 @@ TEST( CHECK(ctx.step_fail.empty()); { // 512 rows reach the split: each router runs on its column slice, each mHC - // read on its chunks and each indexer, its head gates included, on its run - // of query rows, all gathered but the gates; at TP1 nothing changes. + // read on its chunks, each indexer, its head gates included, on its run + // of query rows, and each MLA on its run of rows, all gathered but the + // gates; at TP1 nothing changes. const auto long_ops = issued_ops(b, ctx); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), - world > 1 ? 42 + 90 + 22 : 0); + world > 1 ? 42 + 90 + 22 + 11 : 0); + // 1 embedding, 45 attention and 45 expert reductions, less the 11 MLA ones. + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_reduce"), + world > 1 ? 91 - 11 : 0); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mla_attn"), 11); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), world > 1 ? 0 : 90); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), @@ -551,6 +849,10 @@ TEST( } } +/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and + * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row + * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its + * gathers' message as a range. */ /* From the split threshold each rank scores its run of the step's query rows (rows past the step * included, which score -inf) and selects for the rows of it that exist, against the bounds the * scorer rebased to the run's first row; two all_gathers join the runs' page tables and lengths @@ -722,10 +1024,6 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) { } } -/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and - * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row - * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its - * gathers' message as a range. */ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -1338,6 +1636,7 @@ TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) /* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill * after history, a mixed step, a decode step, a verify and its draft passes. */ + TEST(glm53_is_the_pinned_graph_and_steps) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -1355,10 +1654,16 @@ TEST(glm53_is_the_pinned_graph_and_steps) { struct Case { int world; uint64_t graph, steps; + bool heads_only = false; /* the default: the graph before the row form */ }; const Case cases[] = { { 1, 0x906897570034f5f5ull, 0x68ffc03d2b640d51ull }, - { 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull } }; + { 8, 0x1d378152c40f8834ull, 0x82ed1094dbf4b637ull }, + { 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull, true } }; for (const Case& cs : cases) { + if (cs.heads_only) + unsetenv("RADIANCE_GLM_MLA_ROWS"); + else + setenv("RADIANCE_GLM_MLA_ROWS", "1", 1); RadBuilder b; b.kv_block = 4; b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, @@ -1376,11 +1681,13 @@ TEST(glm53_is_the_pinned_graph_and_steps) { REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK); const uint64_t g = graph_hash(b); const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world); - fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n", - cs.world, (unsigned long long)g, (unsigned long long)s); + fprintf(stderr, " pin: glm5next world %d%s: graph 0x%016llxull, steps 0x%016llxull\n", + cs.world, cs.heads_only ? " heads only" : "", + (unsigned long long)g, (unsigned long long)s); CHECK_EQ(g, cs.graph); CHECK_EQ(s, cs.steps); } + unsetenv("RADIANCE_GLM_MLA_ROWS"); } /* ==================================================================== GLM-5.3's vision tower */ @@ -1766,13 +2073,13 @@ RAD_TEST_MAIN() /* ==================================================================== the row rule */ -/* GlmTp::run_rows is the one rule the indexer's runs follow, and it is the formula it replaced: - * 4 * ceil(T / (4 * world)) for the indexer's 4-byte lengths, ceil(T / world) for a row of whole - * 16-byte words. At the split threshold, around a chunk and at the largest step, for every - * world: run_of covers the step once with no overlap, the last run short where the step ends - * inside it, and a rank whose run lies wholly past a small step takes the first run instead, so - * the planes it writes and gathers are never unwritten. */ -TEST(glm_tp_row_rule_is_the_old_formula_and_covers_a_step_once) { +/* GlmTp::run_rows is the one rule the MLA's and the indexer's runs follow, and it is the two + * formulas it replaced: ceil(T / world) for the MLA's 8192-byte rows, 4 * ceil(T / (4 * world)) + * for the indexer's 4-byte lengths. At the split threshold, around a chunk and at the largest + * step, for every world: run_of covers the step once with no overlap, the last run short where + * the step ends inside it, and a rank whose run lies wholly past a small step takes the first + * run instead, so the planes it writes and gathers are never unwritten. */ +TEST(glm_tp_row_rule_is_the_two_old_formulas_and_covers_a_step_once) { using namespace rad::arch; for (int world : { 1, 2, 4, 8 }) for (int64_t T : { 1, 5, 6, 48, 255, 256, 257, 300, 2047, 2048, 2049, 4096 }) { @@ -1780,6 +2087,7 @@ TEST(glm_tp_row_rule_is_the_old_formula_and_covers_a_step_once) { const int64_t narrow = GlmTp::run_rows(T, world, 4); CHECK_EQ(wide, (T + world - 1) / world); CHECK_EQ(narrow, 4 * ((T + 4 * world - 1) / (4 * world))); + CHECK_EQ(GlmMla::rows_for(T, world), wide); CHECK_EQ(DsaCache::part_rows(T, world), narrow); CHECK(world * wide >= T); CHECK(world * narrow >= T); @@ -2136,12 +2444,11 @@ std::string as_expert_zero(std::string n) { } /* namespace */ /* Every weight the plugin declares reads an entry the served container holds: under its own name, - * or through `source` for a view (a scale plane), and every GEMM names the dtype its weight's - * stored encoding calls for: `fp8a8f32` on the f32-scaled block FP8, `mxfp4a8` on the MXFP4 - * experts, `bf16` on the plain linears. The encodings come from the table, as the container would - * answer. A weight declared under a name the container does not hold, or a GEMM at a dtype its - * weight's encoding does not call for, passes every host test and leaves bands with no kernel at - * the eight-card start. */ + * or through `source` for a view (a scale plane, the row form's full-width projections), and + * every GEMM names the dtype its weight's stored encoding calls for: `fp8a8f32` on the f32-scaled + * block FP8, `mxfp4a8` on the MXFP4 experts, `bf16` on the plain linears. The encodings come + * from the table, as the container would answer. A full-width view declared as its own weight + * at `fp8a8` passed every host test and left 88 bands with no kernel at the eight-card start. */ TEST(glm53_declares_the_served_containers_names_and_their_encodings) { const Glm53Container& c = glm53_container(); MetaKV mk = glm53_vl_meta(); diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 9699bcde..7ac1acf5 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -1018,6 +1018,66 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) { CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_matrix_bf16 "); } +/* GLM-5.3-Flash's MLA split by rows at eight ranks (arch/common/rad_block_glm_mla.h), with the + * parameters its ops declare against the container's encodings (block fp8 at f32 scales): every + * band of every op the row form adds resolves on the device, up to a 4096-token step's run of + * 512 rows. A form libr4d does not serve would stop a TP8 start at "resolved to no kernel". */ +TEST(libr4d_resolves_every_band_of_glm_mla_split_by_rows) { + const std::string so = libr4d(); + if (so.empty()) return; + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + r.set_device_fact(RAD_FACT_P2P, 1); + auto all_resolve = [&](const char* op, const char* ranged, int64_t lo, int64_t hi, + const Geometry& g) { + const std::vector bands = r.build_bands(op, ranged, lo, hi, g); + bool ok = !bands.empty(); + for (const Band& x : bands) ok = ok && x.dom[RAD_DOMAIN_DEVICE].row; + if (!ok) std::fprintf(stderr, " %s: %s\n", op, band_names(bands).c_str()); + return ok; + }; + const int64_t R = 512; + for (const auto& [n, k] : { std::pair{ 16384, 1536 }, { 4096, 16384 } }) { + Geometry g; + g.set_i("N", n); + g.set_i("K", k); + g.set_i("group", 128); + g.set_s("dtype", "fp8a8f32"); + CHECK(all_resolve("gemm_nt_q", "M", 1, R, g)); + } + for (const char* mode : { "absorb", "expand" }) { + Geometry g; + g.set_i("heads", 64); + g.set_i("head_dim", 256); + g.set_i("latent_dim", 512); + g.set_s("mode", mode); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("mla_project", "M", 1, R, g)); + } + { + Geometry g; + g.set_i("latent_dim", 512); + g.set_i("heads", 64); + g.set_i("blocks", 513); + g.set_i("block_size", 4); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("mla_attn", "M", 1, R, g)); + } + { + Geometry g; + g.set_i("n", 16384); + g.set_i("group", 128); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("quant_act_fp8", "M", 1, 4096, g)); + } + { + Geometry g; + g.set_i("world_size", 8); + g.set_s("dtype", "bf16"); + CHECK(all_resolve("all_gather", "numel", 4096, 4096 * 4096, g)); + } +} + /* ================================================================== constraints that are not intervals */ namespace { std::string extra_dir() { return home() + "/testkernels/extra"; }