glm5next: the DSA indexer scores and selects by query rows over the ranks -- the prefill op that grows with context runs a run of rows a rank, bit for bit

Every rank scored every query row of a step against every complete block of its sequence and
selected its 512 blocks, the same work eight times: 58 ms of a 1029 ms step at a 4096-row chunk
and 20k of context, about 185 ms at 64k, the largest op that grows with the context. From
GlmTp::kSplitRows each rank now scores one run of the step's rows with dsa_score's row_part,
selects for the rows of its run under the bounds the scorer rebased (cu_part), and two
all_gathers lay the page tables and lengths end to end (8 MiB a layer at 4096 rows). The key
side stays replicated. 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 lose their column split
and 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 the
replicated one and MLA reads it unchanged.

The rule for a run is GlmTp's, stated once: 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, so its runs are multiples of four (DsaCache::part_rows). 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 selection planes hold world runs, which can reach past the step,
and the score plane shrinks to one run, 256 MiB to 32 MiB at 64k of context and a 4096-row
chunk. A decode step splits too once rows x live blocks reach 2^18 from 16 rows
(GlmTp::kSplitWork): eight sequences verifying five drafts from about 22k of context, where
scoring 48 rows over 8000 blocks (250 us on one R9700) outweighs the two eight-rank gathers
(about 50 us); a single sequence's six rows never pay. The replicated issue passes cu_part
absent as its tenth operand, because the engine counts operands against the schema and refused
the nine-operand issue at a served engine's first long prompt.

On eight R9700s (TP8, two ranks on Gen4 x8 that day) a 19887-token prompt prefills 3927 tok/s
against 3748 on 1.9.0, 7881 tokens 3990 against 3655, 2k 3849 against 3663; greedy text with the
adaptive draft window is identical. r4d_emu splits decode rows beside a prefill chunk at 2, 4
and 8 ranks and joins the runs as the gather does, byte for byte against the unsplit scorer;
glm5next_test declares the split at 2 and 8 ranks with the lint, holds the row rule to the
formula it replaced at every world, and pins the graph and steps (world 1
0xed3fc26c486ea1b5 / 0x33e5f136f0dbba15, world 8 0x712f01858dbe1047 / 0xf9e357b1333c638f).
dsa_score_fp8's selftest passes 62 of 62 on eight cards, and --perfdsa times the indexer whole
and as one rank's run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
NunzeandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-21 15:24:05 +02:00
1 parent 66812280bb
commit 1ad675e10c
5 files changed
+474 -58

No files matched your search

+137 -22
View File
@@ -5,9 +5,13 @@
* gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to
* the MLA.
*
* Under tensor parallelism the indexer is replicated whole: every rank pools into the whole index
* cache, scores every query row against it and selects for every row. Only the head gates' f32
* projection splits its columns from GlmTp::kSplitRows (SplitF32Proj). */
* Under tensor parallelism the key side stays replicated (every rank pools into the whole index
* cache and scores against it), but from GlmTp::kSplitRows rows, or a smaller step whose rows x
* live blocks reach GlmTp::kSplitWork, each rank scores and selects for its own run of query rows
* (GlmTp::run_of) and two all_gathers join the runs' page tables and lengths: every row's
* selection is computed by the same kernels from the same operands as on one rank, so the joined
* table is the replicated one's bits. The query side (projection, head gates, quantiser) then runs
* on this rank's run of rows only, since no other rank reads them. */
#ifndef RAD_BLOCK_GLM_INDEXER_H
#define RAD_BLOCK_GLM_INDEXER_H
#include "rad_fp8.h"
@@ -23,7 +27,16 @@ struct DsaCache {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
};
/* The narrower of the two gathered rows, one i32 length a query row (the page table's 513 a
* row is a multiple of it), so a run is whole 16-byte words of both: a multiple of four rows.
* The query and output planes hold world times this. */
static constexpr int64_t kGatherRowBytes = 4;
static int64_t part_rows(int64_t rows, int world) {
return GlmTp::run_rows(rows, world, kGatherRowBytes);
}
Geom g{};
Config c{};
Wire w{};
@@ -31,6 +44,7 @@ struct DsaCache {
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group,
@@ -102,6 +116,19 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score });
const bool split = g.world > 1;
const int64_t part = split ? part_rows(g.max_tok, g.world) : 0;
if (split && (!w.cu_part || !w.sel_part || !w.len_part)) return RAD_E_INVAL;
if (split)
op_score_part =
rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3"),
RAD_INT("row_part", g.rank)),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score, w.cu_part });
op_select = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks),
@@ -109,8 +136,66 @@ struct DsaCache {
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc, w.cu_part }, { w.sel_part, w.nsel, w.len_part });
op_gather_sel = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4 * 513, part * 513),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.sel_part }, { w.selected });
op_gather_len = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4, part),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.len_part }, { w.length });
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
return RAD_E_INVAL;
}
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
}
/* The columns a step scores: the live reach the batch bounds on the host. */
int64_t live_blocks(const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
int64_t live = ((int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + 4) / 4 + 1;
if (live > c.blocks) live = c.blocks;
// T is the total across sequences, so the conservative bound can exceed the
// per-sequence page table. Columns without a table entry cannot be scored.
if (ib && live > ib->block_table_pitch) live = ib->block_table_pitch;
return live < 1 ? 1 : live;
}
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
* the core), so every rank takes the same path and a recorded decode pass changes it only when
* that bound moves. */
bool splits(const RadBatch* batch) const {
const int64_t T = batch->n_tok;
return op_score_part && (GlmTp::splits(T, g.world) ||
(T >= GlmTp::kSplitWorkRows &&
T * live_blocks(batch) >= GlmTp::kSplitWork));
}
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
* projections into `query` and `gate` cover the same rows. */
void query_rows(const RadBatch* batch, int64_t* r0, int64_t* rows) const {
const int64_t T = batch->n_tok;
*r0 = 0;
*rows = T;
if (!splits(batch)) return;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kGatherRowBytes);
*r0 = run.first;
*rows = run.rows;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
const auto* tb = kv_batch(batch, tail);
@@ -122,8 +207,11 @@ struct DsaCache {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32),
brows(w.scales, T * 32));
int64_t q0 = 0, qn = T;
query_rows(batch, &q0, &qn);
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
brow_slice(w.codes, q0 * 32, qn * 32, 128),
brow_slice(w.scales, q0 * 32, qn * 32, 1));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
@@ -136,22 +224,45 @@ struct DsaCache {
RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch));
int64_t live = ((int64_t)batch->max_ctx_len + T + batch->n_spec + 4) / 4 + 1;
if (live > c.blocks) live = c.blocks;
// T is the total across sequences, so the conservative bound can exceed the
// per-sequence page table. Columns without a table entry cannot be scored.
if (live > ib->block_table_pitch) live = ib->block_table_pitch;
if (live < 1) live = 1;
const int64_t live = live_blocks(batch);
if (splits(batch)) {
step_split(ctx, batch, live);
return;
}
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, T));
bcol_at(w.score, 0, c.blocks, 0, live, T), RAD_NONE);
RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.selected, T), brows(w.nsel, T), brows(w.length, T));
}
/* Rank r scores rows [r R, r R + R) (rows past the step score -inf) and selects for those
* that exist (query_rows), against the bounds the scorer rebased to its first row. The
* gathers lay the runs end to end, so rows past the step land past T, where nothing reads
* them. */
void step_split(RadCtx* ctx, const RadBatch* batch, int64_t live) const {
const auto* ib = kv_batch(batch, index);
const auto* ab = kv_batch(batch, attention);
const int64_t T = batch->n_tok, S = batch->n_seq, W = g.world;
const int64_t R = part_rows(T, g.world);
int64_t p0 = 0, rows = 0;
query_rows(batch, &p0, &rows);
RAD_ISSUE_N(ctx, op_score_part, R, brows(w.codes, W * R * 32),
brows(w.scales, W * R * 32), brows(w.gate, W * R), kv_cache(index, layer),
RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, R), brows(w.cu_part, S + 1));
RAD_ISSUE_N(ctx, op_select_part, rows, bcol_at(w.score, 0, c.blocks, 0, live, rows),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions + p0, RAD_I32, rows), brows(w.cu_part, S + 1),
brows(w.sel_part, rows), brows(w.nsel, rows), brows(w.len_part, rows));
RAD_ISSUE_N(ctx, op_gather_sel, R * 513, brows(w.sel_part, R), brows(w.selected, W * R));
RAD_ISSUE_N(ctx, op_gather_len, R, brows(w.len_part, R), brows(w.length, W * R));
}
};
struct GlmIndexer {
@@ -165,7 +276,6 @@ struct GlmIndexer {
DsaCache cache{};
rad_weight gain = 0, bias = 0, head_weight = 0;
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
SplitF32Proj head_split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention,
rad_kvgroup tail, rad_kvgroup* index) {
@@ -222,8 +332,6 @@ struct GlmIndexer {
RAD_INT("K", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(head_weight)),
{ w.input }, { w.cache.gate });
RAD_ARCH_TRY(head_split.declare(b, nm, g, nm.f("blk.%d.index_head", l), g.max_tok, 32, 4096,
head_weight, w.input, w.cache.gate));
RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index,
nm.ckpt("%s.index_kpool_compress_ape", prefix)));
return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL;
@@ -235,18 +343,25 @@ struct GlmIndexer {
a.x = x;
return a;
};
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, T * 32, brows(w.q_wide, T), brows(w.cache.query, T * 32));
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* Every output row of these ops is independent of the others and of how many there are,
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
* configuration may set: it stays on the step's rows unless every run is wider. */
const bool runs = cache.splits(batch);
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
else
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
if (head_split.takes(T))
head_split.step(ctx, T, brows(w.input, T), head_weight, brows(w.cache.gate, T));
else
RAD_ISSUE_N(ctx, op_head, T, brows(w.input, T), RAD_W(head_weight),
brows(w.cache.gate, T));
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
brow_slice(w.cache.gate, r0, rows, 32));
cache.step(ctx, batch);
}
};
+51 -9
View File
@@ -1,18 +1,26 @@
/* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step
* size a replicated piece of work splits over the ranks instead, and the column split of a
* replicated F32 projection.
* size a replicated or head-split piece of work splits over the ranks instead, how a step's rows
* fall into one run a rank, and the column split of a replicated F32 projection.
*
* The residual stream is replicated (spec.md §9). Two kinds of split share the ranks' work:
* The residual stream is replicated (spec.md §9). Three kinds of split share the ranks' work:
*
* heads the MLA and KDA heads, with them the rows of their projections, the KDA state and
* the convolution history; the experts' and the dense feed-forward's width
* (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce
* columns a replicated F32 projection's output columns (SplitF32Proj), or the mHC read's
* input chunks (ManifoldConn); joined by an all_gather, bit for bit the replicated
* computation */
* rows a prefill-sized step's rows, one run a rank, each rank computing its run with the
* unsplit kernels (`run_rows`, `run_of`); joined by an all_gather of whole runs
* columns a replicated F32 projection's output columns (SplitF32Proj); joined by a
* 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`). */
#ifndef RAD_GLM_TP_H
#define RAD_GLM_TP_H
#include "rad_arch.h"
#include <algorithm>
#include <numeric>
namespace rad {
namespace arch {
@@ -28,10 +36,44 @@ struct GlmTp {
static int64_t expert_width(int world) { return kExpertFF / world; }
static int64_t dense_width(int world) { return kDenseFF / world; }
/* Rows from which a replicated piece of work splits over the ranks. Below it, as in decode,
* the collective's latency outweighs the saved arithmetic and every rank runs the replicated
* form. */
/* Rows from which a step splits by rows or columns over the ranks. Below it, as in decode, the
* collective's latency outweighs the saved arithmetic and every rank runs the replicated or
* head-split form. */
static constexpr int64_t kSplitRows = 256;
/* Rows x live blocks from which the indexer splits a smaller step as well: a decode step at
* long context, where scoring every query row against every block of its sequence outweighs
* the two gathers. On one R9700 48 rows over 8000 blocks (32k of context) score and select in
* about 250 us and a run of 8 in 50, against roughly 50 us for the two eight-rank gathers;
* over 4000 blocks the saving is about the gathers' cost, and six rows never pay. From 16
* rows, so that at least four ranks share the work and every run fits in the step. */
static constexpr int64_t kSplitWork = 1 << 18, kSplitWorkRows = 16;
static bool splits(int64_t rows, int world) { return world > 1 && rows >= kSplitRows; }
/* A rank's run of a step of `rows`, gathered as rows of `row_bytes`: ceil(rows / world) rounded
* up to whole 16-byte words of the gathered row. Every rank but possibly the last takes a whole
* run; the planes a split writes hold world runs, which can reach past the step. */
static int64_t run_rows(int64_t rows, int world, int64_t row_bytes) {
const int64_t word = 16 / std::gcd<int64_t>(16, row_bytes);
return word * ((rows + word * world - 1) / (word * world));
}
struct Run {
int64_t run = 0, first = 0, rows = 0;
};
/* Rank `rank`'s rows [first, first + rows) of a step of `rows`. A rank whose run lies wholly
* past a small step takes the step's first run instead, so every plane it computes from and
* gathers is written; what it computes there is dead rows past the step, and the gather lays
* them past T, where nothing reads them. */
static Run run_of(int64_t rows, int world, int rank, int64_t row_bytes) {
Run r;
r.run = run_rows(rows, world, row_bytes);
r.first = rank * r.run;
r.rows = std::min(r.run, rows - r.first);
if (r.rows <= 0) {
r.first = 0;
r.rows = r.run;
}
return r;
}
/* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact)
* and each head-split block's (the deployment's wire). */
+22 -8
View File
@@ -12,7 +12,7 @@
* rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache 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_glm_tp.h GlmTp the shards and the split threshold
* rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds
*
* This file declares the buffers the blocks share, places the blocks and issues the step's
* order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue
@@ -125,7 +125,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. */
/* 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). */
static int mla_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
@@ -147,14 +149,18 @@ static int mla_buffers(RadBuilder* b, Model& m) {
aw.attn.x = bf("expanded", Q);
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q));
aw.core.out = aw.attn.x;
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 });
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T });
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
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 });
return RAD_OK;
}
static int indexer_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1;
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
@@ -166,9 +172,9 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
iw.kg_raw = bf("index_key_gate", 256);
auto& c = iw.cache;
c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 });
c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 });
c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 });
c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 });
c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { TQ * 32, 128 });
c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { TQ * 32, 1 });
c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { TQ, 32 });
c.kg = bf("index_normalized_key_gate", 256);
c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 });
c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work });
@@ -176,10 +182,18 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs });
c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 });
c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 });
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks });
/* A split step scores one run of rows a rank and an unsplit one is under GlmTp::kSplitRows:
* at 64k of context the whole step's plane would be 256 MiB. */
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
c.selected = m.aw.core.selected;
c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
if (g.world > 1) {
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
c.len_part = decl_b(b, nm.f("length_part"), RAD_I32, { part });
}
return RAD_OK;
}
static int ffn_buffers(RadBuilder* b, Model& m) {
+34 -7
View File
@@ -519,9 +519,18 @@ layer's latent, index and tail for every row and runs its MoE on the proposal ro
**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, each issue's operand count
against the loaded kernel libraries' schemas, and every declared weight against the served
container's names and encodings.
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.
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.
- 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
@@ -530,15 +539,33 @@ container's names and encodings.
of o. q_a, kv_a and the latent are replicated.
- 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 is replicated whole.
- 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.
- 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
(`GlmTp::kSplitRows`; `SplitF32Proj` in `arch/common/rad_glm_tp.h`), each rank computes a disjoint part
with the replicated kernel and an `all_gather` joins the parts, so every value is
bit-identical: the router and the head gates split their output columns, the mHC projection
its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes
on every rank. Below the threshold, as in decode, the collective costs more than it saves.
bit-identical: the router splits its output columns, the mHC projection its 16384-wide input
into eight 2048-column chunks, whose partials `mhc_pre_finish` completes on every rank, and the
head gates go with the indexer's rows (above). Below the threshold, as in decode, the
collective costs more than it saves.
**MoE decode fusions.** Three, each byte-identical to the launches it replaces, declared
wherever a loaded library serves the fused op (the separate launches otherwise):
+230 -12
View File
@@ -433,8 +433,9 @@ 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 and 12 index heads (MTP included), and the 90 mHC reads.
CHECK_EQ(count_op(b, "all_gather"), split ? 55 + 90 : 0);
// 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);
CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0);
ctx.issues.clear();
batch.draft_pass = -1;
@@ -480,12 +481,13 @@ TEST(
glm5next::step(&ctx, &batch);
CHECK(ctx.step_fail.empty());
{
// 512 rows reach the split: each projection runs on its column slice and each
// mHC read on its chunks, both gathered; at TP1 nothing changes.
// 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.
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 ? 53 + 90 : 0);
world > 1 ? 42 + 90 + 22 : 0);
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"),
@@ -493,12 +495,14 @@ TEST(
for (const auto& issue : ctx.issues) {
if (b.ops[issue.op - 1].op != "gemm_nt_f32") continue;
const int64_t n = pint(&b.ops[issue.op - 1], "N");
if (world == 1)
if (world == 1 || n == 32)
CHECK(n == 288 || n == 32);
else {
CHECK(n == 288 / world || n == 32 / world);
CHECK_EQ(n, 288 / world);
CHECK_EQ(issue.opd[1].rows, n);
}
if (world > 1 && n == 32)
CHECK_EQ(issue.opd[0].rows, DsaCache::part_rows(512, world));
}
}
for (int l = 3; l < 45; ++l) {
@@ -547,6 +551,177 @@ TEST(
}
}
/* 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
* into planes that hold every run. The query side (projection, cast, quantiser, head gates) runs
* on the run's rows that exist. Below the threshold the indexer stays replicated. */
TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
using namespace rad::arch;
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
"index_topk" };
const char* vals[] = { "1", "4", "288", "2048" };
RadModelMeta meta{};
meta.n_layers = 45;
meta.n_embd = 4096;
meta.n_vocab = 154880;
meta.rms_eps = 1e-5f;
meta.n_kv = 4;
meta.kv_key = keys;
meta.kv_val = vals;
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
for (int world : { 2, 8 })
for (int rank : { 0, world - 1 }) {
RadBuilder b;
b.kv_block = 4;
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
{ "mtp.blk.45.ffn_down_exps", fp8 },
{ "ffn_gate_up_exps", mx },
{ "ffn_down_exps", mx },
{ "ffn_gate_up_shexp", mx },
{ "ffn_down_shexp", mx },
{ "ffn_gate_up.weight", fp8 },
{ "ffn_down.weight", fp8 } };
RadBuildCtx build{};
build.rank = rank;
build.world_size = world;
build.max_tok = 512;
build.max_seqs = 8;
build.max_ctx = 65536;
build.max_spec = 5;
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
const auto& m = *glm5next::models[rank];
const auto& cache = m.layers[3].index.cache;
const auto& w = m.iw.cache;
const int64_t most = DsaCache::part_rows(512, world);
const RecOp* score = b.op_of(cache.op_score_part);
const RecOp* sel = b.op_of(cache.op_gather_sel);
const RecOp* len = b.op_of(cache.op_gather_len);
REQUIRE(score && sel && len && cache.op_select_part);
CHECK_EQ(pint(score, "row_part"), rank);
CHECK_EQ(param(score, "M")->ihi, most);
CHECK(score->writes == std::vector<rad_buf>({ w.score, w.cu_part }));
CHECK_EQ(param(sel, "numel")->ival, 4 * 513);
CHECK_EQ(param(sel, "numel")->ihi, most * 513);
CHECK_EQ(param(len, "numel")->ihi, most);
CHECK(sel->reads == std::vector<rad_buf>({ w.sel_part }));
CHECK(sel->writes == std::vector<rad_buf>({ w.selected }));
CHECK(len->writes == std::vector<rad_buf>({ w.length }));
CHECK_EQ(b.bufs[w.selected - 1].d.shape[0], world * most);
CHECK_EQ(b.bufs[w.codes - 1].d.shape[0], world * most * 32);
CHECK_EQ(b.bufs[w.sel_part - 1].d.shape[0], most);
// Two decode rows beside a 498-row chunk: 500 rows, runs of R.
auto k = kit(b, { 1, 1 }, { 498 }, 100);
const int64_t T = 500, R = DsaCache::part_rows(T, world), r0 = rank * R,
have = std::min(R, T - r0);
auto passes = run_passes(b, glm5next::step, { k.get() }, rank, world);
CHECK_PASSES(b, passes);
const auto& index = m.layers[3].index;
// The bf16 query projection follows the runs only where every run is over 64 rows.
const bool projected = T - (world - 1) * R > 64;
int scored = 0, selected = 0, gathered = 0, replicated = 0, fronts = 0;
for (const auto& issue : passes[0]->issues) {
if (issue.op == index.query.op) {
++fronts;
CHECK_EQ(issue.opd[0].rows, projected ? have : T);
CHECK_EQ(issue.opd[0].offset, projected ? r0 * 1536 : 0);
}
if (issue.op == index.op_query_copy || issue.op == cache.op_query) {
++fronts;
CHECK_EQ(issue.n, have * 32);
CHECK_EQ(issue.opd[1].offset, r0 * 32 * 128);
}
if (issue.op == index.op_head) {
++fronts;
CHECK_EQ(issue.n, have);
CHECK_EQ(issue.opd[0].offset, r0 * 4096);
CHECK_EQ(issue.opd[2].offset, r0 * 32);
}
if (issue.op == cache.op_score) ++replicated;
if (issue.op == cache.op_score_part) {
++scored;
CHECK_EQ(issue.n, R);
CHECK_EQ(issue.opd[0].rows, world * R * 32);
CHECK_EQ(issue.opd[2].rows, world * R);
CHECK_EQ(issue.opd[8].rows, R);
CHECK_EQ(issue.opd[9].handle, w.cu_part);
}
if (issue.op == cache.op_select_part) {
++selected;
CHECK_EQ(issue.n, have);
CHECK(issue.opd[3].raw == (void*)(k->pos.data() + r0));
CHECK_EQ(issue.opd[3].rows, have);
CHECK_EQ(issue.opd[4].handle, w.cu_part);
CHECK_EQ(issue.opd[5].handle, w.sel_part);
CHECK_EQ(issue.opd[7].handle, w.len_part);
}
if (issue.op == cache.op_gather_sel) {
++gathered;
CHECK_EQ(issue.n, R * 513);
CHECK_EQ(issue.opd[1].rows, world * R);
}
if (issue.op == cache.op_gather_len) CHECK_EQ(issue.n, R);
}
// The handles are layer 3's: one issue each.
CHECK_EQ(scored, 1);
CHECK_EQ(selected, have > 0 ? 1 : 0);
CHECK_EQ(gathered, 1);
CHECK_EQ(replicated, 0);
CHECK_EQ(fronts, 4);
// Under the threshold every rank scores and selects the whole step.
auto small = kit(b, {}, { 255 });
auto under = run_passes(b, glm5next::step, { small.get() }, rank, world);
CHECK_PASSES(b, under);
int whole = 0;
for (const auto& issue : under[0]->issues) {
CHECK(issue.op != cache.op_score_part && issue.op != cache.op_gather_sel);
whole += issue.op == cache.op_score;
// The engine refuses an issue whose operand count is not the schema's: dsa_score
// declares ten (cu_part optional, passed absent).
if (issue.op == cache.op_score || issue.op == cache.op_score_part)
CHECK_EQ(issue.opd.size(), (size_t)10);
if (issue.op == index.op_head) CHECK_EQ(issue.n, 255);
}
CHECK_EQ(whole, 1);
// A verify of eight sequences at 32k of context (48 rows x 8014 blocks) splits too, a
// single sequence's six rows do not; a rank whose run lies past the step still writes
// the runs it gathers.
for (int seqs : { 8, 1 }) {
auto dec = kit(b, std::vector<int>((size_t)seqs, 6), {});
const int64_t pitch = 8192;
dec->table.resize((size_t)(seqs * pitch));
for (int64_t i = 0; i < seqs * pitch; ++i) dec->table[(size_t)i] = (int32_t)i;
for (auto& g : dec->kv) {
g.block_table = dec->table.data();
g.block_table_pitch = g.max_blocks = pitch;
}
dec->b.max_ctx_len = 32000;
auto v = run_passes(b, glm5next::step, { dec.get() }, rank, world);
CHECK_PASSES(b, v);
const int64_t Td = 6 * seqs, Rd = DsaCache::part_rows(Td, world);
const bool split_d = seqs == 8;
int parts = 0, gathers = 0, wholes = 0;
for (const auto& issue : v[0]->issues) {
parts += issue.op == cache.op_score_part;
gathers += issue.op == cache.op_gather_sel;
wholes += issue.op == cache.op_score;
if (issue.op == cache.op_score_part) CHECK_EQ(issue.n, Rd);
if (issue.op == cache.op_score || issue.op == cache.op_score_part)
CHECK_EQ(issue.opd.size(), (size_t)10);
if (split_d &&
(issue.op == cache.op_select_part || issue.op == cache.op_query)) {
const int64_t rows_d = rank * Rd < Td ? std::min(Rd, Td - rank * Rd) : Rd;
CHECK_EQ(issue.n, issue.op == cache.op_query ? rows_d * 32 : rows_d);
}
}
CHECK_EQ(gathers, split_d ? 1 : 0);
CHECK_EQ(parts, split_d ? 1 : 0);
CHECK_EQ(wholes, split_d ? 0 : 1);
}
}
}
/* 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
@@ -1176,8 +1351,8 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
int world;
uint64_t graph, steps;
};
const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull },
{ 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } };
const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x33e5f136f0dbba15ull },
{ 8, 0x712f01858dbe1047ull, 0xf9e357b1333c638full } };
for (const Case& cs : cases) {
RadBuilder b;
b.kv_block = 4;
@@ -1248,6 +1423,48 @@ RadBuildCtx glm53_ctx(int rank, int world, int max_spec = 3) {
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) {
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 }) {
const int64_t wide = GlmTp::run_rows(T, world, 8192);
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(DsaCache::part_rows(T, world), narrow);
CHECK(world * wide >= T);
CHECK(world * narrow >= T);
CHECK_EQ(narrow % 4, 0);
for (int64_t row_bytes : { 8192, 4 }) {
const int64_t run = GlmTp::run_rows(T, world, row_bytes);
int64_t covered = 0, next = 0;
for (int rank = 0; rank < world; ++rank) {
const GlmTp::Run r = GlmTp::run_of(T, world, rank, row_bytes);
CHECK_EQ(r.run, run);
CHECK(r.rows >= 1 && r.rows <= run);
if ((int64_t)rank * run < T) {
CHECK_EQ(r.first, next);
CHECK_EQ(r.rows, std::min(run, T - r.first));
next = r.first + r.rows;
covered += r.rows;
} else {
CHECK_EQ(r.first, 0);
CHECK_EQ(r.rows, run);
}
}
CHECK_EQ(covered, T);
}
}
}
/* ==================================================================== the op schemas */
namespace {
@@ -1305,9 +1522,10 @@ const LoadedSchemas& loaded_schemas() {
* declares names as many weights as rad_builder.cpp admits. The steps: at eight ranks and at
* one, a mixed step over the split threshold (two decode rows beside a 498-row chunk), a step
* under it, a six-row verify and six single-row decodes, each with its history pass and a draft
* round, and a verify of eight sequences at 32k of context. The engine refuses a step at the
* first mismatch, and the fakes alone cannot see one: an issue short of an optional operand
* passes every host test and stops a served engine at its first step through that op. */
* round, and a verify of eight sequences at 32k of context, where the indexer splits a decode.
* The engine refuses a step at the first mismatch, and the fakes alone cannot see one: a
* replicated dsa_score issued with nine operands passed every host test and stopped a served
* engine at its first long prompt. */
TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) {
const LoadedSchemas& lib = loaded_schemas();
if (lib.ops.empty()) {