From fa4a7a75a44905c52acab6b008b675f3306a291c Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:10 +0200 Subject: [PATCH] glm5next: the plugin over its blocks, one a file, and rad_glm_tp.h for the shards and the split threshold -- the same graph, read in order The plugin carried the draft head's buffers, weights and ops in its declare and its draft pass in its step, with the three ops that join the head to its layer declared inside the layer function; each GLM block carried its core in a header of its own (rad_block_mla_latent.h, rad_block_kda_state.h, rad_block_dsa_cache.h), the split threshold sat in rad_tp_split.h beside the router's column split, and 64 / world, 8192 / world, 2048 / world were spelled across the plugin and the blocks. tests/arch_test.cpp held the recording builder, the run-phase fakes, the step lint, the batch kits and the fingerprints beside every architecture's cases, 9.5k lines in one translation unit, GLM-5.3's among them. Now one block a file in arch/common: rad_block_glm_{mhc,kda,mla,indexer,router,mtp}.h, the cores joined to their blocks, and GlmMtp the draft head in three parts (inputs, join, head), declared and stepped around the plugin's layer 45. rad_glm_tp.h (GlmTp) holds the widths a rank's shard divides, the one threshold kSplitRows and the replicated all_reduce declared once; SplitF32Proj moves over unchanged. The plugin reads as the stream's buffers, then each block's, the KV groups, the layers, the head and the draft head. tests/arch_fakes.h holds the fakes and the helpers every architecture test needs, included by one translation unit a binary (neither binary links rad_core, as before); GLM-5.3's cases are tests/glm5next_test.cpp, which includes only its plugin, with two cases new: every op the plugin issues carries the operand count its schema declares (the kernel libraries' schemas under $RADIANCE_HOME/kernels, counted as core/runtime/issue.cpp counts), and every declared weight reads an entry the served container holds, at the dtype its stored encoding calls for (the container's names and encodings as rad-info -v lists them). Every declared name, declaration order and issue order is as it was: the pinned graph and step hashes at one and eight ranks are the values arch_test pinned before the move (world 1 0xed3fc26c486ea1b5 / 0x98ba2952bb37b075, world 8 0x8204e073efdeee0c / 0x1279aecfe4e32d9a), and arch_test's pins of the other architectures are unchanged. Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_dsa_cache.h | 150 -- arch/common/rad_block_glm_indexer.h | 154 +- arch/common/rad_block_glm_kda.h | 148 +- .../{rad_block_mhc.h => rad_block_glm_mhc.h} | 16 +- arch/common/rad_block_glm_mla.h | 110 +- arch/common/rad_block_glm_mtp.h | 187 ++ arch/common/rad_block_glm_router.h | 2 +- arch/common/rad_block_kda_state.h | 128 - arch/common/rad_block_mla_latent.h | 84 - arch/common/rad_glm_tp.h | 103 + arch/common/rad_tp_split.h | 65 - arch/glm5next/glm5next.cpp | 527 ++-- docs/ARCHITECTURES.md | 25 +- tests/CMakeLists.txt | 22 +- tests/arch_fakes.h | 1177 +++++++++ tests/arch_test.cpp | 2347 +---------------- tests/glm5next_test.cpp | 1628 ++++++++++++ 17 files changed, 3768 insertions(+), 3105 deletions(-) delete mode 100644 arch/common/rad_block_dsa_cache.h rename arch/common/{rad_block_mhc.h => rad_block_glm_mhc.h} (93%) create mode 100644 arch/common/rad_block_glm_mtp.h delete mode 100644 arch/common/rad_block_kda_state.h delete mode 100644 arch/common/rad_block_mla_latent.h create mode 100644 arch/common/rad_glm_tp.h delete mode 100644 arch/common/rad_tp_split.h create mode 100644 tests/arch_fakes.h create mode 100644 tests/glm5next_test.cpp diff --git a/arch/common/rad_block_dsa_cache.h b/arch/common/rad_block_dsa_cache.h deleted file mode 100644 index 52cc782a..00000000 --- a/arch/common/rad_block_dsa_cache.h +++ /dev/null @@ -1,150 +0,0 @@ -/* GLM's stateful compressed-index core. The caller supplies projected queries, - * signed F32 head gates, and [LayerNorm(key), pool_gate] BF16 rows. No RoPE. - * Query projections are replicated across TP ranks; selected pages belong to MLA. */ -#ifndef RAD_BLOCK_DSA_CACHE_H -#define RAD_BLOCK_DSA_CACHE_H -#include "rad_arch.h" - -namespace rad { -namespace arch { -struct DsaCache { - struct Config { - int64_t blocks = 0, work = 0, ring = 0, topk = 512; - }; - struct Wire { - 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; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - 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; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, - const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, - rad_kvgroup* index_group, const char* ape_source) { - g = geom; - c = cfg; - w = wire; - layer = l; - attention = attn; - tail = tail_group; - if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 || - c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 || - !w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page || - !w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel || - !w.length) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail)); - const char* name = nm.f("blk.%d.index_ape", l); - RAD_ARCH_TRY(map_copy(b, name, ape_source)); - ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, - grp_layer(l)); - if (!ape) return RAD_E_INVAL; - // Query buffers are [tokens*32,128]; scoring uses their rank-three view. - op_query = rw(b, - RAD_OP(b, "dsa_query", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.query }, { w.codes, w.scales }); - op_work = rw( - b, - RAD_OP(b, "qsa_work", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4), - RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs), - RAD_INT("work", c.work), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.kg }, { w.stage, w.page, w.bpos, w.nc }); - // Declare immediately before the cache consumer: page size comes from that op. - if (!*index_group) { - RadKVGroupDecl d{}; - d.kind = RAD_KV_FULL; - d.dtype = RAD_U8; - d.n_head_kv = 1; - d.head_dim = 17; - *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); - } - index = *index_group; - if (!index) return RAD_E_INVAL; - op_pool = - rw(b, - RAD_OP(b, "dsa_pool", - RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4), - RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(ape)), - { w.stage, w.page }, { w.pooled, w.pool_scale }); - if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index)); - op_tail = rw(b, - RAD_OP(b, "qsa_tail_store", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), - RAD_INT("ratio", 4), RAD_INT("ring", c.ring), - RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.kg }, {}); - op_score = rw(b, - RAD_OP(b, "dsa_score", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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_NOWEIGHTS), - { w.codes, w.scales, w.gate, w.nc }, { w.score }); - op_select = rw(b, - RAD_OP(b, "qsa_select", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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.selected, w.nsel, w.length }); - return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, const RadBatch* batch) const { - const auto* ib = kv_batch(batch, index); - const auto* tb = kv_batch(batch, tail); - const auto* ab = kv_batch(batch, attention); - if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) { - rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices"); - return; - } - 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)); - 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), - praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE, - brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work), - brows(w.nc, S)); - RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work), - brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer)); - // Gather before overwriting the tail; the wider ring preserves rejected-token rollback. - 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; - 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)); - 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)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_block_glm_indexer.h b/arch/common/rad_block_glm_indexer.h index 59d81696..18ed8c56 100644 --- a/arch/common/rad_block_glm_indexer.h +++ b/arch/common/rad_block_glm_indexer.h @@ -1,13 +1,159 @@ -/* Replicated GLM indexer front end. Casts bridge ordinary linear rows to the - * flattened per-head quantizer and join normalized keys with learned pool gates. */ +/* GLM-5.3's DSA indexer: the stateful compressed-index core over its paged key cache (DsaCache), + * which scores every complete block of a sequence's history against each query and selects the + * 512 the MLA attends to, and the front end around it (GlmIndexer), whose casts bridge ordinary + * linear rows to the flattened per-head quantiser and join normalized keys with learned pool + * 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). */ #ifndef RAD_BLOCK_GLM_INDEXER_H #define RAD_BLOCK_GLM_INDEXER_H #include "rad_fp8.h" -#include "rad_block_dsa_cache.h" -#include "rad_tp_split.h" +#include "rad_glm_tp.h" namespace rad { namespace arch { +struct DsaCache { + struct Config { + int64_t blocks = 0, work = 0, ring = 0, topk = 512; + }; + struct Wire { + 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; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + 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; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, + const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, + rad_kvgroup* index_group, const char* ape_source) { + g = geom; + c = cfg; + w = wire; + layer = l; + attention = attn; + tail = tail_group; + if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 || + c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 || + !w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page || + !w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel || + !w.length) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail)); + const char* name = nm.f("blk.%d.index_ape", l); + RAD_ARCH_TRY(map_copy(b, name, ape_source)); + ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(l)); + if (!ape) return RAD_E_INVAL; + // Query buffers are [tokens*32,128]; scoring uses their rank-three view. + op_query = rw(b, + RAD_OP(b, "dsa_query", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.query }, { w.codes, w.scales }); + op_work = rw( + b, + RAD_OP(b, "qsa_work", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4), + RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs), + RAD_INT("work", c.work), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, { w.stage, w.page, w.bpos, w.nc }); + // Declare immediately before the cache consumer: page size comes from that op. + if (!*index_group) { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_U8; + d.n_head_kv = 1; + d.head_dim = 17; + *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); + } + index = *index_group; + if (!index) return RAD_E_INVAL; + op_pool = + rw(b, + RAD_OP(b, "dsa_pool", + RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4), + RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(ape)), + { w.stage, w.page }, { w.pooled, w.pool_scale }); + if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index)); + op_tail = rw(b, + RAD_OP(b, "qsa_tail_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), + RAD_INT("ratio", 4), RAD_INT("ring", c.ring), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, {}); + op_score = rw(b, + RAD_OP(b, "dsa_score", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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_NOWEIGHTS), + { w.codes, w.scales, w.gate, w.nc }, { w.score }); + op_select = rw(b, + RAD_OP(b, "qsa_select", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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.selected, w.nsel, w.length }); + return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto* ib = kv_batch(batch, index); + const auto* tb = kv_batch(batch, tail); + const auto* ab = kv_batch(batch, attention); + if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) { + rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices"); + return; + } + 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)); + 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), + praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE, + brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work), + brows(w.nc, S)); + RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work), + brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer)); + // Gather before overwriting the tail; the wider ring preserves rejected-token rollback. + 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; + 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)); + 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)); + } +}; + struct GlmIndexer { struct Wire { rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0; diff --git a/arch/common/rad_block_glm_kda.h b/arch/common/rad_block_glm_kda.h index 6617ae0f..ab8b4e61 100644 --- a/arch/common/rad_block_glm_kda.h +++ b/arch/common/rad_block_glm_kda.h @@ -1,13 +1,137 @@ -/* GLM KDA projections around the recurrent/cache core. These checkpoint weights - * are BF16. The two low-rank gate paths have no intervening activation. The - * caller supplies normalized input and owns the mHC residual connection. */ +/* GLM-5.3's KDA layer: the seven bf16 projections around the recurrent core (GlmKda), and the + * core itself over already projected inputs (KdaState), whose ple_conv supplies exactly causal + * depthwise convolution + SiLU, cold start and accepted-history rollback included. The two + * low-rank gate paths have no intervening activation. The caller supplies the normalized input + * and owns the mHC residual connection. + * + * Under tensor parallelism the heads split (GlmTp::heads), and with them the q/k/v rows, the + * convolution taps, the state and the output projection's columns; the two rank-128 projections + * into the gates are replicated. The block's all_reduce sums the output. */ #ifndef RAD_BLOCK_GLM_KDA_H #define RAD_BLOCK_GLM_KDA_H #include "rad_fp8.h" -#include "rad_block_kda_state.h" +#include "rad_glm_tp.h" +#include namespace rad { namespace arch { +struct KdaState { + struct Config { + int64_t heads = 16, dim = 128, width = 4; + double lower = -5; + }; + struct Src { + const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr, + *bias = nullptr, *norm = nullptr; + }; + struct Wire { + rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup state = 0, history = 0; + rad_weight taps = 0, alog = 0, bias = 0, norm = 0; + rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv, + const Config& cfg, const Wire& wire, const Src& src) { + g = geom; + c = cfg; + w = wire; + layer = l; + state = st; + history = cv; + if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 || + !std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta || + !w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv || + !src.alog || !src.bias || !src.norm) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); + const int64_t width = c.heads * c.dim; + const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l), + *bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l); + RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv })); + RAD_ARCH_TRY(map_copy(b, an, src.alog)); + RAD_ARCH_TRY(map_copy(b, bn, src.bias)); + RAD_ARCH_TRY(map_copy(b, nn, src.norm)); + taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(l), 0, { width, width, width }); + alog = + decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + norm = + decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + if (!taps || !alog || !bias || !norm) return RAD_E_INVAL; + op_conv = rw(b, + RAD_OP(b, "ple_conv", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width), + RAD_INT("width", c.width), RAD_INT("dilation", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(taps)), + { w.qkv }, { w.conv }); + for (int verify = 0; verify < 2; ++verify) { + const rad_op op = rw( + b, + RAD_OP(b, "kda_update", + RAD_PARAMS( + RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim), + RAD_F64("lower_bound", c.lower), + RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)), + RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"), + RAD_STR("dtype", "bf16"), + RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")), + RAD_WEIGHTS(alog, bias)), + { w.conv, w.a, w.beta }, { w.out }); + if (verify) + op_verify = op; + else + op_prefill = op; + } + op_norm = rw(b, + RAD_OP(b, "gdn_gated_rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim), + RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")), + RAD_WEIGHTS(norm)), + { w.out, w.gate }, { w.out }); + return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); + if (!st || !cv || !st->state_index || !cv->state_index) { + rad_step_fail(ctx, "KDA requires recurrent and convolution state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim; + const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; + int64_t D = 0, DT = 0; + batch_split(batch, &D, &DT); + for (int verify = 1; verify >= 0; --verify) { + const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; + if (!seqs) continue; + const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); + const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); + const RadOperand accepted = + verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; + RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps), + kv_cache(history, layer), cu, RAD_NONE, + praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, + brows(w.conv, rows)); + RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows), + bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows), + brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias), + kv_cache(state, layer), + praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, + init, brows(w.out, rows)); + } + RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm), + brows(w.out, T)); + } +}; + struct GlmKda { struct Wire { rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0; @@ -23,14 +147,14 @@ struct GlmKda { rad_kvgroup history, bool reduce = true) { g = geom; w = wire; - if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input || - !w.forget_low || !w.gate_low || !w.out || w.input == w.out || + if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world || + !w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out || w.forget_low == w.gate_low) return RAD_E_INVAL; // All seven projections are plain BF16 in the pinned checkpoint. Geom bg = g; bg.w_bf16 = true; - const int64_t width = 8192 / g.world, heads = 64 / g.world; + const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world); const auto group = grp_layer(layer); auto act = [](rad_buf x) { ActFP8 a{}; @@ -67,15 +191,7 @@ struct GlmKda { if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 || !gate_b.bf16 || !output.bf16) return RAD_E_UNSUPPORTED; - if (reduce && g.world > 1) - op_ar = rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { w.out }, { w.out }); + if (reduce) op_ar = GlmTp::reduce(b, g, w.out); return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; } void step(RadCtx* ctx, const RadBatch* batch) const { diff --git a/arch/common/rad_block_mhc.h b/arch/common/rad_block_glm_mhc.h similarity index 93% rename from arch/common/rad_block_mhc.h rename to arch/common/rad_block_glm_mhc.h index 67b21d15..f65e3bb7 100644 --- a/arch/common/rad_block_mhc.h +++ b/arch/common/rad_block_glm_mhc.h @@ -1,8 +1,10 @@ -/* GLM manifold-constrained residual connections. The mixed residual must have a - * separate destination: each output stream reads every original input stream. */ -#ifndef RAD_BLOCK_MHC_H -#define RAD_BLOCK_MHC_H -#include "rad_tp_split.h" +/* GLM-5.3's manifold-constrained residual connections (mHC): four residual streams in one + * 16384-wide row. read() mixes them down to the block's 4096-wide input and saves the mixing + * coefficients; write() adds the block's output back into every stream. The mixed residual must + * have a separate destination: each output stream reads every original input stream. */ +#ifndef RAD_BLOCK_GLM_MHC_H +#define RAD_BLOCK_GLM_MHC_H +#include "rad_glm_tp.h" #include namespace rad { @@ -27,7 +29,7 @@ struct ManifoldConn { rad_op op_pre = 0, op_post = 0; /* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank * computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them, - * and mhc_pre_finish completes the read on every rank (rad_tp_split.h). */ + * and mhc_pre_finish completes the read on every rank (rad_glm_tp.h). */ static constexpr int64_t kChunk = 2048, kPartStride = 28; rad_buf part = 0, parts = 0; rad_op op_partial = 0, op_gather = 0, op_finish = 0; @@ -72,7 +74,7 @@ struct ManifoldConn { } int declare_split(RadBuilder* b, Names& nm, const char* name) { const int64_t total = c.hc * g.n_embd / kChunk; - split_rows = kGlmTpSplitRows; + split_rows = GlmTp::kSplitRows; if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) { split_rows = 0; return RAD_OK; diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index 1fe2089b..7c54e67d 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -1,12 +1,92 @@ -/* No-RoPE GLM MLA. prepare() exposes normalized Q-lora for the replicated - * indexer; finish() consumes its selection. The caller owns the mHC residual. */ +/* GLM-5.3's sparse latent attention (MLA, no RoPE): the projections and the latent cache store + * around the absorbed core (GlmMla), and the core itself over the latent cache (MlaLatent), whose + * 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. */ #ifndef RAD_BLOCK_GLM_MLA_H #define RAD_BLOCK_GLM_MLA_H #include "rad_fp8.h" -#include "rad_block_mla_latent.h" +#include "rad_glm_tp.h" +#include namespace rad { namespace arch { +struct MlaLatent { + struct Config { + int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; + }; + struct Wire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + rad_weight projection = 0; + rad_op op_absorb = 0, op_attn = 0, op_expand = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + const Config& cfg, const Wire& wire, const char* source) { + g = geom; + c = cfg; + w = wire; + layer = l; + kv = group; + if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent || + !w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent || + w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 || + c.head_dim != 256) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group)); + const char* name = nm.f("blk.%d.attn_kv_b.weight", l); + RAD_ARCH_TRY(map_copy(b, name, source)); + // The conversion recipe decodes this small projection only. + projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + if (!projection) return RAD_E_INVAL; + op_absorb = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.q }, { w.q_latent }); + op_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), + RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks), + RAD_INT("block_size", 4), + RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.q_latent, w.selected, w.length }, { w.attn_latent }); + if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; + op_expand = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.attn_latent }, { w.out }); + return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, int64_t rows) const { + RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection), + brows(w.q_latent, rows)); + RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer), + brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows)); + RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection), + brows(w.out, rows)); + } +}; + struct GlmMla { struct Wire { ActFP8 input{}, q_low{}, attn{}; @@ -30,8 +110,8 @@ struct GlmMla { w = wire; layer = l; kv = group; - if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input.x || - !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x || + if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world || + !w.input.x || !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x || w.attn.x != w.core.out) return RAD_E_INVAL; const auto wg = grp_layer(l); @@ -56,8 +136,8 @@ struct GlmMla { RAD_WEIGHTS(kv_gain)), { w.kv_raw }, { w.latent }); if (!op_kv_norm) return RAD_E_INVAL; - RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), 16384 / g.world, 1536, - RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world), + 1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, w.q_low, w.core.q)); // Cache stores contiguous halves of the normalized latent, with no duplicated K/V. op_store = rw(b, @@ -72,22 +152,14 @@ struct GlmMla { } int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) { MlaLatent::Config cfg; - cfg.heads = 64 / g.world; + cfg.heads = GlmTp::heads(g.world); RAD_ARCH_TRY( core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix))); - RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, 16384 / g.world)); + RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, GlmTp::mla_width(g.world))); RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096, - 16384 / g.world, RAD_SHARD_COL, grp_layer(layer), + GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); - if (reduce && g.world > 1) - op_ar = rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { w.out }, { 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; } void prepare(RadCtx* ctx, const RadBatch* batch) const { diff --git a/arch/common/rad_block_glm_mtp.h b/arch/common/rad_block_glm_mtp.h new file mode 100644 index 00000000..964700f9 --- /dev/null +++ b/arch/common/rad_block_glm_mtp.h @@ -0,0 +1,187 @@ +/* GLM-5.3's draft head: checkpoint layer 45 as a serial drafter (RAD_DRAFT_SERIAL), around the + * one MLA + indexer + MoE layer the plugin declares and steps itself. + * + * h = gather(the trunk's final hidden states, at the rows this pass continues from) + * e = embed(the token one position on) + * x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first + * x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer + * h' = shared_head.norm(x); logits = the trunk's lm_head over h' + * + * h' is both the logits input and the next round's `h`. No mHC: the layer's residual is a plain + * add. By the sign of RadBatch::draft_pass a history pass (< 0) covers every row the trunk step + * had, fills the draft layer's latent, index and tail for all of them and runs the MoE and the + * head on the proposal rows only (draft_out_ids); a draft round (> 1) is one row a sequence. + * + * The block is declared and stepped in three parts around the layer, in this order: `inputs` + * before the layer's attention, `join` (the residual add and the proposal rows' selection) between + * its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's. + * Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj + * (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */ +#ifndef RAD_BLOCK_GLM_MTP_H +#define RAD_BLOCK_GLM_MTP_H +#include "rad_glm_tp.h" + +namespace rad { +namespace arch { +struct GlmMtp { + /* The trunk's: its final hidden states, its logits, its embedding and head. */ + struct Wire { + rad_buf final_hidden = 0, logits = 0; + rad_weight token = 0, head = 0; + }; + static constexpr int kDepth = 3; /* --num-speculative-tokens auto */ + Names nm{ "mtp" }; + Geom g{}; + Wire w{}; + rad_buf x = 0, hidden = 0, embedding = 0, concat = 0, out = 0; + rad_weight en = 0, hn = 0, eh = 0, norm = 0; + rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0; + rad_op op_residual = 0, op_select = 0, op_back = 0; + rad_op op_norm = 0, op_copy = 0, op_head = 0; + + /* The buffers, the weights, and the ops up to the layer's input. */ + int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire) { + g = geom; + w = wire; + if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1) + return RAD_E_INVAL; + x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 }); + hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); + embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); + concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 }); + out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 }); + const char* pre = "model.language_model.layers.45"; + auto gain = [&](const char* n, const char* src) { + const char* name = nm.f("%s", n); + if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; + return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(45)); + }; + en = gain("enorm.weight", "enorm.weight"); + hn = gain("hnorm.weight", "hnorm.weight"); + norm = gain("output_norm.weight", "shared_head.norm.weight"); + RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre))); + eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(45)); + if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh) + return RAD_E_INVAL; + op_prev = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.final_hidden }, { hidden }); + op_embed = rw(b, + RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(w.token)), + {}, { embedding }); + op_embed_ar = GlmTp::reduce(b, g, embedding, true); + op_en = rmsnorm(b, en, embedding, concat); + op_hn = rmsnorm(b, hn, hidden, concat); + op_eh = rw(b, + RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), + RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(eh)), + { concat }, { x }); + return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar) + ? RAD_OK + : RAD_E_INVAL; + } + /* Between the layer's attention and its feed-forward: the residual add of the attention's + * output `y`, and on a history pass the proposal rows gathered to the head of `x`. */ + int declare_join(RadBuilder* b, rad_buf y) { + op_residual = rw(b, + RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x, y }, { x }); + // All history rows fill the draft cache; only proposal rows need its FFN. + op_select = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { hidden }); + op_back = cast(b, hidden, x); + return op_residual && op_select && op_back ? RAD_OK : RAD_E_INVAL; + } + /* After the layer: the head's norm, its output kept as the next round's hidden, the logits, + * and the drafter's declaration. */ + int declare_head(RadBuilder* b) { + op_norm = rmsnorm(b, norm, x, out); + op_copy = cast(b, out, hidden); + op_head = rw(b, + RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.head)), + { hidden }, { w.logits }); + if (!op_norm || !op_copy || !op_head) return RAD_E_INVAL; + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = g.max_spec; + dd.mask_token = -1; + return rad_declare_drafter(b, &dd); + } + + /* The rows a pass runs its feed-forward and head on: the proposal rows of a history pass, + * every row of a draft round. */ + static int64_t head_rows(const RadBatch* batch) { + return batch->draft_pass < 0 ? batch->n_draft_out : batch->n_tok; + } + void step_inputs(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (batch->draft_pass < 0 && batch->n_out > 0) + RAD_ISSUE_N(c, op_prev, batch->n_out, RAD_B(w.final_hidden), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out)); + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token), + brows(embedding, T)); + if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE); + RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T)); + RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T)); + RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T)); + } + void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const { + const int64_t T = batch->n_tok, L = head_rows(batch); + RAD_ISSUE_N(c, op_residual, T, brows(x, T), brows(y, T), brows(x, T)); + if (batch->draft_pass < 0) { + RAD_ISSUE_N(c, op_select, L, RAD_B(x), praw(batch->draft_out_ids, RAD_I32, L), + brows(hidden, L)); + RAD_ISSUE_N(c, op_back, L, brows(hidden, L), brows(x, L)); + } + } + void step_head(RadCtx* c, const RadBatch* batch) const { + const int64_t L = head_rows(batch); + RAD_ISSUE_N(c, op_norm, L, brows(x, L), RAD_W(norm), brows(out, L)); + RAD_ISSUE_N(c, op_copy, L, brows(out, L), brows(hidden, L)); + RAD_ISSUE_N(c, op_head, L, brows(hidden, L), RAD_W(w.head), brows(w.logits, L)); + } + +private: + rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const { + return rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(gain)), + { in }, { out }); + } + rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_router.h b/arch/common/rad_block_glm_router.h index ce48cf2f..a23f901b 100644 --- a/arch/common/rad_block_glm_router.h +++ b/arch/common/rad_block_glm_router.h @@ -2,7 +2,7 @@ * come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */ #ifndef RAD_BLOCK_GLM_ROUTER_H #define RAD_BLOCK_GLM_ROUTER_H -#include "rad_tp_split.h" +#include "rad_glm_tp.h" #include namespace rad { diff --git a/arch/common/rad_block_kda_state.h b/arch/common/rad_block_kda_state.h deleted file mode 100644 index 559245d3..00000000 --- a/arch/common/rad_block_kda_state.h +++ /dev/null @@ -1,128 +0,0 @@ -/* GLM's recurrent core over already projected inputs. ple_conv supplies exactly - * causal depthwise convolution + SiLU, including cold start and accepted-history rollback. */ -#ifndef RAD_BLOCK_KDA_STATE_H -#define RAD_BLOCK_KDA_STATE_H -#include "rad_arch.h" -#include - -namespace rad { -namespace arch { -struct KdaState { - struct Config { - int64_t heads = 16, dim = 128, width = 4; - double lower = -5; - }; - struct Src { - const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr, - *bias = nullptr, *norm = nullptr; - }; - struct Wire { - rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - rad_kvgroup state = 0, history = 0; - rad_weight taps = 0, alog = 0, bias = 0, norm = 0; - rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv, - const Config& cfg, const Wire& wire, const Src& src) { - g = geom; - c = cfg; - w = wire; - layer = l; - state = st; - history = cv; - if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 || - !std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta || - !w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv || - !src.alog || !src.bias || !src.norm) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); - const int64_t width = c.heads * c.dim; - const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l), - *bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l); - RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv })); - RAD_ARCH_TRY(map_copy(b, an, src.alog)); - RAD_ARCH_TRY(map_copy(b, bn, src.bias)); - RAD_ARCH_TRY(map_copy(b, nn, src.norm)); - taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, - grp_layer(l), 0, { width, width, width }); - alog = - decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - norm = - decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); - if (!taps || !alog || !bias || !norm) return RAD_E_INVAL; - op_conv = rw(b, - RAD_OP(b, "ple_conv", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width), - RAD_INT("width", c.width), RAD_INT("dilation", 1), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(taps)), - { w.qkv }, { w.conv }); - for (int verify = 0; verify < 2; ++verify) { - const rad_op op = rw( - b, - RAD_OP(b, "kda_update", - RAD_PARAMS( - RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim), - RAD_F64("lower_bound", c.lower), - RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)), - RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"), - RAD_STR("dtype", "bf16"), - RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")), - RAD_WEIGHTS(alog, bias)), - { w.conv, w.a, w.beta }, { w.out }); - if (verify) - op_verify = op; - else - op_prefill = op; - } - op_norm = rw(b, - RAD_OP(b, "gdn_gated_rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim), - RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")), - RAD_WEIGHTS(norm)), - { w.out, w.gate }, { w.out }); - return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, const RadBatch* batch) const { - const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); - if (!st || !cv || !st->state_index || !cv->state_index) { - rad_step_fail(ctx, "KDA requires recurrent and convolution state indices"); - return; - } - const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim; - const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; - int64_t D = 0, DT = 0; - batch_split(batch, &D, &DT); - for (int verify = 1; verify >= 0; --verify) { - const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; - if (!seqs) continue; - const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); - const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); - const RadOperand accepted = - verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; - RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps), - kv_cache(history, layer), cu, RAD_NONE, - praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, - brows(w.conv, rows)); - RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows), - bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows), - brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias), - kv_cache(state, layer), - praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, - init, brows(w.out, rows)); - } - RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm), - brows(w.out, T)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_block_mla_latent.h b/arch/common/rad_block_mla_latent.h deleted file mode 100644 index abeb3e94..00000000 --- a/arch/common/rad_block_mla_latent.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Absorbed GLM MLA core. The caller projects/norms q and stores the current - * latent before step(). Complete heads shard as rows of the shared K/V weight. */ -#ifndef RAD_BLOCK_MLA_LATENT_H -#define RAD_BLOCK_MLA_LATENT_H -#include "rad_arch.h" -#include - -namespace rad { -namespace arch { -struct MlaLatent { - struct Config { - int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; - }; - struct Wire { - rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - rad_kvgroup kv = 0; - rad_weight projection = 0; - rad_op op_absorb = 0, op_attn = 0, op_expand = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, - const Config& cfg, const Wire& wire, const char* source) { - g = geom; - c = cfg; - w = wire; - layer = l; - kv = group; - if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent || - !w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent || - w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 || - c.head_dim != 256) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group)); - const char* name = nm.f("blk.%d.attn_kv_b.weight", l); - RAD_ARCH_TRY(map_copy(b, name, source)); - // The conversion recipe decodes this small projection only. - projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim }, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - if (!projection) return RAD_E_INVAL; - op_absorb = rw( - b, - RAD_OP(b, "mla_project", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), - RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(projection)), - { w.q }, { w.q_latent }); - op_attn = - rw(b, - RAD_OP(b, "mla_attn", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), - RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks), - RAD_INT("block_size", 4), - RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.q_latent, w.selected, w.length }, { w.attn_latent }); - if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; - op_expand = rw( - b, - RAD_OP(b, "mla_project", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), - RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(projection)), - { w.attn_latent }, { w.out }); - return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, int64_t rows) const { - RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection), - brows(w.q_latent, rows)); - RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer), - brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows)); - RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection), - brows(w.out, rows)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h new file mode 100644 index 00000000..52ceab6b --- /dev/null +++ b/arch/common/rad_glm_tp.h @@ -0,0 +1,103 @@ +/* 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. + * + * The residual stream is replicated (spec.md ยง9). Two 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 */ +#ifndef RAD_GLM_TP_H +#define RAD_GLM_TP_H +#include "rad_arch.h" + +namespace rad { +namespace arch { +struct GlmTp { + /* The model's widths a rank's shard divides: 64 heads of 128 (KDA) and 256 (MLA), experts of + * 2048 and a dense feed-forward of 12288. */ + static constexpr int64_t kHeads = 64, kKdaDim = 128, kMlaDim = 256, kExpertFF = 2048, + kDenseFF = 12288; + static bool world_ok(int world) { return world == 1 || world == 2 || world == 4 || world == 8; } + static int64_t heads(int world) { return kHeads / world; } + static int64_t kda_width(int world) { return heads(world) * kKdaDim; } + static int64_t mla_width(int world) { return heads(world) * kMlaDim; } + 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. */ + static constexpr int64_t kSplitRows = 256; + + /* 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). */ + static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { + if (g.world == 1) return 0; + return rw(b, + RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16"), + RAD_INT("exact", exact ? 1 : g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); + } +}; + +/* The split's ops are declared whatever the step size, and each gather's message as a range of + * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph + * with the same fixed parameters. + * + * A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on + * rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices + * out as the full [M, n]. The kernel computes every output column independently of n and the + * gather moves bytes, so each value is bit-identical to the replicated projection's. */ +struct SplitF32Proj { + rad_buf part = 0; + rad_op op_part = 0, op_gather = 0; + int64_t cols = 0, k = 0, min_rows = 0, first_col = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, + int64_t width, rad_weight weight, rad_buf input, rad_buf output) { + min_rows = GlmTp::kSplitRows; + if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) { + min_rows = 0; + return RAD_OK; + } + cols = n / g.world; + k = width; + first_col = g.rank * cols; + part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols }); + op_part = rw(b, + RAD_OP(b, "gemm_nt_f32", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(weight)), + { input }, { part }); + op_gather = rw( + b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols), + RAD_STR("dtype", "f32"), RAD_INT("row", cols)), + RAD_NOWEIGHTS), + { part }, { output }); + return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL; + } + bool takes(int64_t rows) const { return min_rows && rows >= min_rows; } + void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight, + RadOperand output) const { + RadOperand slice = RAD_W(weight); + slice.offset = first_col * k; + slice.rows = cols; + RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows)); + RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_tp_split.h b/arch/common/rad_tp_split.h deleted file mode 100644 index 68a92125..00000000 --- a/arch/common/rad_tp_split.h +++ /dev/null @@ -1,65 +0,0 @@ -/* GLM's replicated F32 work split over the tensor-parallel ranks: each rank computes a disjoint - * part with the replicated kernel's own arithmetic and an all_gather moves the parts to every rank, - * so every value is bit-identical to the replicated computation's. */ -#ifndef RAD_TP_SPLIT_H -#define RAD_TP_SPLIT_H -#include "rad_arch.h" - -namespace rad { -namespace arch { -/* Rows from which a replicated F32 projection splits its columns over the ranks. Below it the - * collective's latency outweighs the saved arithmetic, so decode keeps the replicated form. */ -constexpr int64_t kGlmTpSplitRows = 256; - -/* The split's ops are declared whatever the step size, and each gather's message as a range of - * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph - * with the same fixed parameters. - * - * A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on - * rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices - * out as the full [M, n]. The kernel computes every output column independently of n and the - * gather moves bytes, so each value is bit-identical to the replicated projection's. */ -struct SplitF32Proj { - rad_buf part = 0; - rad_op op_part = 0, op_gather = 0; - int64_t cols = 0, k = 0, min_rows = 0, first_col = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, - int64_t width, rad_weight weight, rad_buf input, rad_buf output) { - min_rows = kGlmTpSplitRows; - if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) { - min_rows = 0; - return RAD_OK; - } - cols = n / g.world; - k = width; - first_col = g.rank * cols; - part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols }); - op_part = rw(b, - RAD_OP(b, "gemm_nt_f32", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(weight)), - { input }, { part }); - op_gather = rw( - b, - RAD_OP(b, "all_gather", - RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols), - RAD_STR("dtype", "f32"), RAD_INT("row", cols)), - RAD_NOWEIGHTS), - { part }, { output }); - return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL; - } - bool takes(int64_t rows) const { return min_rows && rows >= min_rows; } - void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight, - RadOperand output) const { - RadOperand slice = RAD_W(weight); - slice.offset = first_col * k; - slice.rows = cols; - RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows)); - RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 1e8c394f..73dd4db6 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -1,16 +1,35 @@ -/* GLM-5.3-Flash: four mHC streams, KDA/latent MLA, mixed Quark weights, - * width-sharded routed experts and a native serial next-token decoder. - * This plugin uses only the public ABI and the installed common headers. */ -#include +/* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC + * residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer, + * 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 + * scales, each weight served as the container stores it; its MTP layer is a serial drafter. + * docs/ARCHITECTURES.md describes the model and its traps. + * + * The blocks live in arch/common (installed as ), one a file: + * + * rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write + * rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence + * rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core + * 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 + * + * 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 + * order is the recorded pass, so both are kept as they read here. This plugin uses only the + * public ABI and the installed common headers. */ +#include #include #include #include +#include #include #include #include namespace glm5next { using namespace rad::arch; + struct Layer { bool full = false, draft = false; ManifoldConn attn_hc{}, ffn_hc{}; @@ -20,17 +39,17 @@ struct Layer { GlmIndexer index{}; MlpFP8 dense{}; MoeFP8 moe{}; - rad_op residual = 0; }; struct Model { - Names nm{}, dnm{ "mtp" }; + Names nm{}; Geom g{}; std::vector layers; - Layer draft{}; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; + /* The streams and the step's stream-wide buffers. */ rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0, logits = 0; - ActFP8 act{}, ff{}; + ActFP8 act{}; + /* The blocks' wires: one set of activations, shared by every layer of a kind. */ GlmKda::Wire kw{}; GlmMla::Wire aw{}; GlmIndexer::Wire iw{}; @@ -38,11 +57,10 @@ struct Model { MoeFP8::Wire mw{}; rad_weight token = 0, head = 0, final_gain = 0; rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0; - rad_buf mtp_x = 0, mtp_h = 0, mtp_e = 0, mtp_concat = 0, mtp_final = 0; - rad_weight en = 0, hn = 0, eh = 0, mnorm = 0; - rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0, - mselect = 0, mback = 0, mcopy = 0, mhead = 0; + /* The draft head and its layer, declared only when the deployment speculates. */ bool have_mtp = false; + GlmMtp mtp{}; + Layer draft{}; }; static std::unique_ptr models[MAX_RANKS]; static thread_local std::unique_ptr probe_model; @@ -52,21 +70,10 @@ static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { std::snprintf(nested, sizeof nested, "text_config.%s", key); return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback)); } -static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { - if (g.world == 1) return 0; - return rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS( - RAD_INT("world_size", g.world), RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", exact ? 1 : g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { x }, { x }); -} -static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y, int64_t n = 4096) { +static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) { return rw(b, RAD_OP(b, "cast", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), RAD_NOWEIGHTS), { x }, { y }); @@ -79,116 +86,184 @@ static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_bu RAD_WEIGHTS(w)), { x }, { y }); } -static int buffers(RadBuilder* b, Model& m) { + +/* ------------------------------------------------------------------ the shared activations */ +static int stream_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; - const int64_t T = g.max_tok, W = 8192 / g.world, F = 2048 / g.world; - auto bf = [&](const char* n, int64_t width) { - return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); - }; - auto a = [&](ActFP8& v, const char* n, int64_t width) { - v.x = bf(n, width); - return v.declare_qs(b, nm, g, n, width); - }; - m.h0 = bf("manifold", 16384); - m.h1 = bf("manifold_mid", 16384); - m.x = bf("collapsed", 4096); - m.y = bf("attn_delta", 4096); + const int64_t T = g.max_tok; + 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 }); m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); - RAD_ARCH_TRY(a(m.act, "normalized", 4096)); + m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 }); + RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096)); m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST); m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 }); m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab }); - RAD_ARCH_TRY(rad_declare_logits(b, m.logits)); - m.kw.input = m.act.x; - m.kw.out = m.y; - m.kw.forget_low = bf("forget_low", 128); - m.kw.gate_low = bf("gate_low", 128); - m.kw.core.qkv = bf("qkv", 3 * W); - m.kw.core.conv = bf("convolved", 3 * W); - m.kw.core.a = bf("forget", W); - m.kw.core.beta = bf("beta", 64 / g.world); - m.kw.core.gate = bf("gate", W); - m.kw.core.out = bf("recurrent_out", W); - m.aw.input = m.act; - m.aw.q_raw = bf("q_raw", 1536); - m.aw.kv_raw = bf("kv_raw", 512); - RAD_ARCH_TRY(a(m.aw.q_low, "q_low", 1536)); - m.aw.latent = bf("latent", 512); - m.aw.out = m.y; - m.aw.core.q = bf("query", 16384 / g.world); - m.aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, 64 / g.world, 512 }); - m.aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, 64 / g.world, 512 }); - RAD_ARCH_TRY(a(m.aw.attn, "expanded", 16384 / g.world)); - m.aw.core.out = m.aw.attn.x; - m.aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 }); - m.aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T }); - const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1; - m.iw.input = m.act.x; - m.iw.q_low = m.aw.q_low.x; - m.iw.q_wide = bf("index_query", 4096); - m.iw.kg_raw = bf("index_key_gate", 256); - auto& iw = m.iw.cache; - iw.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 }); - iw.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 }); - iw.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 }); - iw.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 }); - iw.kg = bf("index_normalized_key_gate", 256); - iw.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 }); - iw.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work }); - iw.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work }); - iw.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs }); - iw.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 }); - iw.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 }); - iw.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks }); - iw.selected = m.aw.core.selected; - iw.length = m.aw.core.length; - iw.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); - m.dw.x = m.x; - m.dw.h = m.act; - m.dw.gate_up = bf("dense_gate_up", 2 * g.n_ff); - RAD_ARCH_TRY(a(m.dw.ffn, "dense_ff", g.n_ff)); - const int64_t R = T; - m.mw.x = m.x; - m.mw.h = m.act; - m.mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 }); - m.mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); - m.mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); - m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); - m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); - m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 }); - m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 }); - m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F }); - m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F }); - RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8)); - m.mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { R * 8, 4096 }); - m.mw.sgu = bf("shared_gate_up", 2 * F); - RAD_ARCH_TRY(a(m.mw.sff, "shared_ff", F)); - m.mw.sout = bf("shared_out", 4096); - m.mw.sgate = bf("shared_one", 1); + return rad_declare_logits(b, m.logits); +} +static int kda_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, W = GlmTp::kda_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& kw = m.kw; + kw.input = m.act.x; + kw.out = m.y; + kw.forget_low = bf("forget_low", 128); + kw.gate_low = bf("gate_low", 128); + kw.core.qkv = bf("qkv", 3 * W); + kw.core.conv = bf("convolved", 3 * W); + kw.core.a = bf("forget", W); + kw.core.beta = bf("beta", GlmTp::heads(g.world)); + kw.core.gate = bf("gate", W); + 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. */ +static int mla_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, H = GlmTp::heads(g.world), Q = GlmTp::mla_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& aw = m.aw; + aw.input = m.act; + aw.q_raw = bf("q_raw", 1536); + aw.kv_raw = bf("kv_raw", 512); + aw.q_low.x = bf("q_low", 1536); + RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536)); + aw.latent = bf("latent", 512); + aw.out = m.y; + aw.core.q = bf("query", Q); + aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 }); + aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 }); + 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 }); + 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 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 }); + }; + auto& iw = m.iw; + iw.input = m.act.x; + iw.q_low = m.aw.q_low.x; + iw.q_wide = bf("index_query", 4096); + 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.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 }); + c.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work }); + 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 }); + c.selected = m.aw.core.selected; + c.length = m.aw.core.length; + c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); + return RAD_OK; +} +static int ffn_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, F = GlmTp::expert_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& dw = m.dw; + dw.x = m.x; + dw.h = m.act; + dw.gate_up = bf("dense_gate_up", 2 * g.n_ff); + dw.ffn.x = bf("dense_ff", g.n_ff); + RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff)); + auto& mw = m.mw; + mw.x = m.x; + mw.h = m.act; + mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 }); + mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); + mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); + mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); + mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); + mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 }); + mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 }); + mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F }); + mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F }); + RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8)); + mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 }); + mw.sgu = bf("shared_gate_up", 2 * F); + mw.sff.x = bf("shared_ff", F); + RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F)); + mw.sout = bf("shared_out", 4096); + mw.sgate = bf("shared_one", 1); + return RAD_OK; +} +static int kv_groups(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 256; + m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.state_dim[0] = 4 + g.max_spec; + d.state_dim[1] = 256; + m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_F32; + d.n_head_kv = GlmTp::heads(g.world); + d.state_dim[0] = d.state_dim[1] = 128; + m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d); + d = {}; + d.kind = RAD_KV_CONV; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 3 * GlmTp::kda_width(g.world); + d.conv_width = 4; + m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d); + // The index group is declared by the first indexer, right before its cache consumer. + return m.latent && m.tail && m.state && m.conv ? RAD_OK : RAD_E_INVAL; +} + +/* ------------------------------------------------------------------ one layer */ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) { const auto& g = m.g; lay.draft = draft; lay.full = draft || l % 4 == 3; const char* pre = nm.ckpt("model.language_model.layers.%d", l); const char* ap = nm.ckpt("%s.self_attn", pre); - rad_buf input = draft ? m.mtp_x : m.x; + rad_buf input = draft ? m.mtp.x : m.x; + ManifoldConn::Config hc; + hc.eps = g.eps; if (!draft) { - ManifoldConn::Config hc; - hc.eps = g.eps; ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb }; - ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre), nm.ckpt("%s.hc_attn_base", pre) }; - ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), - nm.ckpt("%s.hc_ffn_base", pre) }; RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true)); - // Declare ffn mHC after the attention below: declaration order is liveness. - (void)f; - (void)fs; } const char* nn = nm.f("blk.%d.attn_norm.weight", l); RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre))); @@ -210,29 +285,15 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) }; RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv)); } + // The ffn connection is declared after the attention's post: declaration order is liveness. if (!draft) { RAD_ARCH_TRY(lay.attn_hc.declare_post(b)); - ManifoldConn::Config hc; - hc.eps = g.eps; ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), nm.ckpt("%s.hc_ffn_base", pre) }; RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true)); } else { - lay.residual = rw(b, - RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.mtp_x, m.y }, { m.mtp_x }); - // All history rows fill the draft cache; only proposal rows need its FFN. - m.mselect = rw(b, - RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.mtp_x }, { m.mtp_h }); - m.mback = copy(b, g, m.mtp_h, m.mtp_x); + RAD_ARCH_TRY(m.mtp.declare_join(b, m.y)); } if (l < 3) { auto w = m.dw; @@ -254,7 +315,7 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra s.shared = nm.ckpt("%s.mlp.shared_experts", pre); s.cfg.n_expert = s.cfg.n_expert_all = 288; s.cfg.top_k = 8; - s.cfg.n_ff_exp = s.cfg.n_ff_shared = 2048 / g.world; + s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world); s.cfg.rows = g.max_tok; s.cfg.sigmoid_router = 1; s.cfg.route_scale = 2.5; @@ -263,8 +324,8 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra s.cfg.router_fuse = 1; s.cfg.swiglu_quant = 1; for (int q = 0; q < 2; ++q) { - s.cfg.ff_lo[q] = g.rank * (2048 / g.world); - s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world); + s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world); + s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world); } RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg)); RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft)); @@ -272,29 +333,16 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b)); return RAD_OK; } -static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { - if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) - return RAD_E_INVAL; - const int world = ctx->world_size ? ctx->world_size : 1; - if ((world != 1 && world != 2 && world != 4 && world != 8) || meta->n_embd != 4096 || - meta->n_layers != 45 || meta->n_vocab != 154880 || - cfg(meta, "num_nextn_predict_layers", 0) != 1 || cfg(meta, "hc_mult", 0) != 4 || - cfg(meta, "n_routed_experts", 0) != 288 || cfg(meta, "index_topk", 0) != 2048 || - ctx->max_spec > 31 || (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) - return RAD_E_UNSUPPORTED; - auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; - slot = std::make_unique(); - auto& m = *slot; - auto& g = m.g; - m.nm = Names(ctx->scope); - auto& nm = m.nm; + +/* ------------------------------------------------------------------ declare */ +static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) { g.n_layer = 45; g.n_embd = 4096; - g.head_dim = 256; - g.n_head_all = g.n_head_kv_all = 64; - g.n_head = g.n_head_kv = 64 / world; - g.n_ff_all = 12288; - g.n_ff = 12288 / world; + g.head_dim = GlmTp::kMlaDim; + g.n_head_all = g.n_head_kv_all = GlmTp::kHeads; + g.n_head = g.n_head_kv = GlmTp::heads(world); + g.n_ff_all = GlmTp::kDenseFF; + g.n_ff = GlmTp::dense_width(world); g.n_vocab_all = 154880; g.n_vocab = shard_extent(154880, world, ctx->rank); g.vocab_off = shard_begin(154880, world, ctx->rank); @@ -311,34 +359,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.eps = meta->rms_eps; g.wire_exact = !ctx->tp_wire_lossy; g.wire_min_bytes = ctx->tp_wire_min_bytes; - if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL; - RAD_ARCH_TRY(buffers(b, m)); - RadKVGroupDecl d{}; - d.kind = RAD_KV_FULL; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.head_dim = 256; - m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); - d = {}; - d.kind = RAD_KV_LINEAR; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.state_dim[0] = 4 + g.max_spec; - d.state_dim[1] = 256; - m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d); - d = {}; - d.kind = RAD_KV_LINEAR; - d.dtype = RAD_F32; - d.n_head_kv = 64 / world; - d.state_dim[0] = d.state_dim[1] = 128; - m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d); - d = {}; - d.kind = RAD_KV_CONV; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.head_dim = 3 * 8192 / world; - d.conv_width = 4; - m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d); + return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK; +} +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) + return RAD_E_INVAL; + const int world = ctx->world_size ? ctx->world_size : 1; + if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 || + meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 || + cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 || + cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 || + (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) + return RAD_E_UNSUPPORTED; + auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; + slot = std::make_unique(); + auto& m = *slot; + auto& g = m.g; + m.nm = Names(ctx->scope); + auto& nm = m.nm; + RAD_ARCH_TRY(geometry(g, meta, ctx, world)); + RAD_ARCH_TRY(stream_buffers(b, m)); + RAD_ARCH_TRY(kda_buffers(b, m)); + RAD_ARCH_TRY(mla_buffers(b, m)); + RAD_ARCH_TRY(indexer_buffers(b, m)); + RAD_ARCH_TRY(ffn_buffers(b, m)); + RAD_ARCH_TRY(kv_groups(b, m)); RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"))); @@ -357,7 +402,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.token)), {}, { m.x }); - m.embed_ar = reduce(b, g, m.x, true); + m.embed_ar = GlmTp::reduce(b, g, m.x, true); m.expand = copy(b, g, m.x, m.h0); m.layers.resize(45); for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false)); @@ -382,63 +427,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_WEIGHTS(m.head)), { m.logit_input }, { m.logits }); if (g.max_spec > 0) { - auto& dn = m.dnm; - m.mtp_x = decl_b(b, dn.f("x"), RAD_BF16, { g.max_tok, 4096 }); - m.mtp_h = decl_b(b, dn.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); - m.mtp_e = decl_b(b, dn.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); - m.mtp_concat = decl_b(b, dn.f("concat"), RAD_BF16, { g.max_tok, 8192 }); - m.mtp_final = decl_b(b, dn.f("final"), RAD_BF16, { g.max_tok, 4096 }); - const char* pre = "model.language_model.layers.45"; - auto weight = [&](const char* n, const char* src) { - const char* name = dn.f("%s", n); - if (map_copy(b, name, dn.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; - return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, - grp_layer(45)); - }; - m.en = weight("enorm.weight", "enorm.weight"); - m.hn = weight("hnorm.weight", "hnorm.weight"); - m.mnorm = weight("output_norm.weight", "shared_head.norm.weight"); - RAD_ARCH_TRY(map_copy(b, dn.f("eh_proj.weight"), dn.ckpt("%s.eh_proj.weight", pre))); - m.eh = decl_w(b, dn.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, - RAD_SHARD_NONE, grp_layer(45)); - m.mprev = rw(b, - RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.final_hidden }, { m.mtp_h }); - m.membed = rw(b, - RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), - RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), - RAD_INT("vocab_offset", g.vocab_off)), - RAD_WEIGHTS(m.token)), - {}, { m.mtp_e }); - m.membed_ar = reduce(b, g, m.mtp_e, true); - m.men = norm(b, g, m.en, m.mtp_e, m.mtp_concat); - m.mhn = norm(b, g, m.hn, m.mtp_h, m.mtp_concat); - m.meh = rw(b, - RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), - RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(m.eh)), - { m.mtp_concat }, { m.mtp_x }); - RAD_ARCH_TRY(layer(b, m, m.draft, dn, 45, true)); - m.mnorm_op = norm(b, g, m.mnorm, m.mtp_x, m.mtp_final); - m.mcopy = copy(b, g, m.mtp_final, m.mtp_h); - m.mhead = - rw(b, - RAD_OP(b, "logits_gemm", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), - RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(m.head)), - { m.mtp_h }, { m.logits }); - RadDrafterDecl dd{}; - dd.name = "mtp"; - dd.kind = RAD_DRAFT_SERIAL; - dd.depth = g.max_spec; - dd.mask_token = -1; - RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head }; + RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw)); + RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true)); + RAD_ARCH_TRY(m.mtp.declare_head(b)); m.have_mtp = true; } rad_note(b, @@ -446,6 +438,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c world, m.have_mtp ? "enabled" : "disabled"); return RAD_OK; } + +/* ------------------------------------------------------------------ step */ static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { l.norm.step(c, batch->n_tok); if (l.full) { @@ -455,6 +449,24 @@ static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { } else l.kda.step(c, batch); } +static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) { + if (!m.have_mtp || batch->draft_pass == 1) { + rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1"); + return; + } + const int64_t T = batch->n_tok; + m.mtp.step_inputs(c, batch); + auto& l = m.draft; + l.norm.step(c, T); + l.mla.prepare(c, batch); + l.index.step(c, batch); + // A history pass with no proposal row fills the draft caches and ends there. + if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return; + l.mla.finish(c, batch); + m.mtp.step_join(c, batch, m.y); + l.moe.step_rows(c, GlmMtp::head_rows(batch)); + m.mtp.step_head(c, batch); +} static void step(RadCtx* c, const RadBatch* batch) { auto& m = *models[rad_rank(c)]; const int64_t T = batch->n_tok; @@ -463,36 +475,7 @@ static void step(RadCtx* c, const RadBatch* batch) { return; } if (batch->draft_pass) { - if (!m.have_mtp || batch->draft_pass == 1) { - rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1"); - return; - } - if (batch->draft_pass < 0 && batch->n_out > 0) - RAD_ISSUE_N(c, m.mprev, batch->n_out, RAD_B(m.final_hidden), - praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.mtp_h, batch->n_out)); - RAD_ISSUE_N(c, m.membed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), - brows(m.mtp_e, T)); - if (m.membed_ar) RAD_ISSUE_N(c, m.membed_ar, T * 4096, brows(m.mtp_e, T), RAD_NONE); - RAD_ISSUE_N(c, m.men, T, brows(m.mtp_e, T), RAD_W(m.en), bcol(m.mtp_concat, 0, 4096, T)); - RAD_ISSUE_N(c, m.mhn, T, brows(m.mtp_h, T), RAD_W(m.hn), bcol(m.mtp_concat, 4096, 4096, T)); - RAD_ISSUE_N(c, m.meh, T, brows(m.mtp_concat, T), RAD_W(m.eh), brows(m.mtp_x, T)); - auto& l = m.draft; - l.norm.step(c, T); - l.mla.prepare(c, batch); - l.index.step(c, batch); - if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return; - l.mla.finish(c, batch); - RAD_ISSUE_N(c, l.residual, T, brows(m.mtp_x, T), brows(m.y, T), brows(m.mtp_x, T)); - const int64_t L = batch->draft_pass < 0 ? batch->n_draft_out : T; - if (batch->draft_pass < 0) { - RAD_ISSUE_N(c, m.mselect, L, RAD_B(m.mtp_x), praw(batch->draft_out_ids, RAD_I32, L), - brows(m.mtp_h, L)); - RAD_ISSUE_N(c, m.mback, L, brows(m.mtp_h, L), brows(m.mtp_x, L)); - } - l.moe.step_rows(c, L); - RAD_ISSUE_N(c, m.mnorm_op, L, brows(m.mtp_x, L), RAD_W(m.mnorm), brows(m.mtp_final, L)); - RAD_ISSUE_N(c, m.mcopy, L, brows(m.mtp_final, L), brows(m.mtp_h, L)); - RAD_ISSUE_N(c, m.mhead, L, brows(m.mtp_h, L), RAD_W(m.head), brows(m.logits, L)); + draft_pass(c, m, batch); return; } RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); @@ -523,7 +506,7 @@ static void step(RadCtx* c, const RadBatch* batch) { } static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; - if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = 3; + if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth; out->shape_probe_ok = 1; return RAD_OK; } diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 5fd529f9..7cddba35 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -415,6 +415,19 @@ the plugin claims the empty descriptor and reads each weight's encoding from the mapped, so never converted, and an image request fails its step. The reference is SGLang's `glm5_next.py` and `glm5_next_nextn.py` at AMD's pinned commit 654df43. +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. + +| 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_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_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection | + ``` 45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16) mHC: 4 residual streams, a 16384-wide row; 20 Sinkhorn passes, hc_eps 1e-6; the embedding is @@ -446,7 +459,7 @@ Traps: - **`comb` is indexed `[source, destination]`.** Each connection's write is `out[dst] = post[dst] * y + sum_src comb[src, dst] * h[src]`; the transpose has every shape valid and is another model. `out` must be a separate buffer: each output stream reads every - input stream (`rad_block_mhc.h`). + input stream (`rad_block_glm_mhc.h`). - **The router and the index head gates stay f32.** Both projections are f32 weights against a bf16 activation with f32 results (`gemm_nt_f32`), and the routing weights reach the gather as f32. Rounding any of them to bf16 changes which experts and which blocks are picked, and a @@ -504,9 +517,11 @@ The container holds 25845 weights, 171.32 GiB; at eight ranks each card holds 22 3 unless `--num-speculative-tokens` says otherwise (at most 31). Its history pass writes the draft 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. `arch_test` declares and -steps the whole plugin at 1, 4 and 8, and the connection, router and indexer splits at 1, 2, 4 -and 8. +**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. - 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 @@ -519,7 +534,7 @@ and 8. - 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 - (`kGlmTpSplitRows`, `arch/common/rad_tp_split.h`), each rank computes a disjoint part + (`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 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5482fc84..74a07b0b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,11 +10,12 @@ # fast every test with none of slow, gpu, oot and perf, set at the end of this file: the # inner loop (`ctest --preset fast`, or `ctest -L fast`) # -# arch_test does not link rad_core: it supplies its own recording fake of the declare-phase C ABI, -# so plugins are tested without depending on core/build/'s builder. With the archive linked, a new -# ABI call missing from the fake would pull in rad_builder.cpp.o and collide on every rad_decl_* -# symbol; without it the error is a single undefined reference. -set(RAD_TESTS_NO_CORE arch_test) +# arch_test and glm5next_test do not link rad_core: they supply their own recording fake of the +# declare-phase C ABI (arch_fakes.h), so plugins are tested without depending on core/build/'s +# builder. With the archive linked, a new ABI call missing from the fake would pull in +# rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a single +# undefined reference. +set(RAD_TESTS_NO_CORE arch_test glm5next_test) # fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and # the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and @@ -273,10 +274,13 @@ if(TARGET abi_layout_test) endif() # arch_test reads libref's vocabulary from $RADIANCE_HOME/kernels to check that each architecture -# declares on it, so libref is built before it. -if(TARGET libref AND TARGET arch_test) - add_dependencies(arch_test libref) -endif() +# declares on it, and glm5next_test the loaded libraries' op schemas, so libref is built before +# them. +foreach(t arch_test glm5next_test) + if(TARGET libref AND TARGET ${t}) + add_dependencies(${t} libref) + endif() +endforeach() # kbench_mutant_test runs rad-kbench against the deliberately defective kernel libraries # (core/plugin/testplugin/kbmutant.cc) on the host backend, so it needs the tool, libref and the diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h new file mode 100644 index 00000000..824e2eb3 --- /dev/null +++ b/tests/arch_fakes.h @@ -0,0 +1,1177 @@ +/* arch_fakes.h -- the recording builder, the run-phase fakes, the step lint and the fixtures the + * architecture tests share (arch_test.cpp, glm5next_test.cpp). + * + * No GPU, no model file, no core. With two-phase construction (spec ยง3) the whole model is known + * between declare and plan, so a unit test can check what a plugin declares. The fake builder + * records every decl_weight, decl_buffer, decl_op, buffer use and name-map call, and the fake RadCtx + * records every issue, so the run phase's order and operands are checked too. + * + * The fake is deliberately not core/build/'s RadBuilder: a defect there must not fail these tests, + * and a plugin that only works against one builder has an undeclared dependency. + * + * It defines the declare- and run-phase C ABI, so exactly one translation unit of a test binary + * includes it, and that binary does not link rad_core (tests/CMakeLists.txt, RAD_TESTS_NO_CORE). */ +#ifndef RAD_ARCH_FAKES_H +#define RAD_ARCH_FAKES_H + +#include "rad_test.h" + +#include "rad_builder.h" +#include "rad_device.h" +#include "rad_runtime.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ==================================================================== the recording builder */ +namespace { + +struct RecParam { + std::string key; + int kind = 0; + long long ival = 0, ihi = 0; + double dval = 0.0; + std::string sval; +}; + +struct RecWeight { + std::string name; + RadWeightDecl d{}; + /* The uneven slice this weight was handed (rad_weight_shard_span), in the container's + * unsharded units, so tests can check which checkpoint rows each rank reads. Even shards have + * `span_set` false. */ + bool span_set = false; + int64_t span_lo = 0, span_hi = 0; + /* rad_weight_shard_span_parts, recorded likewise. */ + int n_part_spans = 0; + int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; + int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; +}; +struct RecBuf { std::string name; RadBufDecl d{}; }; +struct RecOp { + std::string op; + std::vector p; + std::vector w; + std::vector reads, writes; + bool resolved = true; + bool uses_declared = false; /* rad_op_reads/writes were called */ +}; +struct RecMap { + std::string declared; + int mode = 0; + std::vector src; + int concat_dim = 0; +}; +struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; }; +struct RecIssue { + rad_op op = 0; + std::vector opd; + int64_t n = 0; + int lane = 0; /* the lane it was issued on (rad_lane) */ +}; +/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */ +struct RecJoin { size_t at = 0; int from = 0, to = 0; }; + +} /* namespace */ + +struct RadBuilder { + std::vector weights; + std::vector bufs; + std::vector ops; + std::vector maps; + std::vector kv_groups; + std::vector> binds; + std::vector notes; + + /* Ops the fake kernel hierarchy refuses, to drive the fused-op fallback; and ops no loaded + * library declares (rad_op_declared), as without an optional library. */ + std::set refuse; + std::set undeclared; + /* When set, the only ops any loaded library declares (a CPU-only engine's: libref's + * vocabulary); every other op is undeclared. */ + const std::set* vocab = nullptr; + std::vector asked_undeclared; /* what a real engine would refuse */ + bool declared(const std::string& op) const { + return vocab ? vocab->count(op) != 0 : undeclared.count(op) == 0; + } + int64_t kv_block = 16; + + /* The buffer the plugin named as this step's logits (rad_declare_logits), or as its pooled + * output (rad_declare_pooled). */ + rad_buf logits = 0; + rad_buf pooled = 0; + + /* The draft head's declaration (rad_declare_drafter), and whether it keeps no cache of its + * own (rad_drafter_shared_kv) and at which rotary offset. */ + RadDrafterDecl drafter{}; + std::string drafter_name; + bool drafter_shared = false; + int drafter_pos = -1; + + /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ + std::vector concurrent; + + /* The vision and audio encoder declarations (rad_declare_encoder), if any. */ + RadEncoderDecl encoder{}; + std::string encoder_name; + RadEncoderDecl audio_encoder{}; + std::string audio_encoder_name; + + /* The image generator's declaration (rad_declare_generator), if any. */ + RadGeneratorDecl generator{}; + std::string generator_name; + + /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as + * (native, from, to, from_lo, from_hi, to_lo). */ + std::vector> lora_roots; + struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; + std::vector lora_aliases; + + /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty + * means no model, so every weight is plain in its declared dtype. */ + std::vector> encs; + + const RecOp* op_of(rad_op h) const { return h ? &ops[h - 1] : nullptr; } +}; + +struct RadCtx { + RadBuilder* b = nullptr; + const RadBatch* batch = nullptr; + int rank = 0; + int world = 1; + std::vector issues; + std::vector routed_layers; + std::string step_fail; + int lane = 0; /* where the next issue goes */ + std::vector joins; + /* Device copies into a buffer (rad_memcpy_async to a rad_buf_ptr address): the buffer and the + * issue number the copy came before. The step lint counts each as a write there. */ + std::vector> copies; +}; + +/* -------------------------------------------------------------------- the declare-side ABI */ +extern "C" rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d) { + b->weights.push_back({name, *d}); + return (rad_weight)b->weights.size(); +} + +extern "C" int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t*, + uint32_t*) { + for (const auto& [key, e] : b->encs) + if (source && std::strstr(source, key.c_str())) { *out = e; return RAD_OK; } + return RAD_E_NOTFOUND; +} +extern "C" rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d) { + b->bufs.push_back({name, *d}); + return (rad_buf)b->bufs.size(); +} + +extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, + const rad_weight* weights, int n_weights) { + if (!b->declared(op)) { + b->asked_undeclared.push_back(op); + return RAD_NULL_HANDLE; + } + RecOp r; + r.op = op; + for (int i = 0; i < n_params; ++i) { + RecParam p; + p.key = params[i].key ? params[i].key : ""; + p.kind = params[i].kind; + p.ival = params[i].ival; + p.ihi = params[i].ihi; + p.dval = params[i].dval; + p.sval = params[i].sval ? params[i].sval : ""; + r.p.push_back(p); + } + for (int i = 0; i < n_weights; ++i) r.w.push_back(weights[i]); + r.resolved = b->refuse.count(r.op) == 0; + b->ops.push_back(r); + /* Declare always completes. An unresolved op is RAD_NULL_HANDLE, an error only if the plugin + * issues it (rad_builder.h). */ + return r.resolved ? (rad_op)b->ops.size() : RAD_NULL_HANDLE; +} + +extern "C" int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!h) return RAD_E_INVAL; + RecOp& r = b->ops[h - 1]; + r.uses_declared = true; + for (int i = 0; i < n; ++i) r.reads.push_back(bufs[i]); + return RAD_OK; +} + +extern "C" int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!h) return RAD_E_INVAL; + RecOp& r = b->ops[h - 1]; + r.uses_declared = true; + for (int i = 0; i < n; ++i) r.writes.push_back(bufs[i]); + return RAD_OK; +} + +extern "C" int rad_op_resolved(RadBuilder* b, rad_op h) { + return h != RAD_NULL_HANDLE && b->ops[h - 1].resolved; +} + +extern "C" int rad_op_declared(RadBuilder* b, const char* op) { + return op && b->declared(op); +} + +extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, + const RadKVGroupDecl* d) { + b->kv_groups.push_back({name, *d, false}); + return (rad_kvgroup)b->kv_groups.size(); +} + +extern "C" int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { (void)g; return b->kv_block; } + +extern "C" int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { + b->binds.push_back({layer, g}); + return RAD_OK; +} + +extern "C" int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { + RecMap r; + r.declared = m->declared; + r.mode = m->mode; + r.concat_dim = m->concat_dim; + for (int i = 0; i < m->n_src; ++i) r.src.push_back(m->src[i]); + b->maps.push_back(r); + return RAD_OK; +} + +extern "C" void rad_note(RadBuilder* b, const char* fmt, ...) { + char buf[512]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + b->notes.push_back(buf); +} + +/* The buffer the core samples from, recorded so tests can assert the plugin named the narrow + * one: [max_tok, n_vocab] is legal but 8 GiB at this vocabulary. */ +extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { + if (!b || !logits) return RAD_E_INVAL; + b->logits = logits; + return RAD_OK; +} + +/* An embedding program names its pooled output instead of logits; a program declares one. */ +extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { + if (!b || !pooled || b->logits) return RAD_E_INVAL; + b->pooled = pooled; + return RAD_OK; +} + +/* An image generator's declaration, recorded whole; it too excludes logits. */ +extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { + if (!b || !d || !d->image_out || b->logits || b->pooled) return RAD_E_INVAL; + b->generator = *d; + b->generator_name = d->name ? d->name : ""; + return RAD_OK; +} + +/* Recorded: a generator's adapter key names. */ +extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { + if (!b || !native || !*native) return RAD_E_INVAL; + b->lora_roots.push_back({ native, spellings ? spellings : "" }); + return RAD_OK; +} +extern "C" int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, + int64_t from_lo, int64_t from_hi, int64_t to_lo) { + if (!b || !native || !from || !to) return RAD_E_INVAL; + b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); + return RAD_OK; +} + +/* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ +extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { + if (!b || !buf) return RAD_E_INVAL; + b->concurrent.push_back(buf); + return RAD_OK; +} +extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { + if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; + if (lo < 0 || hi <= lo) return RAD_E_INVAL; + /* The real Builder also checks the declared extent against hi-lo (core/build/rad_builder.cpp); + * the fake only records the span for tests. */ + RecWeight& rw = b->weights[w - 1]; + rw.span_set = true; + rw.span_lo = lo; + rw.span_hi = hi; + return RAD_OK; +} +extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, + const int64_t* hi, const int64_t* total, int n) { + if (!b || w == 0 || w > b->weights.size() || !lo || !hi || !total) return RAD_E_INVAL; + if (n < 2 || n > RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + RecWeight& rw = b->weights[w - 1]; + if (rw.d.n_row_parts != n) return RAD_E_INVAL; + for (int g = 0; g < n; ++g) { + if (lo[g] < 0 || hi[g] <= lo[g] || hi[g] > total[g]) return RAD_E_INVAL; + if (rw.d.row_parts[g] != hi[g] - lo[g]) return RAD_E_SHAPE; + rw.part_lo[g] = lo[g]; + rw.part_hi[g] = hi[g]; + rw.part_total[g] = total[g]; + } + rw.n_part_spans = n; + return RAD_OK; +} +extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { + if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; + b->kv_groups[g - 1].zero = true; + return RAD_OK; +} +extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { + if (!b || !d) return RAD_E_INVAL; + b->drafter = *d; + b->drafter_name = d->name ? d->name : ""; + return RAD_OK; +} +extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { + if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1)) + return RAD_E_STATE; + b->drafter_shared = true; + b->drafter_pos = pos_offset; + return RAD_OK; +} +extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { + if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; + if (d->modalities == RAD_MM_AUDIO) { + b->audio_encoder = *d; + b->audio_encoder_name = d->name; + return RAD_OK; + } + b->encoder = *d; + b->encoder_name = d->name; + return RAD_OK; +} + +/* -------------------------------------------------------------------- model metadata */ +extern "C" long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return atoll(m->kv_val[i]); + return dflt; +} +extern "C" double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return atof(m->kv_val[i]); + return dflt; +} +extern "C" const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return m->kv_val[i]; + return dflt; +} + +/* -------------------------------------------------------------------- the run-phase ABI */ +extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) { + RecIssue r; + r.op = op; + r.n = n; + for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]); + r.lane = c->lane; + c->issues.push_back(r); + return RAD_OK; +} +/* The second lane, recorded: each issue's lane, and each join's position among the issues. */ +extern "C" int rad_lane(RadCtx* c, int lane) { + if (lane != 0 && lane != 1) return RAD_E_INVAL; + c->lane = lane; + return RAD_OK; +} +extern "C" int rad_lane_join(RadCtx* c, int from, int to) { + if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; + c->joins.push_back({ c->issues.size(), from, to }); + return RAD_OK; +} +/* A block that refuses the batch records the reason for the tests. */ +extern "C" int rad_step_fail(RadCtx* c, const char* what) { + c->step_fail = what ? what : ""; + return RAD_E_SHAPE; +} +extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; } +extern "C" int rad_rank(RadCtx* c) { return c->rank; } +extern "C" int rad_world_size(RadCtx* c) { return c->world; } +/* The context itself, so a copy issued on the step's stream is recorded in it (rad_memcpy_async). */ +extern "C" RadStream rad_stream(RadCtx* c) { return (RadStream)c; } +extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; } +extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { + (void)r; + c->routed_layers.push_back(layer); + return RAD_OK; +} +/* No card-side histogram here, so a router writes and reports its own buffer. */ +extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) { + (void)c; (void)layer; (void)n_expert; + return nullptr; +} +/* No prefetch here: the three calls are no-ops, as in a core without one. */ +extern "C" int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, + int64_t rows, int64_t n_embd) { + (void)c; (void)next; (void)h; (void)r0; (void)rows; (void)n_embd; + return RAD_OK; +} +extern "C" int rad_expert_prefetch_mark(RadCtx* c) { (void)c; return RAD_OK; } +extern "C" int rad_expert_prefetch_step(RadCtx* c, int layer) { (void)c; (void)layer; return RAD_OK; } +/* Never dereferenced: a plugin passes these through to rad_route_report or offsets one into a raw + * operand. Each handle gets its own 2^36-byte window above any user-space address, tagged by + * kind in the top bits, so the step lint can map a raw operand inside a buffer back to that buffer + * (fake_buf_of). */ +constexpr int kFakePtrShift = 36; +constexpr uintptr_t kFakeBufTag = (uintptr_t)1 << 61; +constexpr uintptr_t kFakeWeightTag = (uintptr_t)1 << 62; +extern "C" void* rad_weight_ptr(RadCtx* c, rad_weight w) { + (void)c; + return (void*)(kFakeWeightTag | (uintptr_t)w << kFakePtrShift); +} +extern "C" void* rad_buf_ptr(RadCtx* c, rad_buf b) { + (void)c; + return (void*)(kFakeBufTag | (uintptr_t)b << kFakePtrShift); +} +/* The buffer a raw operand points into, if it came from rad_buf_ptr; 0 otherwise. */ +static rad_buf fake_buf_of(const void* p, size_t n_bufs) { + const uintptr_t u = (uintptr_t)p; + if ((u & ~(kFakeBufTag - 1)) != kFakeBufTag) return 0; + const uintptr_t h = (u & (kFakeBufTag - 1)) >> kFakePtrShift; + return h >= 1 && h <= n_bufs ? (rad_buf)h : 0; +} +/* Pinned host memory a plugin fills itself (qwen4exp_fp8's piece bounds, the calibration tap's + * staging), as host memory; nothing else is handed out. */ +extern "C" void* rad_dev_alloc(int64_t bytes, int kind) { + return kind == RAD_MEM_HOST_PINNED && bytes > 0 ? std::calloc(1, (size_t)bytes) : nullptr; +} +extern "C" void rad_dev_free(void* p, int kind) { if (kind == RAD_MEM_HOST_PINNED) std::free(p); } +/* The device copies: nothing is copied. One into a buffer on a step's stream is recorded as a + * write of that buffer before the next issue (RadCtx::copies). */ +extern "C" int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) { + (void)src; (void)bytes; + RadCtx* c = (RadCtx*)s; + if (c && c->b) + if (const rad_buf h = fake_buf_of(dst, c->b->bufs.size())) + c->copies.push_back({ c->issues.size(), h }); + return RAD_OK; +} +extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) { + (void)dst; (void)value; (void)bytes; (void)s; + return RAD_OK; +} + +/* ==================================================================== fixtures and helpers */ +namespace { + +/* A deployment: one rank, 256 rows a step, eight sequences, 32k of context. */ +RadBuildCtx build_ctx(int rank = 0, int world = 1) { + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 256; + c.max_seqs = 8; + c.max_ctx = 32768; + c.scope = ""; + return c; +} + +/* The sampled rows (RadBatch::out_ids). The plugin skips the lm_head when n_out is zero (a chunk + * finishing no sequence), so a fake batch must set them or it silently tests the no-logits + * path. */ +static const int32_t kDecodeOut[] = { 0, 1, 2, 3 }; +static const int32_t kPrefillOut[] = { 31, 63 }; /* last token of each 32-token sequence */ + +RadBatch decode_batch() { + RadBatch b{}; + b.phase = RAD_PHASE_DECODE; + b.n_tok = 4; + b.n_seq = 4; + b.max_q_len = 1; + b.max_ctx_len = 100; + b.n_out = 4; + b.out_ids = kDecodeOut; + return b; +} + +RadBatch prefill_batch() { + RadBatch b{}; + b.phase = RAD_PHASE_PREFILL; + b.n_tok = 64; + b.n_seq = 2; + b.max_q_len = 32; + b.max_ctx_len = 32; + b.n_out = 2; + b.out_ids = kPrefillOut; + return b; +} + +/* --- small queries over the recorded graph --- */ +std::vector op_names(const RadBuilder& b) { + std::vector v; + for (const auto& o : b.ops) v.push_back(o.op); + return v; +} + +const RecOp* find_op(const RadBuilder& b, const std::string& name, int nth = 0) { + for (const auto& o : b.ops) + if (o.op == name && nth-- == 0) return &o; + return nullptr; +} + +int count_op(const RadBuilder& b, const std::string& name) { + int n = 0; + for (const auto& o : b.ops) if (o.op == name) ++n; + return n; +} + +const RecParam* param(const RecOp* o, const char* key) { + if (!o) return nullptr; + for (const auto& p : o->p) if (p.key == key) return &p; + return nullptr; +} + +long long pint(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->ival : -12345; +} + +double pflt(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->dval : -12345.0; +} + +std::string pstr(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->sval : std::string(""); +} + +const RecWeight* find_w(const RadBuilder& b, const std::string& name) { + for (const auto& w : b.weights) if (w.name == name) return &w; + return nullptr; +} + +const RecBuf* find_b(const RadBuilder& b, const std::string& name) { + for (const auto& x : b.bufs) if (x.name == name) return &x; + return nullptr; +} + +const RecMap* find_map(const RadBuilder& b, const std::string& declared) { + for (const auto& m : b.maps) if (m.declared == declared) return &m; + return nullptr; +} + +std::string join(const std::vector& v) { + std::string s; + for (size_t i = 0; i < v.size(); ++i) { if (i) s += " "; s += v[i]; } + return s; +} + +std::vector issued_ops(const RadBuilder& b, const RadCtx& c) { + std::vector got; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + got.push_back(o ? o->op : ""); + } + return got; +} + +/* `fn`'s status, with what it prints kept out of the test output. */ +int stderr_of_rc(const std::function& fn) { + int rc = 0; + stderr_of([&] { rc = fn(); }); + return rc; +} + +/* Model metadata built key by key; `meta()` is valid while this object lives. */ +struct MetaKV { + RadModelMeta m{}; + std::vector keys, vals; + std::vector kp, vp; + explicit MetaKV(const RadModelMeta& base) : m(base) { + for (int i = 0; i < base.n_kv; ++i) set(base.kv_key[i], base.kv_val[i]); + } + MetaKV& set(const char* k, const char* v) { + for (size_t i = 0; i < keys.size(); ++i) + if (keys[i] == k) { vals[i] = v; return *this; } + keys.push_back(k); + vals.push_back(v); + return *this; + } + MetaKV& drop(const char* k) { + for (size_t i = 0; i < keys.size(); ++i) + if (keys[i] == k) { + keys.erase(keys.begin() + (long)i); + vals.erase(vals.begin() + (long)i); + break; + } + return *this; + } + const RadModelMeta* meta() { + kp.clear(); vp.clear(); + for (size_t i = 0; i < keys.size(); ++i) { + kp.push_back(keys[i].c_str()); + vp.push_back(vals[i].c_str()); + } + m.n_kv = (int)kp.size(); + m.kv_key = kp.data(); + m.kv_val = vp.data(); + return &m; + } +}; + +RadBuildCtx spec_ctx(int rank, int world, int max_spec) { + RadBuildCtx c = build_ctx(rank, world); + c.max_spec = max_spec; + return c; +} + +const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string& name, + int nth = 0) { + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == name && nth-- == 0) return &i; + } + return nullptr; +} + +int count_issued(const std::vector& v, const std::string& name) { + return (int)std::count(v.begin(), v.end(), name); +} + +} /* namespace */ + +/* ==================================================================== the step lint + * + * The buffer plan takes liveness from declaration order: a transient lives over the [first, last] + * op indices of its declared reads and writes, and two transients of one arena whose ranges are + * disjoint may share bytes (core/build/rad_bufplan.cpp). A step that issues ops in another order, + * or across passes of one engine step (trunk, drafter history, draft rounds), can write one buffer + * while another that shares its bytes still holds rows a later issue reads. The runtime refuses + * only an op outside a buffer's range, and only on the branch a real model runs, so the class is + * checked here for every recorded step. + * + * lint_step walks the issues of one engine step's passes in order and reports: + * alias a transient read whose last writer is followed, before the read, by a write of a + * transient of the same arena whose range is disjoint from its own; + * undeclared an op issued outside the declared range of a buffer operand + * (core/runtime/issue.cpp refuses this); + * span an operand that reaches past its buffer or weight, rows and columns applied as + * issue.cpp applies them; + * null op an issue of RAD_NULL_HANDLE (a fused op that did not resolve, with no chain); + * unwritten a transient read before any issue, or device copy into it, of the step wrote it; + * kv a cache operand naming a group or layer no rad_bind_layer_kv bound, or a group + * this rank declared zero; + * strided a GEMM whose input is a column slice narrower than its buffer (libr4d's GEMMs + * read whole rows and refuse it). */ +namespace { + +/* One buffer's planned lifetime. `planned` is false for a buffer live over the whole program + * (PERSIST, DERIVED, rad_buf_concurrent, or no declared use), which shares bytes with nothing. */ +struct Live { + int32_t lo = 0, hi = 0; + bool planned = false; + bool transient = false; + int domain = RAD_DOMAIN_DEVICE; +}; + +/* Liveness by the rule of Builder::finish_buffer_liveness (core/build/rad_builder.cpp). Op handle + * h is op index h: the real builder keeps a sentinel at index 0, and the fake hands out ops in + * declaration order from 1. */ +std::vector liveness(const RadBuilder& b) { + const size_t nb = b.bufs.size(); + const int32_t last_op = (int32_t)b.ops.size(); + std::vector first(nb + 1, -1), last(nb + 1, -1); + for (size_t i = 0; i < b.ops.size(); ++i) + for (const std::vector* v : { &b.ops[i].reads, &b.ops[i].writes }) + for (rad_buf h : *v) { + if (h == 0 || h > nb) continue; + if (first[h] < 0) first[h] = (int32_t)(i + 1); + last[h] = (int32_t)(i + 1); + } + std::set conc(b.concurrent.begin(), b.concurrent.end()); + std::vector L(nb + 1); + for (size_t h = 1; h <= nb; ++h) { + const RadBufDecl& d = b.bufs[h - 1].d; + Live& l = L[h]; + l.transient = d.kind == RAD_BUF_TRANSIENT; + l.domain = d.domain; + if (!l.transient || conc.count((rad_buf)h) || first[h] < 0) { + l.lo = 0; + l.hi = last_op; + continue; + } + l.planned = true; + l.lo = first[h]; + l.hi = last[h]; + if ((rad_buf)h == b.logits || (rad_buf)h == b.pooled) l.hi = last_op; + } + return L; +} + +/* Whether operand `o` stays inside a buffer or weight of `shape` (packed strides, rows and cols + * applied as issue.cpp applies them), as issue.cpp's operand_fits decides. */ +bool operand_fits(const int64_t* shape, uint32_t rank, const RadOperand& o) { + if (o.offset < 0) return false; + int64_t sh[RAD_MAX_RANK] = {}, st[RAD_MAX_RANK] = {}; + int64_t numel = 1; + for (uint32_t d = 0; d < rank; ++d) { sh[d] = shape[d]; numel *= shape[d]; } + int64_t s = 1; + for (int d = (int)rank - 1; d >= 0; --d) { st[d] = s; s *= sh[d]; } + if (o.rows > 0 && rank >= 1) sh[0] = o.rows; + if (o.cols > 0 && rank >= 1) sh[rank - 1] = o.cols; + int64_t span = o.offset; + for (uint32_t d = 0; d < rank; ++d) { + if (sh[d] <= 0) return true; + span += (sh[d] - 1) * st[d]; + } + return span < numel; +} + +bool in(const std::vector& v, rad_buf h) { + return std::find(v.begin(), v.end(), h) != v.end(); +} + +std::vector lint_step(const RadBuilder& b, const std::vector& passes) { + std::vector bad; + const std::vector L = liveness(b); + const size_t nb = b.bufs.size(); + auto name = [&](rad_buf h) { return h && h <= nb ? b.bufs[h - 1].name : std::string("?"); }; + auto shares = [&](rad_buf x, rad_buf y) { + const Live& p = L[x]; + const Live& q = L[y]; + return p.planned && q.planned && p.domain == q.domain && (p.hi < q.lo || q.hi < p.lo); + }; + std::set> bound(b.binds.begin(), b.binds.end()); + std::vector last_write(nb + 1, -1); + int64_t pos = 0; + char where[96]; + for (size_t pi = 0; pi < passes.size(); ++pi) { + const RadCtx& c = *passes[pi]; + size_t next_copy = 0; + for (size_t ii = 0; ii < c.issues.size(); ++ii, ++pos) { + for (; next_copy < c.copies.size() && c.copies[next_copy].first <= ii; ++next_copy) + last_write[c.copies[next_copy].second] = pos; + const RecIssue& is = c.issues[ii]; + const RecOp* o = b.op_of(is.op); + std::snprintf(where, sizeof where, "pass %zu issue %zu (%s, op %u)", pi, ii, + o ? o->op.c_str() : "", (unsigned)is.op); + if (!o) { bad.push_back(std::string(where) + ": null op issued"); continue; } + std::vector rd, wr; + for (size_t k = 0; k < is.opd.size(); ++k) { + const RadOperand& od = is.opd[k]; + const std::string at = std::string(where) + " operand " + std::to_string(k); + if (od.kind == RAD_OPK_BUF) { + const rad_buf h = od.handle; + if (h == 0 || h > nb) { + bad.push_back(at + ": buffer handle out of range"); + continue; + } + const RadBufDecl& d = b.bufs[h - 1].d; + if (!operand_fits(d.shape, d.rank, od)) + bad.push_back(at + ": span past '" + name(h) + "' (offset " + + std::to_string(od.offset) + ", rows " + + std::to_string(od.rows) + ", cols " + + std::to_string(od.cols) + ")"); + const Live& l = L[h]; + if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) + bad.push_back(at + ": undeclared use of '" + name(h) + "' (planned ops " + + std::to_string(l.lo) + ".." + std::to_string(l.hi) + ")"); + const bool r = in(o->reads, h), w = in(o->writes, h); + if (r || !w) rd.push_back(h); + if (w || !r) wr.push_back(h); + /* A GEMM's input is read as contiguous rows: libr4d refuses a column slice + * narrower than its buffer. */ + const int64_t width = d.rank ? d.shape[d.rank - 1] : 0; + if (k == 0 && o->op.rfind("gemm_nt", 0) == 0 && od.cols > 0 && + (od.cols != width || od.offset % width)) + bad.push_back(at + ": " + o->op + " reads " + std::to_string(od.cols) + + " of " + std::to_string(width) + " columns of '" + name(h) + + "' as its input, which is not contiguous"); + } else if (od.kind == RAD_OPK_WEIGHT) { + const uint32_t h = od.handle; + if (h == 0 || h > b.weights.size()) { + bad.push_back(at + ": weight handle out of range"); + continue; + } + const RadWeightDecl& d = b.weights[h - 1].d; + if ((od.offset || od.rows > 0 || od.cols > 0) && + !operand_fits(d.shape, d.rank, od)) + bad.push_back(at + ": span past weight '" + b.weights[h - 1].name + "'"); + } else if (od.kind == RAD_OPK_WTAB) { + if (od.handle == 0 || od.rows <= 0 || od.offset || od.cols || + (size_t)(od.handle + od.rows - 1) > b.weights.size()) + bad.push_back(at + ": weight table out of range"); + } else if (od.kind == RAD_OPK_KV) { + const rad_kvgroup g = od.handle; + if (g == 0 || g > b.kv_groups.size()) + bad.push_back(at + ": KV group handle out of range"); + else if (b.kv_groups[g - 1].zero) + bad.push_back(at + ": KV group '" + b.kv_groups[g - 1].name + + "' is declared zero on this rank"); + else if (!bound.count({ (int)od.offset, g })) + bad.push_back(at + ": layer " + std::to_string(od.offset) + + " is not bound to KV group '" + b.kv_groups[g - 1].name + + "'"); + } else if (od.kind == RAD_OPK_RAW) { + if (od.offset && od.dtype == RAD_DT_INVALID) + bad.push_back(at + ": raw operand with an offset and no dtype"); + /* A pointer into a buffer (rad_buf_ptr) is that buffer to the plan, so it is + * classified by the op's declared sets like a buffer operand. */ + if (const rad_buf h = fake_buf_of(od.raw, nb)) { + const Live& l = L[h]; + if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) + bad.push_back(at + ": undeclared use of '" + name(h) + + "' through a raw pointer"); + const bool r = in(o->reads, h), w = in(o->writes, h); + if (r || !w) rd.push_back(h); + if (w || !r) wr.push_back(h); + } + } + } + for (rad_buf h : rd) { + if (!L[h].transient) continue; + const int64_t w = last_write[h]; + if (w < 0) { + bad.push_back(std::string(where) + ": reads '" + name(h) + + "' before any issue of this step wrote it"); + continue; + } + for (size_t x = 1; x <= nb; ++x) + if (x != h && last_write[x] > w && shares(h, (rad_buf)x)) + bad.push_back(std::string(where) + ": reads '" + name(h) + "' (ops " + + std::to_string(L[h].lo) + ".." + std::to_string(L[h].hi) + + ") after a write of '" + name((rad_buf)x) + "' (ops " + + std::to_string(L[x].lo) + ".." + std::to_string(L[x].hi) + + "), which may share its bytes"); + } + for (rad_buf h : wr) last_write[h] = pos; + } + } + return bad; +} + +/* ---------------------------------------------------------------- whole step batches + * + * A batch as the core builds it: every per-token and per-sequence array filled and a group batch + * for every KV group the builder declared, so a plugin's step can take any path. Decode sequences + * come first (RadBatch::n_seq_decode); each `dq` entry is a decode sequence's query length (1, or + * 1 + n_spec for a verify), each `pq` entry a prefill chunk. Every decode row is sampled (a verify + * needs logits at each row) and a chunk's last row; a chunk continues `prefill_ctx` tokens of + * history. */ +struct Kit { + std::vector tok, pos, cu, ctxl, qlen, out, nacc, dout; + std::vector slot, table, used, sidx; + std::vector kv; + RadBatch b{}; +}; + +std::unique_ptr kit(const RadBuilder& bld, const std::vector& dq, + const std::vector& pq, int32_t prefill_ctx = 0) { + auto k = std::make_unique(); + const int64_t nd = (int64_t)dq.size(), ns = nd + (int64_t)pq.size(); + std::vector ql(dq); + ql.insert(ql.end(), pq.begin(), pq.end()); + int64_t T = 0, max_q = 0, max_ctx = 0, td = 0, mqd = 0, mqp = 0; + k->cu.push_back(0); + for (int64_t s = 0; s < ns; ++s) { + const bool dec = s < nd; + const int32_t ctx = dec ? (int32_t)(40 + 7 * s) : prefill_ctx; + for (int i = 0; i < ql[(size_t)s]; ++i) { + k->tok.push_back((int32_t)(3 + (T + i) % 97)); + k->pos.push_back(ctx + i); + if (dec || i + 1 == ql[(size_t)s]) k->out.push_back((int32_t)(T + i)); + } + T += ql[(size_t)s]; + k->cu.push_back((int32_t)T); + k->ctxl.push_back(ctx); + k->qlen.push_back(ql[(size_t)s]); + k->nacc.push_back(1); + k->dout.push_back((int32_t)T - 1); + max_q = std::max(max_q, ql[(size_t)s]); + max_ctx = std::max(max_ctx, ctx + ql[(size_t)s]); + if (dec) { td += ql[(size_t)s]; mqd = std::max(mqd, ql[(size_t)s]); } + else mqp = std::max(mqp, ql[(size_t)s]); + } + k->tok.resize((size_t)T + 64, 5); /* room for a following prompt (RadBatch::n_ahead) */ + const int64_t pitch = 16; + for (int64_t i = 0; i < T; ++i) k->slot.push_back((int32_t)i); + for (int64_t i = 0; i < ns * pitch; ++i) k->table.push_back((int32_t)i); + for (int64_t s = 0; s < ns; ++s) { + k->used.push_back(k->ctxl[(size_t)s] + k->qlen[(size_t)s]); + k->sidx.push_back((int32_t)s); + } + for (size_t g = 0; g < bld.kv_groups.size(); ++g) { + RadKVGroupBatch gb{}; + gb.group = (rad_kvgroup)(g + 1); + gb.slot_mapping = k->slot.data(); + gb.block_table = k->table.data(); + gb.block_table_pitch = pitch; + gb.seqused = k->used.data(); + gb.state_index = k->sidx.data(); + gb.state_index_pitch = 1; + gb.block_size = bld.kv_block; + gb.max_blocks = pitch; + k->kv.push_back(gb); + } + RadBatch& b = k->b; + b.phase = pq.empty() ? RAD_PHASE_DECODE : dq.empty() ? RAD_PHASE_PREFILL : RAD_PHASE_MIXED; + b.n_tok = T; + b.n_seq = ns; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + b.n_out = (int64_t)k->out.size(); + b.out_ids = k->out.data(); + b.q_lens = k->qlen.data(); + b.ctx_lens = k->ctxl.data(); + b.max_q_len = (int32_t)max_q; + b.max_ctx_len = (int32_t)max_ctx; + b.n_kv_groups = (int)k->kv.size(); + b.kv = k->kv.data(); + b.n_spec = mqd > 1 ? (int)(mqd - 1) : 0; + b.num_accepted = k->nacc.data(); + b.n_seq_decode = nd; + b.n_tok_decode = td; + b.max_q_len_decode = (int32_t)mqd; + b.max_q_len_prefill = (int32_t)mqp; + return k; +} + +/* The draft passes the core stages for a step of `n_seq` sequences. + * + * A serial head's history pass (draft_pass -1) covers every row the trunk step had and carries + * round 1 on each sequence's last row; round r (2..depth) is one row a sequence. A block + * drafter's context pass (-1) covers the trunk's rows; its query pass (1) is `block` rows a + * sequence, the anchor first, and samples the `steps` rows after it (RadDrafterDecl::block). */ +std::unique_ptr history_pass(const RadBuilder& bld, const Kit& trunk) { + std::vector rows; + for (int64_t s = 0; s < trunk.b.n_seq; ++s) rows.push_back(trunk.qlen[(size_t)s]); + auto k = kit(bld, rows, {}); + k->b.draft_pass = -1; + k->out.clear(); + for (int64_t i = 0; i < k->b.n_tok; ++i) k->out.push_back((int32_t)i); + k->b.out_ids = k->out.data(); + k->b.n_out = k->b.n_tok; + k->b.n_draft_out = k->b.n_seq; + k->b.draft_out_ids = k->dout.data(); + return k; +} +std::unique_ptr round_pass(const RadBuilder& bld, int64_t n_seq, int r) { + auto k = kit(bld, std::vector((size_t)n_seq, 1), {}); + k->b.draft_pass = r; + return k; +} +std::unique_ptr context_pass(const RadBuilder& bld, const Kit& trunk) { + auto k = history_pass(bld, trunk); + k->b.n_draft_out = 0; + k->b.draft_out_ids = nullptr; + return k; +} +std::unique_ptr query_pass(const RadBuilder& bld, int64_t n_seq, int64_t block, + int64_t steps) { + auto k = kit(bld, std::vector((size_t)n_seq, (int)block), {}); + k->b.draft_pass = 1; + k->out.clear(); + for (int64_t s = 0; s < n_seq; ++s) + for (int64_t i = 0; i < steps; ++i) + k->out.push_back((int32_t)(s * block + block - steps + i)); + k->b.out_ids = k->out.data(); + k->b.n_out = (int64_t)k->out.size(); + return k; +} + +using StepFn = void (*)(RadCtx*, const RadBatch*); + +/* Runs one engine step's passes in order, each on a context of its own. */ +std::vector> run_passes(RadBuilder& b, StepFn step, + const std::vector& passes, + int rank = 0, int world = 1) { + std::vector> out; + for (const Kit* k : passes) { + out.push_back(std::make_unique()); + RadCtx& c = *out.back(); + c.b = &b; + c.batch = &k->b; + c.rank = rank; + c.world = world; + step(&c, &k->b); + } + return out; +} + +std::vector view(const std::vector>& v) { + std::vector p; + for (const auto& c : v) p.push_back(c.get()); + return p; +} + +/* The lint as a check: every finding is printed, and the step passes only with none. */ +size_t report_lint(const std::vector& f) { + for (size_t i = 0; i < f.size() && i < 12; ++i) fprintf(stderr, " lint: %s\n", f[i].c_str()); + if (f.size() > 12) fprintf(stderr, " lint: ... %zu more\n", f.size() - 12); + return f.size(); +} + +/* Every pass of one engine step ran without a step failure. */ +bool steps_ok(const std::vector>& v) { + bool ok = true; + for (size_t i = 0; i < v.size(); ++i) + if (!v[i]->step_fail.empty()) { + fprintf(stderr, " pass %zu failed: %s\n", i, v[i]->step_fail.c_str()); + ok = false; + } + return ok; +} + +} /* namespace */ + +#define CHECK_LINT(b, ...) CHECK_EQ(report_lint(lint_step((b), { __VA_ARGS__ })), (size_t)0) +/* The passes of one engine step (run_passes): none failed and the lint is clean over them. */ +#define CHECK_PASSES(b, v) \ + do { \ + CHECK(steps_ok(v)); \ + CHECK_EQ(report_lint(lint_step((b), view(v))), (size_t)0); \ + } while (0) + +/* ==================================================================== fingerprints */ +namespace { + +/* A 64-bit FNV-1a fingerprint of everything a declare recorded: ops with their parameters, + * weights, read and write sets and resolution; buffers, weights, KV groups, bindings, name maps, + * the logits / pooled / drafter / generator declarations and the concurrent list. Two declares + * give one value only if the core would build the same program from them. */ +struct Fnv { + uint64_t h = 1469598103934665603ull; + Fnv& raw(const void* p, size_t n) { + const auto* c = (const unsigned char*)p; + for (size_t i = 0; i < n; ++i) { h ^= c[i]; h *= 1099511628211ull; } + return *this; + } + Fnv& s(const std::string& x) { return raw(x.data(), x.size()).i((int64_t)x.size()); } + Fnv& s(const char* x) { return s(std::string(x ? x : "")); } + Fnv& i(int64_t v) { return raw(&v, sizeof v); } + Fnv& f(double v) { return raw(&v, sizeof v); } +}; +uint64_t graph_hash(const RadBuilder& b) { + Fnv f; + for (const RecOp& o : b.ops) { + f.s(o.op).i(o.resolved).i((int64_t)o.p.size()); + for (const RecParam& p : o.p) f.s(p.key).i(p.kind).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); + for (const auto* v : { &o.w, &o.reads, &o.writes }) { + f.i((int64_t)v->size()); + for (uint32_t x : *v) f.i(x); + } + } + for (const RecBuf& x : b.bufs) { + f.s(x.name).i(x.d.dtype).i(x.d.rank).i(x.d.kind).i(x.d.domain).i(x.d.kv).s(x.d.derive); + for (uint32_t d = 0; d < x.d.rank; ++d) f.i(x.d.shape[d]); + } + for (const RecWeight& w : b.weights) { + f.s(w.name).i(w.d.dtype).i(w.d.rank).i(w.d.shard).i(w.d.access).i(w.d.group.layer) + .i(w.d.group.expert).s(w.d.source).s(w.d.planes).i(w.d.n_row_parts).i(w.span_lo) + .i(w.span_hi).i(w.n_part_spans); + for (uint32_t d = 0; d < w.d.rank; ++d) f.i(w.d.shape[d]); + } + for (const RecKV& g : b.kv_groups) + f.s(g.name).i(g.d.kind).i(g.d.dtype).i(g.d.window).i(g.d.n_head_kv).i(g.d.head_dim) + .i(g.d.state_dim[0]).i(g.d.state_dim[1]).i(g.d.conv_width).i(g.zero); + for (const auto& [l, g] : b.binds) f.i(l).i(g); + for (const RecMap& m : b.maps) { + f.s(m.declared).i(m.mode).i(m.concat_dim); + for (const auto& x : m.src) f.s(x); + } + f.i(b.logits).i(b.pooled).s(b.drafter_name).i(b.drafter.kind).i(b.drafter.depth) + .i(b.drafter.block).i(b.drafter.proposal).i(b.drafter.mask_token).i(b.drafter_shared) + .s(b.encoder_name).s(b.audio_encoder_name).s(b.generator_name); + for (rad_buf x : b.concurrent) f.i(x); + return f.h; +} + +/* What a step issued, as a fingerprint: each launch's op (by name and declared parameters), row + * count and lane, every operand by kind, buffer or weight name, offset and extent, a raw operand + * by the batch array and element it points at, and every lane join. */ +uint64_t issue_hash(const RadBuilder& b, const std::vector>& v, + const std::vector& kits) { + Fnv f; + auto raw_at = [&](const void* p) { + if (!p) { f.i(-1); return; } + if (const rad_buf h = fake_buf_of(p, b.bufs.size())) { + f.i(1).s(b.bufs[h - 1].name) + .i((int64_t)((uintptr_t)p - (uintptr_t)rad_buf_ptr(nullptr, h))); + return; + } + for (size_t k = 0; k < kits.size(); ++k) { + const Kit& t = *kits[k]; + const std::vector* arrays[] = { &t.tok, &t.pos, &t.cu, &t.ctxl, &t.qlen, + &t.out, &t.nacc, &t.dout, &t.slot, &t.table, + &t.used, &t.sidx }; + for (size_t a = 0; a < sizeof arrays / sizeof arrays[0]; ++a) { + const std::vector& x = *arrays[a]; + const int32_t* q = (const int32_t*)p; + if (!x.empty() && q >= x.data() && q < x.data() + x.size()) { + f.i(2).i((int64_t)a).i((int64_t)(q - x.data())); + return; + } + } + } + f.i(3); + }; + for (const auto& c : v) { + f.i((int64_t)c->issues.size()); + for (const RecIssue& r : c->issues) { + const RecOp* o = b.op_of(r.op); + f.s(o ? o->op : ""); + if (o) + for (const RecParam& p : o->p) f.s(p.key).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); + f.i(r.n).i(r.lane).i((int64_t)r.opd.size()); + for (const RadOperand& d : r.opd) { + f.i(d.kind).i(d.dtype).i(d.offset).i(d.rows).i(d.cols); + if (d.kind == RAD_OPK_BUF) + f.s(d.handle && d.handle <= b.bufs.size() ? b.bufs[d.handle - 1].name : "?"); + else if (d.kind == RAD_OPK_WEIGHT || d.kind == RAD_OPK_WTAB) + f.s(d.handle && d.handle <= b.weights.size() ? b.weights[d.handle - 1].name + : "?"); + else if (d.kind == RAD_OPK_RAW) + raw_at(d.raw); + else + f.i(d.handle); + } + } + for (const RecJoin& j : c->joins) f.i((int64_t)j.at).i(j.from).i(j.to); + } + return f.h; +} + +/* The steps of the fingerprint: a 4096-row prefill after 4096 tokens of history (wider than a + * MoE pass), a mixed step, a decode step, and with a drafter a verify and its first passes. */ +uint64_t pinned_steps(RadBuilder& b, StepFn step, int rank, int world) { + const auto pf = kit(b, {}, { 4096 }, 4096); + const auto mx = kit(b, { 1, 1 }, { 2000 }, 3000); + const auto dc = kit(b, { 1, 1, 1 }, {}); + std::vector> all; + std::vector kits; + for (const Kit* k : { pf.get(), mx.get(), dc.get() }) { + auto v = run_passes(b, step, { k }, rank, world); + CHECK_PASSES(b, v); + for (auto& c : v) all.push_back(std::move(c)); + kits.push_back(k); + } + std::unique_ptr ver, his, r2; + if (b.drafter.kind == RAD_DRAFT_SERIAL) { + ver = kit(b, std::vector(3, 4), {}); + his = history_pass(b, *ver); + r2 = round_pass(b, 3, 2); + auto v = run_passes(b, step, { ver.get(), his.get(), r2.get() }, rank, world); + CHECK_PASSES(b, v); + for (auto& c : v) all.push_back(std::move(c)); + kits.push_back(ver.get()); kits.push_back(his.get()); kits.push_back(r2.get()); + } + return issue_hash(b, all, kits); +} + +} /* namespace */ + +#endif /* RAD_ARCH_FAKES_H */ diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index a3bd4457..ba7b07a6 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -10,457 +10,12 @@ */ #define RAD_ARCH_NO_EXPORTS 1 -#include "rad_test.h" +#include "arch_fakes.h" -#include "rad_builder.h" -#include "rad_device.h" -#include "rad_runtime.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include #include -/* ==================================================================== the recording builder */ -namespace { - -struct RecParam { - std::string key; - int kind = 0; - long long ival = 0, ihi = 0; - double dval = 0.0; - std::string sval; -}; - -struct RecWeight { - std::string name; - RadWeightDecl d{}; - /* The uneven slice this weight was handed (rad_weight_shard_span), in the container's - * unsharded units, so tests can check which checkpoint rows each rank reads. Even shards have - * `span_set` false. */ - bool span_set = false; - int64_t span_lo = 0, span_hi = 0; - /* rad_weight_shard_span_parts, recorded likewise. */ - int n_part_spans = 0; - int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; - int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; -}; -struct RecBuf { std::string name; RadBufDecl d{}; }; -struct RecOp { - std::string op; - std::vector p; - std::vector w; - std::vector reads, writes; - bool resolved = true; - bool uses_declared = false; /* rad_op_reads/writes were called */ -}; -struct RecMap { - std::string declared; - int mode = 0; - std::vector src; - int concat_dim = 0; -}; -struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; }; -struct RecIssue { - rad_op op = 0; - std::vector opd; - int64_t n = 0; - int lane = 0; /* the lane it was issued on (rad_lane) */ -}; -/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */ -struct RecJoin { size_t at = 0; int from = 0, to = 0; }; - -} /* namespace */ - -struct RadBuilder { - std::vector weights; - std::vector bufs; - std::vector ops; - std::vector maps; - std::vector kv_groups; - std::vector> binds; - std::vector notes; - - /* Ops the fake kernel hierarchy refuses, to drive the fused-op fallback; and ops no loaded - * library declares (rad_op_declared), as without an optional library. */ - std::set refuse; - std::set undeclared; - /* When set, the only ops any loaded library declares (a CPU-only engine's: libref's - * vocabulary); every other op is undeclared. */ - const std::set* vocab = nullptr; - std::vector asked_undeclared; /* what a real engine would refuse */ - bool declared(const std::string& op) const { - return vocab ? vocab->count(op) != 0 : undeclared.count(op) == 0; - } - int64_t kv_block = 16; - - /* The buffer the plugin named as this step's logits (rad_declare_logits), or as its pooled - * output (rad_declare_pooled). */ - rad_buf logits = 0; - rad_buf pooled = 0; - - /* The draft head's declaration (rad_declare_drafter), and whether it keeps no cache of its - * own (rad_drafter_shared_kv) and at which rotary offset. */ - RadDrafterDecl drafter{}; - std::string drafter_name; - bool drafter_shared = false; - int drafter_pos = -1; - - /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ - std::vector concurrent; - - /* The vision and audio encoder declarations (rad_declare_encoder), if any. */ - RadEncoderDecl encoder{}; - std::string encoder_name; - RadEncoderDecl audio_encoder{}; - std::string audio_encoder_name; - - /* The image generator's declaration (rad_declare_generator), if any. */ - RadGeneratorDecl generator{}; - std::string generator_name; - - /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as - * (native, from, to, from_lo, from_hi, to_lo). */ - std::vector> lora_roots; - struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; - std::vector lora_aliases; - - /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty - * means no model, so every weight is plain in its declared dtype. */ - std::vector> encs; - - const RecOp* op_of(rad_op h) const { return h ? &ops[h - 1] : nullptr; } -}; - -struct RadCtx { - RadBuilder* b = nullptr; - const RadBatch* batch = nullptr; - int rank = 0; - int world = 1; - std::vector issues; - std::vector routed_layers; - std::string step_fail; - int lane = 0; /* where the next issue goes */ - std::vector joins; - /* Device copies into a buffer (rad_memcpy_async to a rad_buf_ptr address): the buffer and the - * issue number the copy came before. The step lint counts each as a write there. */ - std::vector> copies; -}; - -/* -------------------------------------------------------------------- the declare-side ABI */ -extern "C" rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d) { - b->weights.push_back({name, *d}); - return (rad_weight)b->weights.size(); -} - -extern "C" int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t*, - uint32_t*) { - for (const auto& [key, e] : b->encs) - if (source && std::strstr(source, key.c_str())) { *out = e; return RAD_OK; } - return RAD_E_NOTFOUND; -} -extern "C" rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d) { - b->bufs.push_back({name, *d}); - return (rad_buf)b->bufs.size(); -} - -extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, - const rad_weight* weights, int n_weights) { - if (!b->declared(op)) { - b->asked_undeclared.push_back(op); - return RAD_NULL_HANDLE; - } - RecOp r; - r.op = op; - for (int i = 0; i < n_params; ++i) { - RecParam p; - p.key = params[i].key ? params[i].key : ""; - p.kind = params[i].kind; - p.ival = params[i].ival; - p.ihi = params[i].ihi; - p.dval = params[i].dval; - p.sval = params[i].sval ? params[i].sval : ""; - r.p.push_back(p); - } - for (int i = 0; i < n_weights; ++i) r.w.push_back(weights[i]); - r.resolved = b->refuse.count(r.op) == 0; - b->ops.push_back(r); - /* Declare always completes. An unresolved op is RAD_NULL_HANDLE, an error only if the plugin - * issues it (rad_builder.h). */ - return r.resolved ? (rad_op)b->ops.size() : RAD_NULL_HANDLE; -} - -extern "C" int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { - if (!h) return RAD_E_INVAL; - RecOp& r = b->ops[h - 1]; - r.uses_declared = true; - for (int i = 0; i < n; ++i) r.reads.push_back(bufs[i]); - return RAD_OK; -} - -extern "C" int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { - if (!h) return RAD_E_INVAL; - RecOp& r = b->ops[h - 1]; - r.uses_declared = true; - for (int i = 0; i < n; ++i) r.writes.push_back(bufs[i]); - return RAD_OK; -} - -extern "C" int rad_op_resolved(RadBuilder* b, rad_op h) { - return h != RAD_NULL_HANDLE && b->ops[h - 1].resolved; -} - -extern "C" int rad_op_declared(RadBuilder* b, const char* op) { - return op && b->declared(op); -} - -extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, - const RadKVGroupDecl* d) { - b->kv_groups.push_back({name, *d, false}); - return (rad_kvgroup)b->kv_groups.size(); -} - -extern "C" int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { (void)g; return b->kv_block; } - -extern "C" int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { - b->binds.push_back({layer, g}); - return RAD_OK; -} - -extern "C" int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { - RecMap r; - r.declared = m->declared; - r.mode = m->mode; - r.concat_dim = m->concat_dim; - for (int i = 0; i < m->n_src; ++i) r.src.push_back(m->src[i]); - b->maps.push_back(r); - return RAD_OK; -} - -extern "C" void rad_note(RadBuilder* b, const char* fmt, ...) { - char buf[512]; - va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); - b->notes.push_back(buf); -} - -/* The buffer the core samples from, recorded so tests can assert the plugin named the narrow - * one: [max_tok, n_vocab] is legal but 8 GiB at this vocabulary. */ -extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { - if (!b || !logits) return RAD_E_INVAL; - b->logits = logits; - return RAD_OK; -} - -/* An embedding program names its pooled output instead of logits; a program declares one. */ -extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { - if (!b || !pooled || b->logits) return RAD_E_INVAL; - b->pooled = pooled; - return RAD_OK; -} - -/* An image generator's declaration, recorded whole; it too excludes logits. */ -extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { - if (!b || !d || !d->image_out || b->logits || b->pooled) return RAD_E_INVAL; - b->generator = *d; - b->generator_name = d->name ? d->name : ""; - return RAD_OK; -} - -/* Recorded: a generator's adapter key names. */ -extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { - if (!b || !native || !*native) return RAD_E_INVAL; - b->lora_roots.push_back({ native, spellings ? spellings : "" }); - return RAD_OK; -} -extern "C" int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, - int64_t from_lo, int64_t from_hi, int64_t to_lo) { - if (!b || !native || !from || !to) return RAD_E_INVAL; - b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); - return RAD_OK; -} - -/* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ -extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { - if (!b || !buf) return RAD_E_INVAL; - b->concurrent.push_back(buf); - return RAD_OK; -} -extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { - if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; - if (lo < 0 || hi <= lo) return RAD_E_INVAL; - /* The real Builder also checks the declared extent against hi-lo (core/build/rad_builder.cpp); - * the fake only records the span for tests. */ - RecWeight& rw = b->weights[w - 1]; - rw.span_set = true; - rw.span_lo = lo; - rw.span_hi = hi; - return RAD_OK; -} -extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, - const int64_t* hi, const int64_t* total, int n) { - if (!b || w == 0 || w > b->weights.size() || !lo || !hi || !total) return RAD_E_INVAL; - if (n < 2 || n > RAD_MAX_ROW_PARTS) return RAD_E_INVAL; - RecWeight& rw = b->weights[w - 1]; - if (rw.d.n_row_parts != n) return RAD_E_INVAL; - for (int g = 0; g < n; ++g) { - if (lo[g] < 0 || hi[g] <= lo[g] || hi[g] > total[g]) return RAD_E_INVAL; - if (rw.d.row_parts[g] != hi[g] - lo[g]) return RAD_E_SHAPE; - rw.part_lo[g] = lo[g]; - rw.part_hi[g] = hi[g]; - rw.part_total[g] = total[g]; - } - rw.n_part_spans = n; - return RAD_OK; -} -extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { - if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; - b->kv_groups[g - 1].zero = true; - return RAD_OK; -} -extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { - if (!b || !d) return RAD_E_INVAL; - b->drafter = *d; - b->drafter_name = d->name ? d->name : ""; - return RAD_OK; -} -extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { - if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1)) - return RAD_E_STATE; - b->drafter_shared = true; - b->drafter_pos = pos_offset; - return RAD_OK; -} -extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { - if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; - if (d->modalities == RAD_MM_AUDIO) { - b->audio_encoder = *d; - b->audio_encoder_name = d->name; - return RAD_OK; - } - b->encoder = *d; - b->encoder_name = d->name; - return RAD_OK; -} - -/* -------------------------------------------------------------------- model metadata */ -extern "C" long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return atoll(m->kv_val[i]); - return dflt; -} -extern "C" double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return atof(m->kv_val[i]); - return dflt; -} -extern "C" const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return m->kv_val[i]; - return dflt; -} - -/* -------------------------------------------------------------------- the run-phase ABI */ -extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) { - RecIssue r; - r.op = op; - r.n = n; - for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]); - r.lane = c->lane; - c->issues.push_back(r); - return RAD_OK; -} -/* The second lane, recorded: each issue's lane, and each join's position among the issues. */ -extern "C" int rad_lane(RadCtx* c, int lane) { - if (lane != 0 && lane != 1) return RAD_E_INVAL; - c->lane = lane; - return RAD_OK; -} -extern "C" int rad_lane_join(RadCtx* c, int from, int to) { - if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; - c->joins.push_back({ c->issues.size(), from, to }); - return RAD_OK; -} -/* A block that refuses the batch records the reason for the tests. */ -extern "C" int rad_step_fail(RadCtx* c, const char* what) { - c->step_fail = what ? what : ""; - return RAD_E_SHAPE; -} -extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; } -extern "C" int rad_rank(RadCtx* c) { return c->rank; } -extern "C" int rad_world_size(RadCtx* c) { return c->world; } -/* The context itself, so a copy issued on the step's stream is recorded in it (rad_memcpy_async). */ -extern "C" RadStream rad_stream(RadCtx* c) { return (RadStream)c; } -extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; } -extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { - (void)r; - c->routed_layers.push_back(layer); - return RAD_OK; -} -/* No card-side histogram here, so a router writes and reports its own buffer. */ -extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) { - (void)c; (void)layer; (void)n_expert; - return nullptr; -} -/* No prefetch here: the three calls are no-ops, as in a core without one. */ -extern "C" int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, - int64_t rows, int64_t n_embd) { - (void)c; (void)next; (void)h; (void)r0; (void)rows; (void)n_embd; - return RAD_OK; -} -extern "C" int rad_expert_prefetch_mark(RadCtx* c) { (void)c; return RAD_OK; } -extern "C" int rad_expert_prefetch_step(RadCtx* c, int layer) { (void)c; (void)layer; return RAD_OK; } -/* Never dereferenced: a plugin passes these through to rad_route_report or offsets one into a raw - * operand. Each handle gets its own 2^36-byte window above any user-space address, tagged by - * kind in the top bits, so the step lint can map a raw operand inside a buffer back to that buffer - * (fake_buf_of). */ -constexpr int kFakePtrShift = 36; -constexpr uintptr_t kFakeBufTag = (uintptr_t)1 << 61; -constexpr uintptr_t kFakeWeightTag = (uintptr_t)1 << 62; -extern "C" void* rad_weight_ptr(RadCtx* c, rad_weight w) { - (void)c; - return (void*)(kFakeWeightTag | (uintptr_t)w << kFakePtrShift); -} -extern "C" void* rad_buf_ptr(RadCtx* c, rad_buf b) { - (void)c; - return (void*)(kFakeBufTag | (uintptr_t)b << kFakePtrShift); -} -/* The buffer a raw operand points into, if it came from rad_buf_ptr; 0 otherwise. */ -static rad_buf fake_buf_of(const void* p, size_t n_bufs) { - const uintptr_t u = (uintptr_t)p; - if ((u & ~(kFakeBufTag - 1)) != kFakeBufTag) return 0; - const uintptr_t h = (u & (kFakeBufTag - 1)) >> kFakePtrShift; - return h >= 1 && h <= n_bufs ? (rad_buf)h : 0; -} -/* Pinned host memory a plugin fills itself (qwen4exp_fp8's piece bounds, the calibration tap's - * staging), as host memory; nothing else is handed out. */ -extern "C" void* rad_dev_alloc(int64_t bytes, int kind) { - return kind == RAD_MEM_HOST_PINNED && bytes > 0 ? std::calloc(1, (size_t)bytes) : nullptr; -} -extern "C" void rad_dev_free(void* p, int kind) { if (kind == RAD_MEM_HOST_PINNED) std::free(p); } -/* The device copies: nothing is copied. One into a buffer on a step's stream is recorded as a - * write of that buffer before the next issue (RadCtx::copies). */ -extern "C" int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) { - (void)src; (void)bytes; - RadCtx* c = (RadCtx*)s; - if (c && c->b) - if (const rad_buf h = fake_buf_of(dst, c->b->bufs.size())) - c->copies.push_back({ c->issues.size(), h }); - return RAD_OK; -} -extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) { - (void)dst; (void)value; (void)bytes; (void)s; - return RAD_OK; -} - /* ==================================================================== the plugin under test */ #include "../arch/qwen35_bf16/qwen35_bf16.cpp" /* The production architecture, for its sizing declare (RadBuildCtx::shape_probe). */ @@ -503,16 +58,6 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/qwenimage21/qwenimage21.cpp" /* Anima: a cross-attention generator conditioned through two tokenizers. */ #include "../arch/anima/anima.cpp" -/* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include "../arch/glm5next/glm5next.cpp" /* ==================================================================== fixtures and helpers */ namespace { @@ -635,101 +180,6 @@ RadModelMeta gemma4_draft_meta() { return m; } -RadBuildCtx build_ctx(int rank = 0, int world = 1) { - RadBuildCtx c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 256; - c.max_seqs = 8; - c.max_ctx = 32768; - c.scope = ""; - return c; -} - -/* The sampled rows (RadBatch::out_ids). The plugin skips the lm_head when n_out is zero (a chunk - * finishing no sequence), so a fake batch must set them or it silently tests the no-logits - * path. */ -static const int32_t kDecodeOut[] = { 0, 1, 2, 3 }; -static const int32_t kPrefillOut[] = { 31, 63 }; /* last token of each 32-token sequence */ - -RadBatch decode_batch() { - RadBatch b{}; - b.phase = RAD_PHASE_DECODE; - b.n_tok = 4; - b.n_seq = 4; - b.max_q_len = 1; - b.max_ctx_len = 100; - b.n_out = 4; - b.out_ids = kDecodeOut; - return b; -} - -RadBatch prefill_batch() { - RadBatch b{}; - b.phase = RAD_PHASE_PREFILL; - b.n_tok = 64; - b.n_seq = 2; - b.max_q_len = 32; - b.max_ctx_len = 32; - b.n_out = 2; - b.out_ids = kPrefillOut; - return b; -} - -/* --- small queries over the recorded graph --- */ -std::vector op_names(const RadBuilder& b) { - std::vector v; - for (const auto& o : b.ops) v.push_back(o.op); - return v; -} - -const RecOp* find_op(const RadBuilder& b, const std::string& name, int nth = 0) { - for (const auto& o : b.ops) - if (o.op == name && nth-- == 0) return &o; - return nullptr; -} - -int count_op(const RadBuilder& b, const std::string& name) { - int n = 0; - for (const auto& o : b.ops) if (o.op == name) ++n; - return n; -} - -const RecParam* param(const RecOp* o, const char* key) { - if (!o) return nullptr; - for (const auto& p : o->p) if (p.key == key) return &p; - return nullptr; -} - -long long pint(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->ival : -12345; -} - -double pflt(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->dval : -12345.0; -} - -std::string pstr(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->sval : std::string(""); -} - -const RecWeight* find_w(const RadBuilder& b, const std::string& name) { - for (const auto& w : b.weights) if (w.name == name) return &w; - return nullptr; -} - -const RecBuf* find_b(const RadBuilder& b, const std::string& name) { - for (const auto& x : b.bufs) if (x.name == name) return &x; - return nullptr; -} - -const RecMap* find_map(const RadBuilder& b, const std::string& declared) { - for (const auto& m : b.maps) if (m.declared == declared) return &m; - return nullptr; -} /* The gated attention layer's ops, listed once for every test. * * The fused qk_norm_rope_gate is not declared: its schema requires a precomputed cos/sin table @@ -793,416 +243,8 @@ std::vector program_ops(bool tp) { return v; } -std::string join(const std::vector& v) { - std::string s; - for (size_t i = 0; i < v.size(); ++i) { if (i) s += " "; s += v[i]; } - return s; -} - -std::vector issued_ops(const RadBuilder& b, const RadCtx& c) { - std::vector got; - for (const auto& i : c.issues) { - const RecOp* o = b.op_of(i.op); - got.push_back(o ? o->op : ""); - } - return got; -} - } /* namespace */ -/* ==================================================================== the step lint - * - * The buffer plan takes liveness from declaration order: a transient lives over the [first, last] - * op indices of its declared reads and writes, and two transients of one arena whose ranges are - * disjoint may share bytes (core/build/rad_bufplan.cpp). A step that issues ops in another order, - * or across passes of one engine step (trunk, drafter history, draft rounds), can write one buffer - * while another that shares its bytes still holds rows a later issue reads. The runtime refuses - * only an op outside a buffer's range, and only on the branch a real model runs, so the class is - * checked here for every recorded step. - * - * lint_step walks the issues of one engine step's passes in order and reports: - * alias a transient read whose last writer is followed, before the read, by a write of a - * transient of the same arena whose range is disjoint from its own; - * undeclared an op issued outside the declared range of a buffer operand - * (core/runtime/issue.cpp refuses this); - * span an operand that reaches past its buffer or weight, rows and columns applied as - * issue.cpp applies them; - * null op an issue of RAD_NULL_HANDLE (a fused op that did not resolve, with no chain); - * unwritten a transient read before any issue, or device copy into it, of the step wrote it; - * kv a cache operand naming a group or layer no rad_bind_layer_kv bound, or a group - * this rank declared zero; - * strided a GEMM whose input is a column slice narrower than its buffer (libr4d's GEMMs - * read whole rows and refuse it). */ -namespace { - -/* One buffer's planned lifetime. `planned` is false for a buffer live over the whole program - * (PERSIST, DERIVED, rad_buf_concurrent, or no declared use), which shares bytes with nothing. */ -struct Live { - int32_t lo = 0, hi = 0; - bool planned = false; - bool transient = false; - int domain = RAD_DOMAIN_DEVICE; -}; - -/* Liveness by the rule of Builder::finish_buffer_liveness (core/build/rad_builder.cpp). Op handle - * h is op index h: the real builder keeps a sentinel at index 0, and the fake hands out ops in - * declaration order from 1. */ -std::vector liveness(const RadBuilder& b) { - const size_t nb = b.bufs.size(); - const int32_t last_op = (int32_t)b.ops.size(); - std::vector first(nb + 1, -1), last(nb + 1, -1); - for (size_t i = 0; i < b.ops.size(); ++i) - for (const std::vector* v : { &b.ops[i].reads, &b.ops[i].writes }) - for (rad_buf h : *v) { - if (h == 0 || h > nb) continue; - if (first[h] < 0) first[h] = (int32_t)(i + 1); - last[h] = (int32_t)(i + 1); - } - std::set conc(b.concurrent.begin(), b.concurrent.end()); - std::vector L(nb + 1); - for (size_t h = 1; h <= nb; ++h) { - const RadBufDecl& d = b.bufs[h - 1].d; - Live& l = L[h]; - l.transient = d.kind == RAD_BUF_TRANSIENT; - l.domain = d.domain; - if (!l.transient || conc.count((rad_buf)h) || first[h] < 0) { - l.lo = 0; - l.hi = last_op; - continue; - } - l.planned = true; - l.lo = first[h]; - l.hi = last[h]; - if ((rad_buf)h == b.logits || (rad_buf)h == b.pooled) l.hi = last_op; - } - return L; -} - -/* Whether operand `o` stays inside a buffer or weight of `shape` (packed strides, rows and cols - * applied as issue.cpp applies them), as issue.cpp's operand_fits decides. */ -bool operand_fits(const int64_t* shape, uint32_t rank, const RadOperand& o) { - if (o.offset < 0) return false; - int64_t sh[RAD_MAX_RANK] = {}, st[RAD_MAX_RANK] = {}; - int64_t numel = 1; - for (uint32_t d = 0; d < rank; ++d) { sh[d] = shape[d]; numel *= shape[d]; } - int64_t s = 1; - for (int d = (int)rank - 1; d >= 0; --d) { st[d] = s; s *= sh[d]; } - if (o.rows > 0 && rank >= 1) sh[0] = o.rows; - if (o.cols > 0 && rank >= 1) sh[rank - 1] = o.cols; - int64_t span = o.offset; - for (uint32_t d = 0; d < rank; ++d) { - if (sh[d] <= 0) return true; - span += (sh[d] - 1) * st[d]; - } - return span < numel; -} - -bool in(const std::vector& v, rad_buf h) { - return std::find(v.begin(), v.end(), h) != v.end(); -} - -std::vector lint_step(const RadBuilder& b, const std::vector& passes) { - std::vector bad; - const std::vector L = liveness(b); - const size_t nb = b.bufs.size(); - auto name = [&](rad_buf h) { return h && h <= nb ? b.bufs[h - 1].name : std::string("?"); }; - auto shares = [&](rad_buf x, rad_buf y) { - const Live& p = L[x]; - const Live& q = L[y]; - return p.planned && q.planned && p.domain == q.domain && (p.hi < q.lo || q.hi < p.lo); - }; - std::set> bound(b.binds.begin(), b.binds.end()); - std::vector last_write(nb + 1, -1); - int64_t pos = 0; - char where[96]; - for (size_t pi = 0; pi < passes.size(); ++pi) { - const RadCtx& c = *passes[pi]; - size_t next_copy = 0; - for (size_t ii = 0; ii < c.issues.size(); ++ii, ++pos) { - for (; next_copy < c.copies.size() && c.copies[next_copy].first <= ii; ++next_copy) - last_write[c.copies[next_copy].second] = pos; - const RecIssue& is = c.issues[ii]; - const RecOp* o = b.op_of(is.op); - std::snprintf(where, sizeof where, "pass %zu issue %zu (%s, op %u)", pi, ii, - o ? o->op.c_str() : "", (unsigned)is.op); - if (!o) { bad.push_back(std::string(where) + ": null op issued"); continue; } - std::vector rd, wr; - for (size_t k = 0; k < is.opd.size(); ++k) { - const RadOperand& od = is.opd[k]; - const std::string at = std::string(where) + " operand " + std::to_string(k); - if (od.kind == RAD_OPK_BUF) { - const rad_buf h = od.handle; - if (h == 0 || h > nb) { - bad.push_back(at + ": buffer handle out of range"); - continue; - } - const RadBufDecl& d = b.bufs[h - 1].d; - if (!operand_fits(d.shape, d.rank, od)) - bad.push_back(at + ": span past '" + name(h) + "' (offset " + - std::to_string(od.offset) + ", rows " + - std::to_string(od.rows) + ", cols " + - std::to_string(od.cols) + ")"); - const Live& l = L[h]; - if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) - bad.push_back(at + ": undeclared use of '" + name(h) + "' (planned ops " + - std::to_string(l.lo) + ".." + std::to_string(l.hi) + ")"); - const bool r = in(o->reads, h), w = in(o->writes, h); - if (r || !w) rd.push_back(h); - if (w || !r) wr.push_back(h); - /* A GEMM's input is read as contiguous rows: libr4d refuses a column slice - * narrower than its buffer. */ - const int64_t width = d.rank ? d.shape[d.rank - 1] : 0; - if (k == 0 && o->op.rfind("gemm_nt", 0) == 0 && od.cols > 0 && - (od.cols != width || od.offset % width)) - bad.push_back(at + ": " + o->op + " reads " + std::to_string(od.cols) + - " of " + std::to_string(width) + " columns of '" + name(h) + - "' as its input, which is not contiguous"); - } else if (od.kind == RAD_OPK_WEIGHT) { - const uint32_t h = od.handle; - if (h == 0 || h > b.weights.size()) { - bad.push_back(at + ": weight handle out of range"); - continue; - } - const RadWeightDecl& d = b.weights[h - 1].d; - if ((od.offset || od.rows > 0 || od.cols > 0) && - !operand_fits(d.shape, d.rank, od)) - bad.push_back(at + ": span past weight '" + b.weights[h - 1].name + "'"); - } else if (od.kind == RAD_OPK_WTAB) { - if (od.handle == 0 || od.rows <= 0 || od.offset || od.cols || - (size_t)(od.handle + od.rows - 1) > b.weights.size()) - bad.push_back(at + ": weight table out of range"); - } else if (od.kind == RAD_OPK_KV) { - const rad_kvgroup g = od.handle; - if (g == 0 || g > b.kv_groups.size()) - bad.push_back(at + ": KV group handle out of range"); - else if (b.kv_groups[g - 1].zero) - bad.push_back(at + ": KV group '" + b.kv_groups[g - 1].name + - "' is declared zero on this rank"); - else if (!bound.count({ (int)od.offset, g })) - bad.push_back(at + ": layer " + std::to_string(od.offset) + - " is not bound to KV group '" + b.kv_groups[g - 1].name + - "'"); - } else if (od.kind == RAD_OPK_RAW) { - if (od.offset && od.dtype == RAD_DT_INVALID) - bad.push_back(at + ": raw operand with an offset and no dtype"); - /* A pointer into a buffer (rad_buf_ptr) is that buffer to the plan, so it is - * classified by the op's declared sets like a buffer operand. */ - if (const rad_buf h = fake_buf_of(od.raw, nb)) { - const Live& l = L[h]; - if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) - bad.push_back(at + ": undeclared use of '" + name(h) + - "' through a raw pointer"); - const bool r = in(o->reads, h), w = in(o->writes, h); - if (r || !w) rd.push_back(h); - if (w || !r) wr.push_back(h); - } - } - } - for (rad_buf h : rd) { - if (!L[h].transient) continue; - const int64_t w = last_write[h]; - if (w < 0) { - bad.push_back(std::string(where) + ": reads '" + name(h) + - "' before any issue of this step wrote it"); - continue; - } - for (size_t x = 1; x <= nb; ++x) - if (x != h && last_write[x] > w && shares(h, (rad_buf)x)) - bad.push_back(std::string(where) + ": reads '" + name(h) + "' (ops " + - std::to_string(L[h].lo) + ".." + std::to_string(L[h].hi) + - ") after a write of '" + name((rad_buf)x) + "' (ops " + - std::to_string(L[x].lo) + ".." + std::to_string(L[x].hi) + - "), which may share its bytes"); - } - for (rad_buf h : wr) last_write[h] = pos; - } - } - return bad; -} - -/* ---------------------------------------------------------------- whole step batches - * - * A batch as the core builds it: every per-token and per-sequence array filled and a group batch - * for every KV group the builder declared, so a plugin's step can take any path. Decode sequences - * come first (RadBatch::n_seq_decode); each `dq` entry is a decode sequence's query length (1, or - * 1 + n_spec for a verify), each `pq` entry a prefill chunk. Every decode row is sampled (a verify - * needs logits at each row) and a chunk's last row; a chunk continues `prefill_ctx` tokens of - * history. */ -struct Kit { - std::vector tok, pos, cu, ctxl, qlen, out, nacc, dout; - std::vector slot, table, used, sidx; - std::vector kv; - RadBatch b{}; -}; - -std::unique_ptr kit(const RadBuilder& bld, const std::vector& dq, - const std::vector& pq, int32_t prefill_ctx = 0) { - auto k = std::make_unique(); - const int64_t nd = (int64_t)dq.size(), ns = nd + (int64_t)pq.size(); - std::vector ql(dq); - ql.insert(ql.end(), pq.begin(), pq.end()); - int64_t T = 0, max_q = 0, max_ctx = 0, td = 0, mqd = 0, mqp = 0; - k->cu.push_back(0); - for (int64_t s = 0; s < ns; ++s) { - const bool dec = s < nd; - const int32_t ctx = dec ? (int32_t)(40 + 7 * s) : prefill_ctx; - for (int i = 0; i < ql[(size_t)s]; ++i) { - k->tok.push_back((int32_t)(3 + (T + i) % 97)); - k->pos.push_back(ctx + i); - if (dec || i + 1 == ql[(size_t)s]) k->out.push_back((int32_t)(T + i)); - } - T += ql[(size_t)s]; - k->cu.push_back((int32_t)T); - k->ctxl.push_back(ctx); - k->qlen.push_back(ql[(size_t)s]); - k->nacc.push_back(1); - k->dout.push_back((int32_t)T - 1); - max_q = std::max(max_q, ql[(size_t)s]); - max_ctx = std::max(max_ctx, ctx + ql[(size_t)s]); - if (dec) { td += ql[(size_t)s]; mqd = std::max(mqd, ql[(size_t)s]); } - else mqp = std::max(mqp, ql[(size_t)s]); - } - k->tok.resize((size_t)T + 64, 5); /* room for a following prompt (RadBatch::n_ahead) */ - const int64_t pitch = 16; - for (int64_t i = 0; i < T; ++i) k->slot.push_back((int32_t)i); - for (int64_t i = 0; i < ns * pitch; ++i) k->table.push_back((int32_t)i); - for (int64_t s = 0; s < ns; ++s) { - k->used.push_back(k->ctxl[(size_t)s] + k->qlen[(size_t)s]); - k->sidx.push_back((int32_t)s); - } - for (size_t g = 0; g < bld.kv_groups.size(); ++g) { - RadKVGroupBatch gb{}; - gb.group = (rad_kvgroup)(g + 1); - gb.slot_mapping = k->slot.data(); - gb.block_table = k->table.data(); - gb.block_table_pitch = pitch; - gb.seqused = k->used.data(); - gb.state_index = k->sidx.data(); - gb.state_index_pitch = 1; - gb.block_size = bld.kv_block; - gb.max_blocks = pitch; - k->kv.push_back(gb); - } - RadBatch& b = k->b; - b.phase = pq.empty() ? RAD_PHASE_DECODE : dq.empty() ? RAD_PHASE_PREFILL : RAD_PHASE_MIXED; - b.n_tok = T; - b.n_seq = ns; - b.token_ids = k->tok.data(); - b.positions = k->pos.data(); - b.cu_seqlens = k->cu.data(); - b.n_out = (int64_t)k->out.size(); - b.out_ids = k->out.data(); - b.q_lens = k->qlen.data(); - b.ctx_lens = k->ctxl.data(); - b.max_q_len = (int32_t)max_q; - b.max_ctx_len = (int32_t)max_ctx; - b.n_kv_groups = (int)k->kv.size(); - b.kv = k->kv.data(); - b.n_spec = mqd > 1 ? (int)(mqd - 1) : 0; - b.num_accepted = k->nacc.data(); - b.n_seq_decode = nd; - b.n_tok_decode = td; - b.max_q_len_decode = (int32_t)mqd; - b.max_q_len_prefill = (int32_t)mqp; - return k; -} - -/* The draft passes the core stages for a step of `n_seq` sequences. - * - * A serial head's history pass (draft_pass -1) covers every row the trunk step had and carries - * round 1 on each sequence's last row; round r (2..depth) is one row a sequence. A block - * drafter's context pass (-1) covers the trunk's rows; its query pass (1) is `block` rows a - * sequence, the anchor first, and samples the `steps` rows after it (RadDrafterDecl::block). */ -std::unique_ptr history_pass(const RadBuilder& bld, const Kit& trunk) { - std::vector rows; - for (int64_t s = 0; s < trunk.b.n_seq; ++s) rows.push_back(trunk.qlen[(size_t)s]); - auto k = kit(bld, rows, {}); - k->b.draft_pass = -1; - k->out.clear(); - for (int64_t i = 0; i < k->b.n_tok; ++i) k->out.push_back((int32_t)i); - k->b.out_ids = k->out.data(); - k->b.n_out = k->b.n_tok; - k->b.n_draft_out = k->b.n_seq; - k->b.draft_out_ids = k->dout.data(); - return k; -} -std::unique_ptr round_pass(const RadBuilder& bld, int64_t n_seq, int r) { - auto k = kit(bld, std::vector((size_t)n_seq, 1), {}); - k->b.draft_pass = r; - return k; -} -std::unique_ptr context_pass(const RadBuilder& bld, const Kit& trunk) { - auto k = history_pass(bld, trunk); - k->b.n_draft_out = 0; - k->b.draft_out_ids = nullptr; - return k; -} -std::unique_ptr query_pass(const RadBuilder& bld, int64_t n_seq, int64_t block, - int64_t steps) { - auto k = kit(bld, std::vector((size_t)n_seq, (int)block), {}); - k->b.draft_pass = 1; - k->out.clear(); - for (int64_t s = 0; s < n_seq; ++s) - for (int64_t i = 0; i < steps; ++i) - k->out.push_back((int32_t)(s * block + block - steps + i)); - k->b.out_ids = k->out.data(); - k->b.n_out = (int64_t)k->out.size(); - return k; -} - -using StepFn = void (*)(RadCtx*, const RadBatch*); - -/* Runs one engine step's passes in order, each on a context of its own. */ -std::vector> run_passes(RadBuilder& b, StepFn step, - const std::vector& passes, - int rank = 0, int world = 1) { - std::vector> out; - for (const Kit* k : passes) { - out.push_back(std::make_unique()); - RadCtx& c = *out.back(); - c.b = &b; - c.batch = &k->b; - c.rank = rank; - c.world = world; - step(&c, &k->b); - } - return out; -} - -std::vector view(const std::vector>& v) { - std::vector p; - for (const auto& c : v) p.push_back(c.get()); - return p; -} - -/* The lint as a check: every finding is printed, and the step passes only with none. */ -size_t report_lint(const std::vector& f) { - for (size_t i = 0; i < f.size() && i < 12; ++i) fprintf(stderr, " lint: %s\n", f[i].c_str()); - if (f.size() > 12) fprintf(stderr, " lint: ... %zu more\n", f.size() - 12); - return f.size(); -} - -/* Every pass of one engine step ran without a step failure. */ -bool steps_ok(const std::vector>& v) { - bool ok = true; - for (size_t i = 0; i < v.size(); ++i) - if (!v[i]->step_fail.empty()) { - fprintf(stderr, " pass %zu failed: %s\n", i, v[i]->step_fail.c_str()); - ok = false; - } - return ok; -} - -} /* namespace */ - -#define CHECK_LINT(b, ...) CHECK_EQ(report_lint(lint_step((b), { __VA_ARGS__ })), (size_t)0) -/* The passes of one engine step (run_passes): none failed and the lint is clean over them. */ -#define CHECK_PASSES(b, v) \ - do { \ - CHECK(steps_ok(v)); \ - CHECK_EQ(report_lint(lint_step((b), view(v))), (size_t)0); \ - } while (0) - /* ==================================================================== tests */ TEST(declare_is_a_qwen35_trunk) { @@ -2331,1144 +1373,6 @@ TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) { CHECK(!p.layers[0].hc_mix.mix_e4m3); } -TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residual_destination) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - ManifoldConn::Config cfg; - ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", - "model.layers.3.hc_attn_base" }; - ManifoldConn::Wire w; - w.h = decl_b(&b, "h", RAD_BF16, { 32, 16384 }); - w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); - w.y = decl_b(&b, "y", RAD_BF16, { 32, 4096 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16384 }); - w.post = decl_b(&b, "post", RAD_F32, { 32, 4 }); - w.comb = decl_b(&b, "comb", RAD_F32, { 32, 16 }); - ManifoldConn conn; - REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)3); - CHECK_EQ(b.weights[0].d.shape[0], 24); - CHECK_EQ(b.weights[0].d.shape[1], 16384); - CHECK_EQ(b.weights[1].d.shape[0], 3); - CHECK_EQ(b.weights[2].d.shape[0], 24); - for (const auto& weight : b.weights) { - CHECK_EQ(weight.d.dtype, RAD_F32); - CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); - } - CHECK(b.ops[conn.op_pre - 1].reads == std::vector({ w.h })); - CHECK(b.ops[conn.op_pre - 1].writes == std::vector({ w.x, w.post, w.comb })); - CHECK(b.ops[conn.op_post - 1].reads == std::vector({ w.y, w.h, w.post, w.comb })); - CHECK(b.ops[conn.op_post - 1].writes == std::vector({ w.out })); - RadCtx ctx; - conn.read(&ctx, 4); - conn.write(&ctx, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, conn.op_pre); - CHECK_EQ(ctx.issues[1].op, conn.op_post); - CHECK_EQ(ctx.issues[0].n, 4); - CHECK_EQ(ctx.issues[1].n, 4); - REQUIRE_EQ(ctx.issues[0].opd.size(), (size_t)7); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); - const rad_weight coefficients[] = { conn.w_fn, conn.w_scale, conn.w_base }; - for (int i = 0; i < 3; ++i) { - CHECK_EQ(ctx.issues[0].opd[i + 1].kind, RAD_OPK_WEIGHT); - CHECK_EQ(ctx.issues[0].opd[i + 1].handle, coefficients[i]); - } - CHECK_EQ(ctx.issues[0].opd[4].handle, w.x); - CHECK_EQ(ctx.issues[0].opd[5].handle, w.post); - CHECK_EQ(ctx.issues[0].opd[6].handle, w.comb); - REQUIRE_EQ(ctx.issues[1].opd.size(), (size_t)5); - const rad_buf expected[] = { w.y, w.h, w.post, w.comb, w.out }; - for (int i = 0; i < 5; ++i) { - CHECK_EQ(ctx.issues[1].opd[i].handle, expected[i]); - CHECK_EQ(ctx.issues[1].opd[i].rows, 4); - } - auto invalid = w; - invalid.out = w.h; - ManifoldConn refused; - CHECK_EQ(refused.declare(&b, nm, g, 3, "bad", cfg, invalid, src), RAD_E_INVAL); -} - -TEST(manifold_read_splits_its_projection_by_chunks_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; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 512; - g.world = world; - g.rank = rank; - ManifoldConn::Config cfg; - ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", - "model.layers.3.hc_attn_base" }; - ManifoldConn::Wire w; - w.h = decl_b(&b, "h", RAD_BF16, { 512, 16384 }); - w.x = decl_b(&b, "x", RAD_BF16, { 512, 4096 }); - w.y = decl_b(&b, "y", RAD_BF16, { 512, 4096 }); - w.out = decl_b(&b, "out", RAD_BF16, { 512, 16384 }); - w.post = decl_b(&b, "post", RAD_F32, { 512, 4 }); - w.comb = decl_b(&b, "comb", RAD_F32, { 512, 16 }); - ManifoldConn conn; - REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); - const bool split = world > 1; - const int64_t mine = 8 / world; - CHECK_EQ(count_op(b, "mhc_pre"), 1); - CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 1 : 0); - CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); - CHECK_EQ(count_op(b, "mhc_pre_finish"), split ? 1 : 0); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); - if (split) { - const RecOp* part = find_op(b, "mhc_pre_partial"); - const RecOp* gather = find_op(b, "all_gather"); - const RecOp* finish = find_op(b, "mhc_pre_finish"); - REQUIRE(part && gather && finish); - CHECK_EQ(pint(part, "chunk"), 2048); - CHECK_EQ(pint(part, "first"), rank * mine); - CHECK_EQ(pint(part, "chunks"), mine); - CHECK(part->w == std::vector({ conn.w_fn })); - CHECK(part->reads == std::vector({ w.h })); - CHECK(part->writes == std::vector({ conn.part })); - CHECK_EQ(pint(gather, "world_size"), world); - CHECK_EQ(pint(gather, "row"), mine * 28); - CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); - CHECK_EQ(param(gather, "numel")->ival, mine * 28); - CHECK_EQ(param(gather, "numel")->ihi, 512 * mine * 28); - CHECK_EQ(pstr(gather, "dtype"), "f32"); - CHECK(gather->reads == std::vector({ conn.part })); - CHECK(gather->writes == std::vector({ conn.parts })); - CHECK_EQ(pint(finish, "chunk"), 2048); - CHECK_EQ(pint(finish, "iterations"), 20); - CHECK(finish->w == std::vector({ conn.w_scale, conn.w_base })); - CHECK(finish->reads == std::vector({ conn.parts, w.h })); - CHECK(finish->writes == std::vector({ w.x, w.post, w.comb })); - CHECK_EQ(find_b(b, "blk.3.mhc_attn.parts")->d.shape[1], 8 * 28); - } - RadCtx ctx; - conn.read(&ctx, 300); - conn.read(&ctx, 255); - if (split) { - REQUIRE_EQ(ctx.issues.size(), (size_t)4); - CHECK_EQ(ctx.issues[0].op, conn.op_partial); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); - CHECK_EQ(ctx.issues[0].opd[0].rows, 300); - CHECK_EQ(ctx.issues[0].opd[1].handle, conn.w_fn); - CHECK_EQ(ctx.issues[0].opd[2].handle, conn.part); - CHECK_EQ(ctx.issues[1].op, conn.op_gather); - CHECK_EQ(ctx.issues[1].n, 300 * mine * 28); - CHECK_EQ(ctx.issues[1].opd[1].handle, conn.parts); - CHECK_EQ(ctx.issues[1].opd[1].rows, 300); - CHECK_EQ(ctx.issues[2].op, conn.op_finish); - REQUIRE_EQ(ctx.issues[2].opd.size(), (size_t)7); - const uint32_t expected[] = { conn.parts, w.h, conn.w_scale, conn.w_base, - w.x, w.post, w.comb }; - for (int i = 0; i < 7; ++i) CHECK_EQ(ctx.issues[2].opd[i].handle, expected[i]); - CHECK_EQ(ctx.issues[3].op, conn.op_pre); - } else { - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, conn.op_pre); - CHECK_EQ(ctx.issues[1].op, conn.op_pre); - } - } -} - -TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 128; - g.world = 4; - g.rank = rank; - GlmRouter::Config cfg; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 32, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 32, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 32, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)2); - for (const auto& weight : b.weights) { - CHECK_EQ(weight.d.dtype, RAD_F32); - CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); - } - CHECK_EQ(b.weights[0].d.shape[0], 288); - CHECK_EQ(b.weights[0].d.shape[1], 4096); - CHECK_EQ(b.ops[router.op_project - 1].op, std::string("gemm_nt_f32")); - CHECK_EQ(b.ops[router.op_select - 1].op, std::string("router_sigmoid_topk")); - RadCtx ctx; - router.step(&ctx, 7, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); - CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); - CHECK_EQ(ctx.issues[0].opd[0].rows, 4); - CHECK_EQ(ctx.issues[1].opd[1].handle, router.correction); - CHECK_EQ(ctx.issues[1].opd[2].handle, w.ids); - CHECK_EQ(ctx.issues[1].opd[3].handle, w.weights); - } -} - -TEST(glm_router_and_index_head_split_columns_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; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 512; - g.world = world; - g.rank = rank; - GlmRouter::Config cfg; - cfg.rows = 512; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 512, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 512, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 512, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 512, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - const bool split = world > 1; - const int64_t cols = 288 / world; - CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); - CHECK_EQ(count_op(b, "gemm_nt_f32"), split ? 2 : 1); - // The weight stays whole and replicated: decode keeps the unsplit projection. - CHECK_EQ(b.weights[0].d.shape[0], 288); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); - if (split) { - const RecOp* part = find_op(b, "gemm_nt_f32", 1); - const RecOp* gather = find_op(b, "all_gather"); - REQUIRE(part && gather); - CHECK_EQ(pint(part, "N"), cols); - CHECK_EQ(pint(part, "K"), 4096); - CHECK(part->w == std::vector({ router.projection })); - CHECK(part->reads == std::vector({ w.input })); - CHECK(part->writes == std::vector({ router.split.part })); - CHECK_EQ(pint(gather, "world_size"), world); - CHECK_EQ(pint(gather, "row"), cols); - CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); - CHECK_EQ(param(gather, "numel")->ival, cols); - CHECK_EQ(param(gather, "numel")->ihi, 512 * cols); - CHECK_EQ(pstr(gather, "dtype"), "f32"); - CHECK(gather->reads == std::vector({ router.split.part })); - CHECK(gather->writes == std::vector({ w.logits })); - } - RadCtx ctx; - router.step(&ctx, 7, 300, 7); - if (split) { - REQUIRE_EQ(ctx.issues.size(), (size_t)3); - CHECK_EQ(ctx.issues[0].op, router.split.op_part); - CHECK_EQ(ctx.issues[0].n, 300); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); - CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); - CHECK_EQ(ctx.issues[0].opd[0].rows, 300); - CHECK_EQ(ctx.issues[0].opd[1].kind, RAD_OPK_WEIGHT); - CHECK_EQ(ctx.issues[0].opd[1].handle, router.projection); - CHECK_EQ(ctx.issues[0].opd[1].offset, rank * cols * 4096); - CHECK_EQ(ctx.issues[0].opd[1].rows, cols); - CHECK_EQ(ctx.issues[0].opd[2].handle, router.split.part); - CHECK_EQ(ctx.issues[0].opd[2].rows, 300); - CHECK_EQ(ctx.issues[1].op, router.split.op_gather); - CHECK_EQ(ctx.issues[1].n, 300 * cols); - CHECK_EQ(ctx.issues[1].opd[0].handle, router.split.part); - CHECK_EQ(ctx.issues[1].opd[1].handle, w.logits); - CHECK_EQ(ctx.issues[1].opd[1].offset, 7 * 288); - CHECK_EQ(ctx.issues[1].opd[1].rows, 300); - CHECK_EQ(ctx.issues[2].op, router.op_select); - } else { - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, router.op_project); - } - ctx.issues.clear(); - router.step(&ctx, 0, 255); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, router.op_project); - } -} - -TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - 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); - MlaLatent::Config cfg; - MlaLatent::Wire w; - w.q = decl_b(&b, "q", RAD_BF16, { 32, 16, 256 }); - w.q_latent = decl_b(&b, "ql", RAD_BF16, { 32, 16, 512 }); - w.attn_latent = decl_b(&b, "al", RAD_BF16, { 32, 16, 512 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 256 }); - w.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); - w.length = decl_b(&b, "length", RAD_I32, { 32 }); - MlaLatent block; - REQUIRE_EQ( - block.declare(&b, nm, g, 3, kv, cfg, w, "model.layers.3.self_attn.kv_b_proj.weight"), - RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)1); - CHECK_EQ(b.weights[0].d.dtype, RAD_BF16); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[0].d.shape[0], 8192); - CHECK_EQ(b.weights[0].d.shape[1], 512); - RadCtx ctx; - block.step(&ctx, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)3); - CHECK_EQ(b.ops[ctx.issues[0].op - 1].op, std::string("mla_project")); - CHECK_EQ(b.ops[ctx.issues[1].op - 1].op, std::string("mla_attn")); - CHECK_EQ(b.ops[ctx.issues[2].op - 1].op, std::string("mla_project")); - CHECK_EQ(ctx.issues[1].opd[1].kind, RAD_OPK_KV); - CHECK_EQ(ctx.issues[1].opd[2].handle, w.selected); - CHECK_EQ(ctx.issues[1].opd[3].handle, w.length); - CHECK_EQ(ctx.issues[2].opd[1].handle, block.projection); - } -} - -TEST( - glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { - 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 : { 1, 4, 8 }) - for (int rank = 0; rank < world; ++rank) { - 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 = rank == 0 ? 512 : 16; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - const auto& m = *glm5next::models[rank]; - CHECK(m.have_mtp); - CHECK_EQ(b.drafter.kind, RAD_DRAFT_SERIAL); - CHECK_EQ(b.drafter.depth, 3); - CHECK_EQ(m.layers.size(), (size_t)45); - int full = 0; - for (int l = 0; l < 45; ++l) { - const auto& layer = m.layers[l]; - full += layer.full; - CHECK(layer.attn_hc.op_pre < layer.norm.op); - CHECK(layer.attn_hc.op_post < layer.ffn_hc.op_pre); - if (layer.full) { - CHECK(layer.index.cache.op_select < layer.mla.core.op_attn); - CHECK(layer.mla.output.op < layer.attn_hc.op_post); - } else - CHECK(layer.kda.output.op < layer.attn_hc.op_post); - if (l >= 3) { - CHECK_EQ(layer.moe.c.expert_mx, 1); - CHECK(layer.moe.op_gather < layer.ffn_hc.op_post); - } - } - CHECK_EQ(full, 11); - CHECK_EQ(m.draft.moe.c.expert_f32_scale, 1); - for (const auto& map : b.maps) - if (map.declared.starts_with("mtp.")) - for (const auto& source : map.src) CHECK(!source.starts_with("mtp.model.")); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = rank; - ctx.world = world; - ctx.batch = &batch; - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90); - CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34); - CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11); - // Two rows stay under the split threshold: 42 routers and 11 index heads, replicated. - CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53); - 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); - CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); - ctx.issues.clear(); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - const auto draft_ops = issued_ops(b, ctx); - CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mhc_pre"), 0); - CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mla_attn"), 1); - CHECK_EQ(ctx.issues.back().op, m.mhead); - CHECK(m.mselect < m.draft.moe.op_router); - for (const auto& issue : ctx.issues) { - if (issue.op == m.draft.moe.op_router || issue.op == m.mnorm_op) - CHECK_EQ(issue.opd[0].rows, 1); // Only the row producing a proposal. - if (issue.op == m.draft.residual) - CHECK_EQ(issue.opd[0].rows, 2); // Full history still fills attention caches. - } - ctx.issues.clear(); - batch.n_draft_out = 0; - glm5next::step(&ctx, &batch); - const auto history = issued_ops(b, ctx); - CHECK(std::find(history.begin(), history.end(), "kv_store") != history.end()); - CHECK(std::find(history.begin(), history.end(), "moe_gemm_q") == history.end()); - if (rank == 0) { - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.max_q_len = 512; - ctx.issues.clear(); - 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. - 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); - 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"), - world > 1 ? 90 : 0); - 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) - CHECK(n == 288 || n == 32); - else { - CHECK(n == 288 / world || n == 32 / world); - CHECK_EQ(issue.opd[1].rows, n); - } - } - } - for (int l = 3; l < 45; ++l) { - // A prefill routes its full batch once, reusing each expert's - // weights across its rows instead of re-reading them in chunks. - CHECK_EQ(std::count_if(ctx.issues.begin(), ctx.issues.end(), - [&](const auto& issue) { - const auto& moe = m.layers[l].moe; - return issue.op == moe.op_router || - issue.op == moe.glm_router.split.op_part; - }), - 1); - } - // Arena-lending probes must not replace the model the serving - // graph's handles refer to, even when they declare fewer rows. - const auto* live = glm5next::models[rank].get(); - RadBuilder pb; - pb.kv_block = 4; - pb.encs = b.encs; - auto small = build; - small.shape_probe = 1; - small.max_tok = 1; - REQUIRE_EQ(glm5next::declare(&pb, &meta, &small), RAD_OK); - CHECK_EQ(glm5next::models[rank].get(), live); - CHECK_EQ(glm5next::models[rank]->g.max_tok, 512); - RadArchProbe capabilities{}; - REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK); - CHECK_EQ(capabilities.shape_probe_ok, 1); - std::array results{}; - std::vector probes; - for (int i = 0; i < 8; ++i) - probes.emplace_back([&, i] { - RadBuilder parallel; - parallel.kv_block = 4; - parallel.encs = b.encs; - auto level = build; - level.rank = i % 4; - level.max_tok = i < 4 ? 256 : 1024; - level.shape_probe = 1; - results[i] = glm5next::declare(¶llel, &meta, &level); - }); - for (auto& thread : probes) thread.join(); - for (int status : results) CHECK_EQ(status, RAD_OK); - CHECK_EQ(glm5next::models[rank].get(), live); - } - } -} - -/* 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" }; - 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); - const int world = 8, rank = 3; - for (int64_t R : { 256, 3072 }) { - auto encs = [&](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 c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 4096; - c.max_seqs = 8; - c.max_ctx = 32768; - c.max_spec = 3; - RadBuilder full; - encs(full); - REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); - RadBuildCtx p = c; - p.max_tok = R; - p.shape_probe = 1; - RadBuilder small; - encs(small); - REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); - REQUIRE_EQ(small.ops.size(), full.ops.size()); - int differ = 0; - for (size_t i = 0; i < full.ops.size(); ++i) { - if (small.ops[i].op != full.ops[i].op) { - ++differ; - continue; - } - REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); - for (size_t k = 0; k < full.ops[i].p.size(); ++k) { - const RecParam& a = full.ops[i].p[k]; - const RecParam& q = small.ops[i].p[k]; - if (a.kind == RAD_P_RANGE) continue; - // A capacity may shrink: its kernel writes by its operands' extents. - if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) - continue; - if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { - fprintf(stderr, - " R %lld: op %zu '%s' param '%s': " - "%lld real, %lld small\n", - (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), - a.ival, q.ival); - ++differ; - } - } - } - CHECK_EQ(differ, 0); - REQUIRE_EQ(small.bufs.size(), full.bufs.size()); - for (size_t i = 0; i < full.bufs.size(); ++i) - for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) - CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); - } -} - -/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill - * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the - * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's - * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ -TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { - 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); - using Counts = std::map; - /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed - * and a shared clamped SwiGLU, and three dense ones. */ - struct Want { - const char* op; - int trunk, draft, prefill; - }; - const Want wants[] = { - { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, - { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, - { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, - }; - for (int world : { 1, 8 }) { - 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 = 0; - build.world_size = world; - build.max_tok = 512; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = 0; - ctx.world = world; - ctx.batch = &batch; - Counts got[3]; - /* With the inverse, the fused selection writes it as its ninth operand and the gather - * reads it as its third. */ - const rad_buf inv = find_b(b, "expert_inverse") - ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) - : 0; - REQUIRE(inv != 0); - auto run = [&](int k) { - ctx.issues.clear(); - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - CHECK_LINT(b, &ctx); - for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; - for (const auto& is : ctx.issues) { - const RecOp* o = b.op_of(is.op); - if (!o) continue; - if (o->op == "router_sigmoid_topk_scatter") - CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && - is.opd[8].handle == inv); - if (o->op == "moe_gather_inv") - CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && - is.opd[2].handle == inv); - } - }; - run(0); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - run(1); - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.n_draft_out = 0; - batch.max_q_len = 512; - run(2); - for (int k = 0; k < 3; ++k) - for (const Want& w : wants) { - const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; - if (got[k][w.op] != want) - fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, - got[k][w.op], want); - CHECK_EQ(got[k][w.op], want); - } - } -} - -TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { - using namespace rad::arch; - for (bool front : { false, true }) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.max_seqs = 4; - g.max_spec = 3; - RadKVGroupDecl ad{}; - ad.kind = RAD_KV_FULL; - ad.dtype = RAD_BF16; - ad.n_head_kv = 1; - ad.head_dim = 256; - const auto attn = rad_decl_kv_group(&b, "attn", &ad); - // Claim the attention group's consumer before declaring the index group. - RAD_OP(&b, "mla_attn", RAD_PARAMS(RAD_INT("block_size", 4)), RAD_NOWEIGHTS); - RadKVGroupDecl td{}; - td.kind = RAD_KV_LINEAR; - td.dtype = RAD_BF16; - td.n_head_kv = 1; - td.state_dim[0] = 7; - td.state_dim[1] = 256; - const auto tail = rad_decl_kv_group(&b, "tail", &td); - DsaCache::Wire w; - w.query = decl_b(&b, "query", RAD_BF16, { 1024, 128 }); - w.codes = decl_b(&b, "codes", RAD_F8E4M3, { 1024, 128 }); - w.scales = decl_b(&b, "scales", RAD_F32, { 1024, 1 }); - w.gate = decl_b(&b, "gates", RAD_F32, { 32, 32 }); - w.kg = decl_b(&b, "kg", RAD_BF16, { 32, 256 }); - w.stage = decl_b(&b, "stage", RAD_BF16, { 48, 256 }); - w.page = decl_b(&b, "page", RAD_I32, { 12 }); - w.bpos = decl_b(&b, "bpos", RAD_I32, { 12 }); - w.nc = decl_b(&b, "nc", RAD_I32, { 4 }); - w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 }); - w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 }); - w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 }); - w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 }); - w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 }); - w.length = decl_b(&b, "len", RAD_I32, { 32 }); - DsaCache block; - DsaCache::Config cfg; - cfg.blocks = 1024; - cfg.work = 12; - cfg.ring = 7; - rad_kvgroup index = 0; - GlmIndexer indexer; - if (front) { - GlmIndexer::Wire iw; - iw.cache = w; - iw.input = decl_b(&b, "input", RAD_BF16, { 32, 4096 }); - iw.q_low = decl_b(&b, "q_low", RAD_BF16, { 32, 1536 }); - iw.q_wide = decl_b(&b, "q_wide", RAD_BF16, { 32, 4096 }); - iw.kg_raw = decl_b(&b, "kg_raw", RAD_BF16, { 32, 256 }); - REQUIRE_EQ(indexer.declare(&b, nm, g, 3, iw, "indexer", cfg, attn, tail, &index), - RAD_OK); - block = indexer.cache; - CHECK_EQ(b.weights[indexer.head_weight - 1].d.dtype, RAD_F32); - CHECK_EQ(b.weights[indexer.query.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[indexer.key_gate.w - 1].d.shard, RAD_SHARD_NONE); - } else - REQUIRE_EQ(block.declare(&b, nm, g, 3, cfg, w, attn, tail, &index, "indexer.pool.ape"), - RAD_OK); - CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8); - CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17); - int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{}; - RadKVGroupBatch kv[3]{}; - kv[0].group = index; - kv[0].block_table = ibt; - kv[0].block_table_pitch = 8; - kv[1].group = tail; - kv[1].state_index = sidx; - kv[1].state_index_pitch = 6; - kv[2].group = attn; - kv[2].block_table = abt; - kv[2].block_table_pitch = 8; - RadBatch batch{}; - batch.n_tok = 8; - batch.n_seq = 2; - batch.n_spec = 2; - batch.kv = kv; - batch.n_kv_groups = 3; - batch.positions = pos; - batch.cu_seqlens = cu; - batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns. - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - if (front) { - indexer.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)12); - CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy); - CHECK_EQ(ctx.issues[1].opd[1].rows, 256); - CHECK_EQ(ctx.issues[3].op, indexer.op_norm); - CHECK_EQ(ctx.issues[4].opd[0].offset, 128); - CHECK_EQ(ctx.issues[5].op, indexer.op_head); - ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6); - } else - block.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)6); - CHECK_EQ(ctx.issues[0].n, 256); - CHECK(ctx.issues[1].opd[5].raw == ibt); - CHECK_EQ(ctx.issues[1].opd[4].cols, 6); - CHECK_EQ(ctx.issues[2].op, block.op_pool); - CHECK_EQ(ctx.issues[2].opd[5].handle, index); - CHECK_EQ(ctx.issues[3].op, block.op_tail); - CHECK_EQ(ctx.issues[4].opd[0].rows, 256); - CHECK_EQ(ctx.issues[4].opd[3].handle, index); - CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE); - CHECK(ctx.issues[4].opd[5].raw == ibt); - CHECK_EQ(ctx.issues[4].opd[8].cols, 8); - CHECK_EQ(ctx.issues[5].opd[0].cols, 8); - CHECK(ctx.issues[5].opd[1].raw == abt); - } -} - -TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.n_ff = 3072; - g.max_tok = 32; - g.world = 4; - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - b.encs = { { "ffn_gate_up", fp8 }, { "ffn_down", fp8 } }; - MlpFP8::Wire w; - w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); - w.h.x = decl_b(&b, "h", RAD_BF16, { 32, 4096 }); - REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); - w.gate_up = decl_b(&b, "gate_up", RAD_BF16, { 32, 6144 }); - w.ffn.x = decl_b(&b, "ffn", RAD_BF16, { 32, 3072 }); - REQUIRE_EQ(w.ffn.declare_qs(&b, nm, g, "ffn", 3072), RAD_OK); - MlpFP8 block; - MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", - "mlp.up_proj.weight", "mlp.down_proj.weight" }; - REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); - CHECK_EQ(block.op_gated, 0u); - CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); - RadCtx ctx; - ctx.b = &b; - block.slice(&ctx, 8, 4, 4); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 1); - CHECK(std::find(ops.begin(), ops.end(), "gemm_nt_q_gated") == ops.end()); - CHECK(std::find(ops.begin(), ops.end(), "quant_act_fp8") != ops.end()); -} - -TEST(glm_mla_stores_one_normalized_latent_and_exposes_q_lora_before_sparse_attention) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.rank = rank; - RadKVGroupDecl kd{}; - kd.kind = RAD_KV_FULL; - kd.dtype = RAD_BF16; - kd.n_head_kv = 1; - kd.head_dim = 256; - const auto kv = rad_decl_kv_group(&b, "latent", &kd); - auto buf = [&](const char* name, int64_t n) { - return decl_b(&b, name, RAD_BF16, { 32, n }); - }; - GlmMla::Wire w; - w.input.x = buf("input", 4096); - w.q_raw = buf("q_raw", 1536); - w.kv_raw = buf("kv_raw", 512); - w.q_low.x = buf("q_low", 1536); - w.latent = buf("latent_out", 512); - w.out = buf("out", 4096); - REQUIRE_EQ(w.input.declare_qs(&b, nm, g, "input", 4096), RAD_OK); - REQUIRE_EQ(w.q_low.declare_qs(&b, nm, g, "q_low", 1536), RAD_OK); - w.core.q = buf("q", 4096); - w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { 32, 16, 512 }); - w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { 32, 16, 512 }); - w.core.out = buf("expanded", 4096); - w.attn.x = w.core.out; - REQUIRE_EQ(w.attn.declare_qs(&b, nm, g, "expanded", 4096), RAD_OK); - w.core.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); - w.core.length = decl_b(&b, "length", RAD_I32, { 32 }); - GlmMla block; - REQUIRE_EQ(block.declare(&b, nm, g, 3, w, "attn", kv), RAD_OK); - CHECK_EQ(b.weights[block.q_a.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[block.q_b.w - 1].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); - int32_t slots[4]{}; - RadKVGroupBatch kb{}; - kb.group = kv; - kb.slot_mapping = slots; - RadBatch batch{}; - batch.n_tok = 4; - batch.kv = &kb; - batch.n_kv_groups = 1; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.prepare(&ctx, &batch); - auto find_issue = [&](rad_op op) -> const RecIssue* { - for (const auto& issue : ctx.issues) - if (issue.op == op) return &issue; - return nullptr; - }; - const auto* store = find_issue(block.op_store); - REQUIRE(store); - CHECK_EQ(store->opd[0].handle, w.latent); - CHECK_EQ(store->opd[0].cols, 256); - CHECK_EQ(store->opd[1].offset, 256); - CHECK_EQ(store->opd[1].cols, 256); - CHECK(store->opd[2].raw == slots); - const auto before = issued_ops(b, ctx); - CHECK(std::find(before.begin(), before.end(), "mla_attn") == before.end()); - block.finish(&ctx, &batch); - const auto* attn = find_issue(block.core.op_attn); - REQUIRE(attn); - CHECK_EQ(attn->opd[2].handle, w.core.selected); - CHECK_EQ(ctx.issues.back().op, block.op_ar); - } -} - -TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.rank = rank; - g.max_spec = 3; - RadKVGroupDecl sd{}; - sd.kind = RAD_KV_LINEAR; - sd.dtype = RAD_F32; - sd.n_head_kv = 16; - sd.state_dim[0] = sd.state_dim[1] = 128; - RadKVGroupDecl cd{}; - cd.kind = RAD_KV_CONV; - cd.dtype = RAD_BF16; - cd.n_head_kv = 1; - cd.head_dim = 6144; - cd.conv_width = 4; - const auto state = rad_decl_kv_group(&b, "state", &sd), - history = rad_decl_kv_group(&b, "conv", &cd); - auto buf = [&](const char* name, int64_t width) { - return decl_b(&b, name, RAD_BF16, { 32, width }); - }; - GlmKda::Wire w; - w.input = buf("input", 4096); - w.forget_low = buf("forget_low", 128); - w.gate_low = buf("gate_low", 128); - w.out = buf("out", 4096); - w.core.qkv = buf("qkv", 6144); - w.core.conv = buf("conv_out", 6144); - w.core.a = buf("a", 2048); - w.core.beta = buf("beta", 16); - w.core.gate = buf("gate", 2048); - w.core.out = buf("core_out", 2048); - KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", - "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; - GlmKda block; - REQUIRE_EQ(block.declare(&b, nm, g, 0, w, "attn", src, state, history), RAD_OK); - CHECK_EQ(b.weights[block.qkv.w - 1].d.n_row_parts, 3); - CHECK_EQ(b.weights[block.forget_a.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[block.forget_b.w - 1].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); - int32_t cu[] = { 0, 4 }, ctxlens[] = { 0 }, indices[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }; - RadKVGroupBatch kv[2]{}; - kv[0].group = state; - kv[0].state_index = indices; - kv[0].state_index_pitch = 6; - kv[1].group = history; - kv[1].state_index = ci; - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 4; - batch.n_seq = 1; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv; - batch.n_kv_groups = 2; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.step(&ctx, &batch); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); - CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); - REQUIRE_EQ(ctx.issues.size(), (size_t)11); - CHECK_EQ(ctx.issues[9].op, block.output.op); - CHECK_EQ(ctx.issues[10].op, block.op_ar); - CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); - } -} - -TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.max_spec = 3; - RadKVGroupDecl sd{}; - sd.kind = RAD_KV_LINEAR; - sd.dtype = RAD_F32; - sd.n_head_kv = 16; - sd.state_dim[0] = sd.state_dim[1] = 128; - RadKVGroupDecl cd{}; - cd.kind = RAD_KV_CONV; - cd.dtype = RAD_BF16; - cd.n_head_kv = 1; - cd.head_dim = 6144; - cd.conv_width = 4; - const rad_kvgroup st = rad_decl_kv_group(&b, "state", &sd), - cv = rad_decl_kv_group(&b, "conv", &cd); - KdaState::Wire w; - w.qkv = decl_b(&b, "qkv", RAD_BF16, { 32, 6144 }); - w.conv = decl_b(&b, "filtered", RAD_BF16, { 32, 6144 }); - w.a = decl_b(&b, "a", RAD_BF16, { 32, 2048 }); - w.beta = decl_b(&b, "beta", RAD_BF16, { 32, 16 }); - w.gate = decl_b(&b, "gate", RAD_BF16, { 32, 2048 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 128 }); - KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", - "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; - KdaState block; - KdaState::Config cfg; - REQUIRE_EQ(block.declare(&b, nm, g, 0, st, cv, cfg, w, src), RAD_OK); - CHECK_EQ(b.weights[block.taps - 1].d.n_row_parts, 3); - for (int p = 0; p < 3; ++p) CHECK_EQ(b.weights[block.taps - 1].d.row_parts[p], 2048); - CHECK_EQ(b.weights[block.bias - 1].d.shape[0], 2048); - for (rad_op op : { block.op_prefill, block.op_verify }) { - bool found = false; - for (const auto& p : b.ops[op - 1].p) - if (p.key == "state_form") { - CHECK_EQ(p.sval, std::string("anchor")); - found = true; - } - CHECK(found); - } - int32_t cu[] = { 0, 3, 8 }, ctxlens[] = { 11, 0 }, accepted[] = { 2, 1 }; - int32_t indices[] = { 0, 0, 0, 2, 2, 2, 1, 1, 1, 3, 3, 3 }, conv_indices[] = { 0, 1 }; - RadKVGroupBatch kv[2]{}; - kv[0].group = st; - kv[0].state_index = indices; - kv[0].state_index_pitch = 6; - kv[1].group = cv; - kv[1].state_index = conv_indices; - kv[1].state_index_pitch = 1; - RadBatch batch{}; - batch.phase = RAD_PHASE_MIXED; - batch.n_tok = 8; - batch.n_seq = 2; - batch.n_seq_decode = 1; - batch.n_tok_decode = 3; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.num_accepted = accepted; - batch.kv = kv; - batch.n_kv_groups = 2; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)5); - CHECK_EQ(ctx.issues[0].op, block.op_conv); - CHECK_EQ(ctx.issues[0].n, 3); - CHECK_EQ(ctx.issues[1].op, block.op_verify); - CHECK_EQ(ctx.issues[1].opd[0].cols, 2048); - CHECK_EQ(ctx.issues[1].opd[1].offset, 2048); - CHECK_EQ(ctx.issues[1].opd[2].offset, 4096); - CHECK_EQ(ctx.issues[2].op, block.op_conv); - CHECK_EQ(ctx.issues[2].n, 8); - CHECK(ctx.issues[2].opd[3].raw == cu + 1); - CHECK_EQ(ctx.issues[2].opd[7].kind, RAD_OPK_NONE); - CHECK_EQ(ctx.issues[3].op, block.op_prefill); - CHECK(ctx.issues[3].opd[8].raw == indices + 6); - CHECK(ctx.issues[3].opd[9].raw == cu + 1); - CHECK_EQ(ctx.issues[3].opd[0].offset, 0); - CHECK_EQ(ctx.issues[3].opd[0].rows, 8); - CHECK_EQ(ctx.issues[4].op, block.op_norm); -} - TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_groups) { using namespace rad::arch; const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); @@ -4488,14 +2392,6 @@ const RecOp* issued_op(const RadBuilder& b, const RadCtx& c, const std::string& } return nullptr; } -const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string& name, - int nth = 0) { - for (const auto& i : c.issues) { - const RecOp* o = b.op_of(i.op); - if (o && o->op == name && nth-- == 0) return &i; - } - return nullptr; -} } /* namespace */ @@ -5972,10 +3868,6 @@ int count_resolved(const RadBuilder& b, const std::string& name) { return n; } -int count_issued(const std::vector& v, const std::string& name) { - return (int)std::count(v.begin(), v.end(), name); -} - } /* namespace */ TEST(a_gemma4_moe_trunk_declares_both_arms_and_the_joins) { @@ -6905,50 +4797,6 @@ TEST(the_step_lint_reports_each_rule_it_checks) { namespace { -/* `fn`'s status, with what it prints kept out of the test output. */ -int stderr_of_rc(const std::function& fn) { - int rc = 0; - stderr_of([&] { rc = fn(); }); - return rc; -} - -/* Model metadata built key by key; `meta()` is valid while this object lives. */ -struct MetaKV { - RadModelMeta m{}; - std::vector keys, vals; - std::vector kp, vp; - explicit MetaKV(const RadModelMeta& base) : m(base) { - for (int i = 0; i < base.n_kv; ++i) set(base.kv_key[i], base.kv_val[i]); - } - MetaKV& set(const char* k, const char* v) { - for (size_t i = 0; i < keys.size(); ++i) - if (keys[i] == k) { vals[i] = v; return *this; } - keys.push_back(k); - vals.push_back(v); - return *this; - } - MetaKV& drop(const char* k) { - for (size_t i = 0; i < keys.size(); ++i) - if (keys[i] == k) { - keys.erase(keys.begin() + (long)i); - vals.erase(vals.begin() + (long)i); - break; - } - return *this; - } - const RadModelMeta* meta() { - kp.clear(); vp.clear(); - for (size_t i = 0; i < keys.size(); ++i) { - kp.push_back(keys[i].c_str()); - vp.push_back(vals[i].c_str()); - } - m.n_kv = (int)kp.size(); - m.kv_key = kp.data(); - m.kv_val = vp.data(); - return &m; - } -}; - /* Qwen3.8-27B-FP8's shape cut to the eight-layer fixture, its MTP head declared. */ MetaKV q35fp8_meta() { MetaKV k(qwen35_meta()); @@ -6992,12 +4840,6 @@ MetaKV with_dflash2(MetaKV k) { return k; } -RadBuildCtx spec_ctx(int rank, int world, int max_spec) { - RadBuildCtx c = build_ctx(rank, world); - c.max_spec = max_spec; - return c; -} - /* Every gemm_nt handle a pass issues is issued once: the bf16 GEMMs take a whole pass in one * launch (libr4d's bf16 row serves M to 65536), so a slice loop would be a stale band. */ bool each_gemm_nt_once(const RadBuilder& b, const RadCtx& c) { @@ -9110,57 +6952,6 @@ std::string joined(const std::set& s) { return r.empty() ? std::string("(none)") : r; } -/* A 64-bit FNV-1a fingerprint of everything a declare recorded: ops with their parameters, - * weights, read and write sets and resolution; buffers, weights, KV groups, bindings, name maps, - * the logits / pooled / drafter / generator declarations and the concurrent list. Two declares - * give one value only if the core would build the same program from them. */ -struct Fnv { - uint64_t h = 1469598103934665603ull; - Fnv& raw(const void* p, size_t n) { - const auto* c = (const unsigned char*)p; - for (size_t i = 0; i < n; ++i) { h ^= c[i]; h *= 1099511628211ull; } - return *this; - } - Fnv& s(const std::string& x) { return raw(x.data(), x.size()).i((int64_t)x.size()); } - Fnv& s(const char* x) { return s(std::string(x ? x : "")); } - Fnv& i(int64_t v) { return raw(&v, sizeof v); } - Fnv& f(double v) { return raw(&v, sizeof v); } -}; -uint64_t graph_hash(const RadBuilder& b) { - Fnv f; - for (const RecOp& o : b.ops) { - f.s(o.op).i(o.resolved).i((int64_t)o.p.size()); - for (const RecParam& p : o.p) f.s(p.key).i(p.kind).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); - for (const auto* v : { &o.w, &o.reads, &o.writes }) { - f.i((int64_t)v->size()); - for (uint32_t x : *v) f.i(x); - } - } - for (const RecBuf& x : b.bufs) { - f.s(x.name).i(x.d.dtype).i(x.d.rank).i(x.d.kind).i(x.d.domain).i(x.d.kv).s(x.d.derive); - for (uint32_t d = 0; d < x.d.rank; ++d) f.i(x.d.shape[d]); - } - for (const RecWeight& w : b.weights) { - f.s(w.name).i(w.d.dtype).i(w.d.rank).i(w.d.shard).i(w.d.access).i(w.d.group.layer) - .i(w.d.group.expert).s(w.d.source).s(w.d.planes).i(w.d.n_row_parts).i(w.span_lo) - .i(w.span_hi).i(w.n_part_spans); - for (uint32_t d = 0; d < w.d.rank; ++d) f.i(w.d.shape[d]); - } - for (const RecKV& g : b.kv_groups) - f.s(g.name).i(g.d.kind).i(g.d.dtype).i(g.d.window).i(g.d.n_head_kv).i(g.d.head_dim) - .i(g.d.state_dim[0]).i(g.d.state_dim[1]).i(g.d.conv_width).i(g.zero); - for (const auto& [l, g] : b.binds) f.i(l).i(g); - for (const RecMap& m : b.maps) { - f.s(m.declared).i(m.mode).i(m.concat_dim); - for (const auto& x : m.src) f.s(x); - } - f.i(b.logits).i(b.pooled).s(b.drafter_name).i(b.drafter.kind).i(b.drafter.depth) - .i(b.drafter.block).i(b.drafter.proposal).i(b.drafter.mask_token).i(b.drafter_shared) - .s(b.encoder_name).s(b.audio_encoder_name).s(b.generator_name); - for (rad_buf x : b.concurrent) f.i(x); - return f.h; -} - } /* namespace */ /* For every architecture, declaring with only libref's vocabulary either asks for nothing else and @@ -9706,93 +7497,6 @@ TEST(qwen3asr_refuses_a_tower_it_does_not_serve) { RAD_TEST_MAIN() -/* ==================================================================== a 4096 budget without a span */ -namespace { - -/* What a step issued, as a fingerprint: each launch's op (by name and declared parameters), row - * count and lane, every operand by kind, buffer or weight name, offset and extent, a raw operand - * by the batch array and element it points at, and every lane join. */ -uint64_t issue_hash(const RadBuilder& b, const std::vector>& v, - const std::vector& kits) { - Fnv f; - auto raw_at = [&](const void* p) { - if (!p) { f.i(-1); return; } - if (const rad_buf h = fake_buf_of(p, b.bufs.size())) { - f.i(1).s(b.bufs[h - 1].name) - .i((int64_t)((uintptr_t)p - (uintptr_t)rad_buf_ptr(nullptr, h))); - return; - } - for (size_t k = 0; k < kits.size(); ++k) { - const Kit& t = *kits[k]; - const std::vector* arrays[] = { &t.tok, &t.pos, &t.cu, &t.ctxl, &t.qlen, - &t.out, &t.nacc, &t.dout, &t.slot, &t.table, - &t.used, &t.sidx }; - for (size_t a = 0; a < sizeof arrays / sizeof arrays[0]; ++a) { - const std::vector& x = *arrays[a]; - const int32_t* q = (const int32_t*)p; - if (!x.empty() && q >= x.data() && q < x.data() + x.size()) { - f.i(2).i((int64_t)a).i((int64_t)(q - x.data())); - return; - } - } - } - f.i(3); - }; - for (const auto& c : v) { - f.i((int64_t)c->issues.size()); - for (const RecIssue& r : c->issues) { - const RecOp* o = b.op_of(r.op); - f.s(o ? o->op : ""); - if (o) - for (const RecParam& p : o->p) f.s(p.key).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); - f.i(r.n).i(r.lane).i((int64_t)r.opd.size()); - for (const RadOperand& d : r.opd) { - f.i(d.kind).i(d.dtype).i(d.offset).i(d.rows).i(d.cols); - if (d.kind == RAD_OPK_BUF) - f.s(d.handle && d.handle <= b.bufs.size() ? b.bufs[d.handle - 1].name : "?"); - else if (d.kind == RAD_OPK_WEIGHT || d.kind == RAD_OPK_WTAB) - f.s(d.handle && d.handle <= b.weights.size() ? b.weights[d.handle - 1].name - : "?"); - else if (d.kind == RAD_OPK_RAW) - raw_at(d.raw); - else - f.i(d.handle); - } - } - for (const RecJoin& j : c->joins) f.i((int64_t)j.at).i(j.from).i(j.to); - } - return f.h; -} - -/* The steps of the fingerprint: a 4096-row prefill after 4096 tokens of history (wider than a - * MoE pass), a mixed step, a decode step, and with a drafter a verify and its first passes. */ -uint64_t pinned_steps(RadBuilder& b, StepFn step, int rank, int world) { - const auto pf = kit(b, {}, { 4096 }, 4096); - const auto mx = kit(b, { 1, 1 }, { 2000 }, 3000); - const auto dc = kit(b, { 1, 1, 1 }, {}); - std::vector> all; - std::vector kits; - for (const Kit* k : { pf.get(), mx.get(), dc.get() }) { - auto v = run_passes(b, step, { k }, rank, world); - CHECK_PASSES(b, v); - for (auto& c : v) all.push_back(std::move(c)); - kits.push_back(k); - } - std::unique_ptr ver, his, r2; - if (b.drafter.kind == RAD_DRAFT_SERIAL) { - ver = kit(b, std::vector(3, 4), {}); - his = history_pass(b, *ver); - r2 = round_pass(b, 3, 2); - auto v = run_passes(b, step, { ver.get(), his.get(), r2.get() }, rank, world); - CHECK_PASSES(b, v); - for (auto& c : v) all.push_back(std::move(c)); - kits.push_back(ver.get()); kits.push_back(his.get()); kits.push_back(r2.get()); - } - return issue_hash(b, all, kits); -} - -} /* namespace */ - /* Without --prefill-span a 4096 budget declares and steps the pinned graph and launches: for * Flash-Next and the other plugins built on the same fp8 blocks, at one, two and four ranks, taken * from the plugins as they were before the span. */ @@ -9843,53 +7547,6 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } -/* 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" }; - 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); - struct Case { - int world; - uint64_t graph, steps; - }; - const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, - { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; - for (const Case& cs : cases) { - 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 ctx = spec_ctx(0, cs.world, 3); - ctx.max_tok = 4096; - ctx.max_seqs = 8; - ctx.max_ctx = 200000; - 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); - CHECK_EQ(g, cs.graph); - CHECK_EQ(s, cs.steps); - } -} - /* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its * connection reads take a pass each and the indexer scores its pass-tall plane in windows, the MTP * head's pass included. At four ranks the step is pipelined (step_pipelined): every layer's diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp new file mode 100644 index 00000000..f6c7adfb --- /dev/null +++ b/tests/glm5next_test.cpp @@ -0,0 +1,1628 @@ +/* glm5next_test.cpp -- the declared graph and the steps of GLM-5.3-Flash's plugin and its blocks, + * asserted statically against the recording builder of arch_fakes.h. */ +#define RAD_ARCH_NO_EXPORTS 1 + +#include "arch_fakes.h" + +#include +#include +#include +#include + +/* ==================================================================== the plugin under test */ + +/* GLM-5.3-Flash: its blocks (through the plugin's includes) and the plugin. */ +#include "../arch/glm5next/glm5next.cpp" + +/* ==================================================================== the blocks */ + +TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residual_destination) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 32, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 32, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 32, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 32, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)3); + CHECK_EQ(b.weights[0].d.shape[0], 24); + CHECK_EQ(b.weights[0].d.shape[1], 16384); + CHECK_EQ(b.weights[1].d.shape[0], 3); + CHECK_EQ(b.weights[2].d.shape[0], 24); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK(b.ops[conn.op_pre - 1].reads == std::vector({ w.h })); + CHECK(b.ops[conn.op_pre - 1].writes == std::vector({ w.x, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].reads == std::vector({ w.y, w.h, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].writes == std::vector({ w.out })); + RadCtx ctx; + conn.read(&ctx, 4); + conn.write(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_post); + CHECK_EQ(ctx.issues[0].n, 4); + CHECK_EQ(ctx.issues[1].n, 4); + REQUIRE_EQ(ctx.issues[0].opd.size(), (size_t)7); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + const rad_weight coefficients[] = { conn.w_fn, conn.w_scale, conn.w_base }; + for (int i = 0; i < 3; ++i) { + CHECK_EQ(ctx.issues[0].opd[i + 1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[i + 1].handle, coefficients[i]); + } + CHECK_EQ(ctx.issues[0].opd[4].handle, w.x); + CHECK_EQ(ctx.issues[0].opd[5].handle, w.post); + CHECK_EQ(ctx.issues[0].opd[6].handle, w.comb); + REQUIRE_EQ(ctx.issues[1].opd.size(), (size_t)5); + const rad_buf expected[] = { w.y, w.h, w.post, w.comb, w.out }; + for (int i = 0; i < 5; ++i) { + CHECK_EQ(ctx.issues[1].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[1].opd[i].rows, 4); + } + auto invalid = w; + invalid.out = w.h; + ManifoldConn refused; + CHECK_EQ(refused.declare(&b, nm, g, 3, "bad", cfg, invalid, src), RAD_E_INVAL); +} + +TEST(manifold_read_splits_its_projection_by_chunks_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; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 512, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 512, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 512, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 512, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 512, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 512, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t mine = 8 / world; + CHECK_EQ(count_op(b, "mhc_pre"), 1); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 1 : 0); + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "mhc_pre_finish"), split ? 1 : 0); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "mhc_pre_partial"); + const RecOp* gather = find_op(b, "all_gather"); + const RecOp* finish = find_op(b, "mhc_pre_finish"); + REQUIRE(part && gather && finish); + CHECK_EQ(pint(part, "chunk"), 2048); + CHECK_EQ(pint(part, "first"), rank * mine); + CHECK_EQ(pint(part, "chunks"), mine); + CHECK(part->w == std::vector({ conn.w_fn })); + CHECK(part->reads == std::vector({ w.h })); + CHECK(part->writes == std::vector({ conn.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), mine * 28); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, mine * 28); + CHECK_EQ(param(gather, "numel")->ihi, 512 * mine * 28); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ conn.part })); + CHECK(gather->writes == std::vector({ conn.parts })); + CHECK_EQ(pint(finish, "chunk"), 2048); + CHECK_EQ(pint(finish, "iterations"), 20); + CHECK(finish->w == std::vector({ conn.w_scale, conn.w_base })); + CHECK(finish->reads == std::vector({ conn.parts, w.h })); + CHECK(finish->writes == std::vector({ w.x, w.post, w.comb })); + CHECK_EQ(find_b(b, "blk.3.mhc_attn.parts")->d.shape[1], 8 * 28); + } + RadCtx ctx; + conn.read(&ctx, 300); + conn.read(&ctx, 255); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)4); + CHECK_EQ(ctx.issues[0].op, conn.op_partial); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].handle, conn.w_fn); + CHECK_EQ(ctx.issues[0].opd[2].handle, conn.part); + CHECK_EQ(ctx.issues[1].op, conn.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * mine * 28); + CHECK_EQ(ctx.issues[1].opd[1].handle, conn.parts); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, conn.op_finish); + REQUIRE_EQ(ctx.issues[2].opd.size(), (size_t)7); + const uint32_t expected[] = { conn.parts, w.h, conn.w_scale, conn.w_base, + w.x, w.post, w.comb }; + for (int i = 0; i < 7; ++i) CHECK_EQ(ctx.issues[2].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[3].op, conn.op_pre); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_pre); + } + } +} + +TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 128; + g.world = 4; + g.rank = rank; + GlmRouter::Config cfg; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 32, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 32, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 32, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)2); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shape[1], 4096); + CHECK_EQ(b.ops[router.op_project - 1].op, std::string("gemm_nt_f32")); + CHECK_EQ(b.ops[router.op_select - 1].op, std::string("router_sigmoid_topk")); + RadCtx ctx; + router.step(&ctx, 7, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 4); + CHECK_EQ(ctx.issues[1].opd[1].handle, router.correction); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.ids); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.weights); + } +} + +TEST(glm_router_and_index_head_split_columns_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; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + GlmRouter::Config cfg; + cfg.rows = 512; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 512, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 512, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 512, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 512, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t cols = 288 / world; + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "gemm_nt_f32"), split ? 2 : 1); + // The weight stays whole and replicated: decode keeps the unsplit projection. + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "gemm_nt_f32", 1); + const RecOp* gather = find_op(b, "all_gather"); + REQUIRE(part && gather); + CHECK_EQ(pint(part, "N"), cols); + CHECK_EQ(pint(part, "K"), 4096); + CHECK(part->w == std::vector({ router.projection })); + CHECK(part->reads == std::vector({ w.input })); + CHECK(part->writes == std::vector({ router.split.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), cols); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, cols); + CHECK_EQ(param(gather, "numel")->ihi, 512 * cols); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ router.split.part })); + CHECK(gather->writes == std::vector({ w.logits })); + } + RadCtx ctx; + router.step(&ctx, 7, 300, 7); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(ctx.issues[0].op, router.split.op_part); + CHECK_EQ(ctx.issues[0].n, 300); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[1].handle, router.projection); + CHECK_EQ(ctx.issues[0].opd[1].offset, rank * cols * 4096); + CHECK_EQ(ctx.issues[0].opd[1].rows, cols); + CHECK_EQ(ctx.issues[0].opd[2].handle, router.split.part); + CHECK_EQ(ctx.issues[0].opd[2].rows, 300); + CHECK_EQ(ctx.issues[1].op, router.split.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * cols); + CHECK_EQ(ctx.issues[1].opd[0].handle, router.split.part); + CHECK_EQ(ctx.issues[1].opd[1].handle, w.logits); + CHECK_EQ(ctx.issues[1].opd[1].offset, 7 * 288); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, router.op_select); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } + ctx.issues.clear(); + router.step(&ctx, 0, 255); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } +} + +TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + 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); + MlaLatent::Config cfg; + MlaLatent::Wire w; + w.q = decl_b(&b, "q", RAD_BF16, { 32, 16, 256 }); + w.q_latent = decl_b(&b, "ql", RAD_BF16, { 32, 16, 512 }); + w.attn_latent = decl_b(&b, "al", RAD_BF16, { 32, 16, 512 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 256 }); + w.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.length = decl_b(&b, "length", RAD_I32, { 32 }); + MlaLatent block; + REQUIRE_EQ( + block.declare(&b, nm, g, 3, kv, cfg, w, "model.layers.3.self_attn.kv_b_proj.weight"), + RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)1); + CHECK_EQ(b.weights[0].d.dtype, RAD_BF16); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[0].d.shape[0], 8192); + CHECK_EQ(b.weights[0].d.shape[1], 512); + RadCtx ctx; + block.step(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(b.ops[ctx.issues[0].op - 1].op, std::string("mla_project")); + CHECK_EQ(b.ops[ctx.issues[1].op - 1].op, std::string("mla_attn")); + CHECK_EQ(b.ops[ctx.issues[2].op - 1].op, std::string("mla_project")); + CHECK_EQ(ctx.issues[1].opd[1].kind, RAD_OPK_KV); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.selected); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.length); + CHECK_EQ(ctx.issues[2].opd[1].handle, block.projection); + } +} + +TEST( + glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { + 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 : { 1, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + 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 = rank == 0 ? 512 : 16; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + const auto& m = *glm5next::models[rank]; + CHECK(m.have_mtp); + CHECK_EQ(b.drafter.kind, RAD_DRAFT_SERIAL); + CHECK_EQ(b.drafter.depth, 3); + CHECK_EQ(m.layers.size(), (size_t)45); + int full = 0; + for (int l = 0; l < 45; ++l) { + const auto& layer = m.layers[l]; + full += layer.full; + CHECK(layer.attn_hc.op_pre < layer.norm.op); + CHECK(layer.attn_hc.op_post < layer.ffn_hc.op_pre); + if (layer.full) { + CHECK(layer.index.cache.op_select < layer.mla.core.op_attn); + CHECK(layer.mla.output.op < layer.attn_hc.op_post); + } else + CHECK(layer.kda.output.op < layer.attn_hc.op_post); + if (l >= 3) { + CHECK_EQ(layer.moe.c.expert_mx, 1); + CHECK(layer.moe.op_gather < layer.ffn_hc.op_post); + } + } + CHECK_EQ(full, 11); + CHECK_EQ(m.draft.moe.c.expert_f32_scale, 1); + for (const auto& map : b.maps) + if (map.declared.starts_with("mtp.")) + for (const auto& source : map.src) CHECK(!source.starts_with("mtp.model.")); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + ctx.batch = &batch; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90); + CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11); + // Two rows stay under the split threshold: 42 routers and 11 index heads, replicated. + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53); + 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); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); + ctx.issues.clear(); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto draft_ops = issued_ops(b, ctx); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mhc_pre"), 0); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mla_attn"), 1); + CHECK_EQ(ctx.issues.back().op, m.mtp.op_head); + CHECK(m.mtp.op_select < m.draft.moe.op_router); + for (const auto& issue : ctx.issues) { + if (issue.op == m.draft.moe.op_router || issue.op == m.mtp.op_norm) + CHECK_EQ(issue.opd[0].rows, 1); // Only the row producing a proposal. + if (issue.op == m.mtp.op_residual) + CHECK_EQ(issue.opd[0].rows, 2); // Full history still fills attention caches. + } + ctx.issues.clear(); + batch.n_draft_out = 0; + glm5next::step(&ctx, &batch); + const auto history = issued_ops(b, ctx); + CHECK(std::find(history.begin(), history.end(), "kv_store") != history.end()); + CHECK(std::find(history.begin(), history.end(), "moe_gemm_q") == history.end()); + if (rank == 0) { + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.max_q_len = 512; + ctx.issues.clear(); + 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. + 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); + 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"), + world > 1 ? 90 : 0); + 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) + CHECK(n == 288 || n == 32); + else { + CHECK(n == 288 / world || n == 32 / world); + CHECK_EQ(issue.opd[1].rows, n); + } + } + } + for (int l = 3; l < 45; ++l) { + // A prefill routes its full batch once, reusing each expert's + // weights across its rows instead of re-reading them in chunks. + CHECK_EQ(std::count_if(ctx.issues.begin(), ctx.issues.end(), + [&](const auto& issue) { + const auto& moe = m.layers[l].moe; + return issue.op == moe.op_router || + issue.op == moe.glm_router.split.op_part; + }), + 1); + } + // Arena-lending probes must not replace the model the serving + // graph's handles refer to, even when they declare fewer rows. + const auto* live = glm5next::models[rank].get(); + RadBuilder pb; + pb.kv_block = 4; + pb.encs = b.encs; + auto small = build; + small.shape_probe = 1; + small.max_tok = 1; + REQUIRE_EQ(glm5next::declare(&pb, &meta, &small), RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + CHECK_EQ(glm5next::models[rank]->g.max_tok, 512); + RadArchProbe capabilities{}; + REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK); + CHECK_EQ(capabilities.shape_probe_ok, 1); + std::array results{}; + std::vector probes; + for (int i = 0; i < 8; ++i) + probes.emplace_back([&, i] { + RadBuilder parallel; + parallel.kv_block = 4; + parallel.encs = b.encs; + auto level = build; + level.rank = i % 4; + level.max_tok = i < 4 ? 256 : 1024; + level.shape_probe = 1; + results[i] = glm5next::declare(¶llel, &meta, &level); + }); + for (auto& thread : probes) thread.join(); + for (int status : results) CHECK_EQ(status, RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + } + } +} + +/* 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" }; + 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); + const int world = 8, rank = 3; + for (int64_t R : { 256, 3072 }) { + auto encs = [&](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 c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + c.max_spec = 3; + RadBuilder full; + encs(full); + REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + encs(small); + REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + // A capacity may shrink: its kernel writes by its operands' extents. + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) + continue; + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, + " R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), + a.ival, q.ival); + ++differ; + } + } + } + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } +} + +/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill + * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the + * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's + * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ +TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { + 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); + using Counts = std::map; + /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed + * and a shared clamped SwiGLU, and three dense ones. */ + struct Want { + const char* op; + int trunk, draft, prefill; + }; + const Want wants[] = { + { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, + { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, + { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, + }; + for (int world : { 1, 8 }) { + 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 = 0; + build.world_size = world; + build.max_tok = 512; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 0; + ctx.world = world; + ctx.batch = &batch; + Counts got[3]; + /* With the inverse, the fused selection writes it as its ninth operand and the gather + * reads it as its third. */ + const rad_buf inv = find_b(b, "expert_inverse") + ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) + : 0; + REQUIRE(inv != 0); + auto run = [&](int k) { + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + CHECK_LINT(b, &ctx); + for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; + for (const auto& is : ctx.issues) { + const RecOp* o = b.op_of(is.op); + if (!o) continue; + if (o->op == "router_sigmoid_topk_scatter") + CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && + is.opd[8].handle == inv); + if (o->op == "moe_gather_inv") + CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && + is.opd[2].handle == inv); + } + }; + run(0); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + run(1); + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.n_draft_out = 0; + batch.max_q_len = 512; + run(2); + for (int k = 0; k < 3; ++k) + for (const Want& w : wants) { + const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; + if (got[k][w.op] != want) + fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, + got[k][w.op], want); + CHECK_EQ(got[k][w.op], want); + } + } +} + +TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { + using namespace rad::arch; + for (bool front : { false, true }) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.max_seqs = 4; + g.max_spec = 3; + RadKVGroupDecl ad{}; + ad.kind = RAD_KV_FULL; + ad.dtype = RAD_BF16; + ad.n_head_kv = 1; + ad.head_dim = 256; + const auto attn = rad_decl_kv_group(&b, "attn", &ad); + // Claim the attention group's consumer before declaring the index group. + RAD_OP(&b, "mla_attn", RAD_PARAMS(RAD_INT("block_size", 4)), RAD_NOWEIGHTS); + RadKVGroupDecl td{}; + td.kind = RAD_KV_LINEAR; + td.dtype = RAD_BF16; + td.n_head_kv = 1; + td.state_dim[0] = 7; + td.state_dim[1] = 256; + const auto tail = rad_decl_kv_group(&b, "tail", &td); + DsaCache::Wire w; + w.query = decl_b(&b, "query", RAD_BF16, { 1024, 128 }); + w.codes = decl_b(&b, "codes", RAD_F8E4M3, { 1024, 128 }); + w.scales = decl_b(&b, "scales", RAD_F32, { 1024, 1 }); + w.gate = decl_b(&b, "gates", RAD_F32, { 32, 32 }); + w.kg = decl_b(&b, "kg", RAD_BF16, { 32, 256 }); + w.stage = decl_b(&b, "stage", RAD_BF16, { 48, 256 }); + w.page = decl_b(&b, "page", RAD_I32, { 12 }); + w.bpos = decl_b(&b, "bpos", RAD_I32, { 12 }); + w.nc = decl_b(&b, "nc", RAD_I32, { 4 }); + w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 }); + w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 }); + w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 }); + w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 }); + w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 }); + w.length = decl_b(&b, "len", RAD_I32, { 32 }); + DsaCache block; + DsaCache::Config cfg; + cfg.blocks = 1024; + cfg.work = 12; + cfg.ring = 7; + rad_kvgroup index = 0; + GlmIndexer indexer; + if (front) { + GlmIndexer::Wire iw; + iw.cache = w; + iw.input = decl_b(&b, "input", RAD_BF16, { 32, 4096 }); + iw.q_low = decl_b(&b, "q_low", RAD_BF16, { 32, 1536 }); + iw.q_wide = decl_b(&b, "q_wide", RAD_BF16, { 32, 4096 }); + iw.kg_raw = decl_b(&b, "kg_raw", RAD_BF16, { 32, 256 }); + REQUIRE_EQ(indexer.declare(&b, nm, g, 3, iw, "indexer", cfg, attn, tail, &index), + RAD_OK); + block = indexer.cache; + CHECK_EQ(b.weights[indexer.head_weight - 1].d.dtype, RAD_F32); + CHECK_EQ(b.weights[indexer.query.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[indexer.key_gate.w - 1].d.shard, RAD_SHARD_NONE); + } else + REQUIRE_EQ(block.declare(&b, nm, g, 3, cfg, w, attn, tail, &index, "indexer.pool.ape"), + RAD_OK); + CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8); + CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17); + int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{}; + RadKVGroupBatch kv[3]{}; + kv[0].group = index; + kv[0].block_table = ibt; + kv[0].block_table_pitch = 8; + kv[1].group = tail; + kv[1].state_index = sidx; + kv[1].state_index_pitch = 6; + kv[2].group = attn; + kv[2].block_table = abt; + kv[2].block_table_pitch = 8; + RadBatch batch{}; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_spec = 2; + batch.kv = kv; + batch.n_kv_groups = 3; + batch.positions = pos; + batch.cu_seqlens = cu; + batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns. + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + if (front) { + indexer.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)12); + CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy); + CHECK_EQ(ctx.issues[1].opd[1].rows, 256); + CHECK_EQ(ctx.issues[3].op, indexer.op_norm); + CHECK_EQ(ctx.issues[4].opd[0].offset, 128); + CHECK_EQ(ctx.issues[5].op, indexer.op_head); + ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6); + } else + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)6); + CHECK_EQ(ctx.issues[0].n, 256); + CHECK(ctx.issues[1].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[1].opd[4].cols, 6); + CHECK_EQ(ctx.issues[2].op, block.op_pool); + CHECK_EQ(ctx.issues[2].opd[5].handle, index); + CHECK_EQ(ctx.issues[3].op, block.op_tail); + CHECK_EQ(ctx.issues[4].opd[0].rows, 256); + CHECK_EQ(ctx.issues[4].opd[3].handle, index); + CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE); + CHECK(ctx.issues[4].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[4].opd[8].cols, 8); + CHECK_EQ(ctx.issues[5].opd[0].cols, 8); + CHECK(ctx.issues[5].opd[1].raw == abt); + } +} + +TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.n_ff = 3072; + g.max_tok = 32; + g.world = 4; + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "ffn_gate_up", fp8 }, { "ffn_down", fp8 } }; + MlpFP8::Wire w; + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.h.x = decl_b(&b, "h", RAD_BF16, { 32, 4096 }); + REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); + w.gate_up = decl_b(&b, "gate_up", RAD_BF16, { 32, 6144 }); + w.ffn.x = decl_b(&b, "ffn", RAD_BF16, { 32, 3072 }); + REQUIRE_EQ(w.ffn.declare_qs(&b, nm, g, "ffn", 3072), RAD_OK); + MlpFP8 block; + MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", + "mlp.up_proj.weight", "mlp.down_proj.weight" }; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); + CHECK_EQ(block.op_gated, 0u); + CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); + RadCtx ctx; + ctx.b = &b; + block.slice(&ctx, 8, 4, 4); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 1); + CHECK(std::find(ops.begin(), ops.end(), "gemm_nt_q_gated") == ops.end()); + CHECK(std::find(ops.begin(), ops.end(), "quant_act_fp8") != ops.end()); +} + +TEST(glm_mla_stores_one_normalized_latent_and_exposes_q_lora_before_sparse_attention) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const auto kv = rad_decl_kv_group(&b, "latent", &kd); + auto buf = [&](const char* name, int64_t n) { + return decl_b(&b, name, RAD_BF16, { 32, n }); + }; + GlmMla::Wire w; + w.input.x = buf("input", 4096); + w.q_raw = buf("q_raw", 1536); + w.kv_raw = buf("kv_raw", 512); + w.q_low.x = buf("q_low", 1536); + w.latent = buf("latent_out", 512); + w.out = buf("out", 4096); + REQUIRE_EQ(w.input.declare_qs(&b, nm, g, "input", 4096), RAD_OK); + REQUIRE_EQ(w.q_low.declare_qs(&b, nm, g, "q_low", 1536), RAD_OK); + w.core.q = buf("q", 4096); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { 32, 16, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { 32, 16, 512 }); + w.core.out = buf("expanded", 4096); + w.attn.x = w.core.out; + REQUIRE_EQ(w.attn.declare_qs(&b, nm, g, "expanded", 4096), RAD_OK); + w.core.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { 32 }); + GlmMla block; + REQUIRE_EQ(block.declare(&b, nm, g, 3, w, "attn", kv), RAD_OK); + CHECK_EQ(b.weights[block.q_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.q_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t slots[4]{}; + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots; + RadBatch batch{}; + batch.n_tok = 4; + batch.kv = &kb; + batch.n_kv_groups = 1; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.prepare(&ctx, &batch); + auto find_issue = [&](rad_op op) -> const RecIssue* { + for (const auto& issue : ctx.issues) + if (issue.op == op) return &issue; + return nullptr; + }; + const auto* store = find_issue(block.op_store); + REQUIRE(store); + CHECK_EQ(store->opd[0].handle, w.latent); + CHECK_EQ(store->opd[0].cols, 256); + CHECK_EQ(store->opd[1].offset, 256); + CHECK_EQ(store->opd[1].cols, 256); + CHECK(store->opd[2].raw == slots); + const auto before = issued_ops(b, ctx); + CHECK(std::find(before.begin(), before.end(), "mla_attn") == before.end()); + block.finish(&ctx, &batch); + const auto* attn = find_issue(block.core.op_attn); + REQUIRE(attn); + CHECK_EQ(attn->opd[2].handle, w.core.selected); + CHECK_EQ(ctx.issues.back().op, block.op_ar); + } +} + +TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const auto state = rad_decl_kv_group(&b, "state", &sd), + history = rad_decl_kv_group(&b, "conv", &cd); + auto buf = [&](const char* name, int64_t width) { + return decl_b(&b, name, RAD_BF16, { 32, width }); + }; + GlmKda::Wire w; + w.input = buf("input", 4096); + w.forget_low = buf("forget_low", 128); + w.gate_low = buf("gate_low", 128); + w.out = buf("out", 4096); + w.core.qkv = buf("qkv", 6144); + w.core.conv = buf("conv_out", 6144); + w.core.a = buf("a", 2048); + w.core.beta = buf("beta", 16); + w.core.gate = buf("gate", 2048); + w.core.out = buf("core_out", 2048); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + GlmKda block; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, "attn", src, state, history), RAD_OK); + CHECK_EQ(b.weights[block.qkv.w - 1].d.n_row_parts, 3); + CHECK_EQ(b.weights[block.forget_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.forget_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t cu[] = { 0, 4 }, ctxlens[] = { 0 }, indices[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = state; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = history; + kv[1].state_index = ci; + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 4; + batch.n_seq = 1; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); + CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); + REQUIRE_EQ(ctx.issues.size(), (size_t)11); + CHECK_EQ(ctx.issues[9].op, block.output.op); + CHECK_EQ(ctx.issues[10].op, block.op_ar); + CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); + } +} + +TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const rad_kvgroup st = rad_decl_kv_group(&b, "state", &sd), + cv = rad_decl_kv_group(&b, "conv", &cd); + KdaState::Wire w; + w.qkv = decl_b(&b, "qkv", RAD_BF16, { 32, 6144 }); + w.conv = decl_b(&b, "filtered", RAD_BF16, { 32, 6144 }); + w.a = decl_b(&b, "a", RAD_BF16, { 32, 2048 }); + w.beta = decl_b(&b, "beta", RAD_BF16, { 32, 16 }); + w.gate = decl_b(&b, "gate", RAD_BF16, { 32, 2048 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 128 }); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + KdaState block; + KdaState::Config cfg; + REQUIRE_EQ(block.declare(&b, nm, g, 0, st, cv, cfg, w, src), RAD_OK); + CHECK_EQ(b.weights[block.taps - 1].d.n_row_parts, 3); + for (int p = 0; p < 3; ++p) CHECK_EQ(b.weights[block.taps - 1].d.row_parts[p], 2048); + CHECK_EQ(b.weights[block.bias - 1].d.shape[0], 2048); + for (rad_op op : { block.op_prefill, block.op_verify }) { + bool found = false; + for (const auto& p : b.ops[op - 1].p) + if (p.key == "state_form") { + CHECK_EQ(p.sval, std::string("anchor")); + found = true; + } + CHECK(found); + } + int32_t cu[] = { 0, 3, 8 }, ctxlens[] = { 11, 0 }, accepted[] = { 2, 1 }; + int32_t indices[] = { 0, 0, 0, 2, 2, 2, 1, 1, 1, 3, 3, 3 }, conv_indices[] = { 0, 1 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = st; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = cv; + kv[1].state_index = conv_indices; + kv[1].state_index_pitch = 1; + RadBatch batch{}; + batch.phase = RAD_PHASE_MIXED; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_seq_decode = 1; + batch.n_tok_decode = 3; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.num_accepted = accepted; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)5); + CHECK_EQ(ctx.issues[0].op, block.op_conv); + CHECK_EQ(ctx.issues[0].n, 3); + CHECK_EQ(ctx.issues[1].op, block.op_verify); + CHECK_EQ(ctx.issues[1].opd[0].cols, 2048); + CHECK_EQ(ctx.issues[1].opd[1].offset, 2048); + CHECK_EQ(ctx.issues[1].opd[2].offset, 4096); + CHECK_EQ(ctx.issues[2].op, block.op_conv); + CHECK_EQ(ctx.issues[2].n, 8); + CHECK(ctx.issues[2].opd[3].raw == cu + 1); + CHECK_EQ(ctx.issues[2].opd[7].kind, RAD_OPK_NONE); + CHECK_EQ(ctx.issues[3].op, block.op_prefill); + CHECK(ctx.issues[3].opd[8].raw == indices + 6); + CHECK(ctx.issues[3].opd[9].raw == cu + 1); + CHECK_EQ(ctx.issues[3].opd[0].offset, 0); + CHECK_EQ(ctx.issues[3].opd[0].rows, 8); + CHECK_EQ(ctx.issues[4].op, block.op_norm); +} + +/* ==================================================================== the pinned graph and steps */ + +/* 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" }; + 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); + struct Case { + int world; + uint64_t graph, steps; + }; + const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, + { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; + for (const Case& cs : cases) { + 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 ctx = spec_ctx(0, cs.world, 3); + ctx.max_tok = 4096; + ctx.max_seqs = 8; + ctx.max_ctx = 200000; + 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); + CHECK_EQ(g, cs.graph); + CHECK_EQ(s, cs.steps); + } +} + +/* ==================================================================== fixtures */ +namespace { + +/* GLM-5.3-Flash's container keys, the four the plugin reads. */ +MetaKV glm53_meta() { + RadModelMeta m{}; + m.n_layers = 45; + m.n_embd = 4096; + m.n_vocab = 154880; + m.rms_eps = 1e-5f; + MetaKV k(m); + k.set("num_nextn_predict_layers", "1").set("hc_mult", "4").set("n_routed_experts", "288") + .set("index_topk", "2048"); + return k; +} + +/* The served container's encodings: block fp8 at f32 scales for the attention and dense linears + * and the MTP layer's experts, MXFP4 for the trunk's experts. */ +void glm53_encs(RadBuilder& b) { + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + 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 } }; +} + +/* A deployment of 512 rows a step, four sequences, 4k of context. */ +RadBuildCtx glm53_ctx(int rank, int world, int max_spec = 3) { + RadBuildCtx c = spec_ctx(rank, world, max_spec); + c.max_tok = 512; + c.max_seqs = 4; + c.max_ctx = 4096; + return c; +} + +} /* namespace */ + +RAD_TEST_MAIN() + +/* ==================================================================== the op schemas */ +namespace { + +/* The op schemas the kernel libraries under $RADIANCE_HOME/kernels declare: libr4d's first, the + * served vocabulary, then libref's for what it lacks. Empty without a home or a library, as + * arch_test's libref vocabulary is. */ +struct OpSpec { + int n_operands = 0, w_req = 0, w_max = 0, n_tab = 0; +}; +struct LoadedSchemas { + std::map ops; + bool r4d = false; +}; +const LoadedSchemas& loaded_schemas() { + static LoadedSchemas s; + static bool tried = false; + if (tried) return s; + tried = true; + const char* home = std::getenv("RADIANCE_HOME"); + if (!home) return s; + for (const char* lib : { "libr4d.so", "libref.so" }) { + const std::string path = std::string(home) + "/kernels/" + lib; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { + fprintf(stderr, " cannot load %s: %s\n", path.c_str(), dlerror()); + continue; + } + auto count = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto at = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!count || !at) continue; + for (int i = 0; i < count(); ++i) { + const RadOpSchema* sc = at(i); + if (!sc || !sc->op || s.ops.count(sc->op)) continue; + OpSpec spec; + spec.n_operands = sc->n_operands; + for (int k = 0; sc->operands && k < sc->n_operands; ++k) { + if (sc->operands[k].role == RAD_OPD_WTAB) { + ++spec.n_tab; + } else if (sc->operands[k].role == RAD_OPD_WEIGHT) { + ++spec.w_max; + if (!sc->operands[k].optional) ++spec.w_req; + } + } + s.ops[sc->op] = spec; + } + if (!std::strcmp(lib, "libr4d.so")) s.r4d = true; + } + return s; +} + +} /* namespace */ + +/* Every op the plugin issues carries as many operands as its schema declares, counted as + * core/runtime/issue.cpp counts them (an absent optional operand is one of them), and every op it + * 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. */ +TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) { + const LoadedSchemas& lib = loaded_schemas(); + if (lib.ops.empty()) { + fprintf(stderr, " no kernel library under $RADIANCE_HOME/kernels; nothing to count\n"); + return; + } + MetaKV mk = glm53_meta(); + std::set uncovered, wrong; + for (int world : { 8, 1 }) { + const int rank = world == 8 ? 3 : 0; + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_ctx(rank, world, 5); + ctx.max_tok = 4096; + ctx.max_seqs = 8; + ctx.max_ctx = 65536; + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + for (const RecOp& r : b.ops) { + auto it = lib.ops.find(r.op); + if (it == lib.ops.end()) { + uncovered.insert(r.op); + continue; + } + const OpSpec& s = it->second; + const int n_w = (int)r.w.size(); + const bool ok = s.n_tab > 0 ? n_w - s.w_max >= s.n_tab + : n_w >= s.w_req && n_w <= s.w_max; + if (!ok && wrong.insert(r.op + " (declare)").second) + fprintf(stderr, + " world %d: '%s' declares %d weights; the schema has %d (%d required) " + "and %d tables\n", + world, r.op.c_str(), n_w, s.w_max, s.w_req, s.n_tab); + } + std::vector> kits; + auto with_drafts = [&](std::unique_ptr k) { + auto his = history_pass(b, *k); + auto round = round_pass(b, k->b.n_seq, 2); + kits.push_back(std::move(k)); + kits.push_back(std::move(his)); + kits.push_back(std::move(round)); + }; + with_drafts(kit(b, { 1, 1 }, { 498 }, 100)); + with_drafts(kit(b, {}, { 255 })); + with_drafts(kit(b, { 6 }, {})); + with_drafts(kit(b, std::vector(6, 1), {})); + { + auto dec = kit(b, std::vector(8, 6), {}); + const int64_t pitch = 8192; + dec->table.resize((size_t)(8 * pitch)); + for (int64_t i = 0; i < 8 * 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; + kits.push_back(std::move(dec)); + } + std::vector passes; + for (const auto& k : kits) passes.push_back(k.get()); + auto v = run_passes(b, glm5next::step, passes, rank, world); + CHECK_PASSES(b, v); + for (size_t p = 0; p < v.size(); ++p) + for (const RecIssue& issue : v[p]->issues) { + const RecOp* op = b.op_of(issue.op); + REQUIRE(op); + auto it = lib.ops.find(op->op); + if (it == lib.ops.end()) { + uncovered.insert(op->op); + continue; + } + if ((int)issue.opd.size() != it->second.n_operands && wrong.insert(op->op).second) + fprintf(stderr, + " world %d pass %zu: '%s' issued with %zu operands; the schema " + "declares %d\n", + world, p, op->op.c_str(), issue.opd.size(), it->second.n_operands); + } + } + CHECK(wrong.empty()); + for (const auto& o : uncovered) fprintf(stderr, " no schema loaded for '%s'\n", o.c_str()); + if (lib.r4d) CHECK(uncovered.empty()); +} + +/* ==================================================================== the container's names */ +namespace { + +/* The served container, GLM-5.3-Flash-Quark-MXFP4.rad, as `rad-info -v` lists it: each weight's + * name and stored encoding, for the model, one KDA layer (0, with the dense feed-forward of + * layers 0 to 2), one MLA layer (3, with its experts 0 and 287) and the MTP layer under its + * `mtp.` scope (the fp8 linears of its layer under `mtp.mtp.`, as the converter wrote them). The + * other layers of a kind carry the same names at their own index. */ +struct ContainerWeight { + const char* name; + const char* enc; +}; +const ContainerWeight kGlm53Container[] = { + { "output.weight", "bf16" }, + { "output_norm.weight", "bf16" }, + { "token_embd.weight", "bf16" }, + { "blk.0.attn_beta.weight", "bf16" }, + { "blk.0.attn_forget_a.weight", "bf16" }, + { "blk.0.attn_forget_b.weight", "bf16" }, + { "blk.0.attn_gate_a.weight", "bf16" }, + { "blk.0.attn_gate_b.weight", "bf16" }, + { "blk.0.attn_norm.weight", "bf16" }, + { "blk.0.attn_output.weight", "bf16" }, + { "blk.0.attn_qkv.weight", "bf16" }, + { "blk.0.ffn_down.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.0.ffn_gate_up.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.0.ffn_norm.weight", "bf16" }, + { "blk.0.hc_attn.base", "f32" }, + { "blk.0.hc_attn.fn", "bf16" }, + { "blk.0.hc_attn.scale", "f32" }, + { "blk.0.hc_ffn.base", "f32" }, + { "blk.0.hc_ffn.fn", "bf16" }, + { "blk.0.hc_ffn.scale", "f32" }, + { "blk.0.ssm_a", "f32" }, + { "blk.0.ssm_conv.weight", "bf16" }, + { "blk.0.ssm_dt_bias", "f32" }, + { "blk.0.ssm_norm.weight", "bf16" }, + { "blk.3.attn_kv_a.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_kv_a_norm.weight", "bf16" }, + { "blk.3.attn_kv_b.weight", "bf16" }, + { "blk.3.attn_norm.weight", "bf16" }, + { "blk.3.attn_output.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_q_a.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_q_a_norm.weight", "bf16" }, + { "blk.3.attn_q_b.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.ffn_down_shexp.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_gate_up_shexp.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_norm.weight", "bf16" }, + { "blk.3.glm_router.correction", "f32" }, + { "blk.3.glm_router.weight", "bf16" }, + { "blk.3.hc_attn.base", "f32" }, + { "blk.3.hc_attn.fn", "bf16" }, + { "blk.3.hc_attn.scale", "f32" }, + { "blk.3.hc_ffn.base", "f32" }, + { "blk.3.hc_ffn.fn", "bf16" }, + { "blk.3.hc_ffn.scale", "f32" }, + { "blk.3.index_ape", "bf16" }, + { "blk.3.index_head.weight", "bf16" }, + { "blk.3.index_key_gate.weight", "bf16" }, + { "blk.3.index_norm.bias", "bf16" }, + { "blk.3.index_norm.weight", "bf16" }, + { "blk.3.index_query.weight", "bf16" }, + { "blk.3.ffn_gate_up_exps.0.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_down_exps.0.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_gate_up_exps.287.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_down_exps.287.weight", "fp4_e2m1*e8m0[1x32]" }, + { "mtp.blk.45.attn_kv_a_norm.weight", "bf16" }, + { "mtp.blk.45.attn_kv_b.weight", "bf16" }, + { "mtp.blk.45.attn_norm.weight", "bf16" }, + { "mtp.blk.45.attn_q_a_norm.weight", "bf16" }, + { "mtp.blk.45.ffn_norm.weight", "bf16" }, + { "mtp.blk.45.index_ape", "bf16" }, + { "mtp.blk.45.index_head.weight", "bf16" }, + { "mtp.blk.45.index_norm.bias", "bf16" }, + { "mtp.blk.45.index_norm.weight", "bf16" }, + { "mtp.eh_proj.weight", "bf16" }, + { "mtp.enorm.weight", "bf16" }, + { "mtp.hnorm.weight", "bf16" }, + { "mtp.mtp.blk.45.attn_kv_a.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_output.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_q_a.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_q_b.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.ffn_down_shexp.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.ffn_gate_up_shexp.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.glm_router.correction", "f32" }, + { "mtp.mtp.blk.45.glm_router.weight", "bf16" }, + { "mtp.mtp.blk.45.index_key_gate.weight", "bf16" }, + { "mtp.mtp.blk.45.index_query.weight", "bf16" }, + { "mtp.output_norm.weight", "bf16" }, + { "mtp.blk.45.ffn_gate_up_exps.0.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_down_exps.0.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_gate_up_exps.287.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_down_exps.287.weight", "fp8_e4m3*f32[128x128]" }, +}; + +RadEncoding container_enc(const std::string& e) { + if (e == "fp8_e4m3*f32[128x128]") return rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + if (e == "fp4_e2m1*e8m0[1x32]") return rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + if (e == "f32") return rad_enc_plain(RAD_F32); + if (e != "bf16") fprintf(stderr, " unknown container encoding '%s'\n", e.c_str()); + return rad_enc_plain(RAD_BF16); +} + +/* The table above expanded to every layer: a KDA layer's names from layer 0 (its dense + * feed-forward in layers 0 to 2 only), an MLA layer's from layer 3, the MoE's from layer 3 into + * every layer from 3. `encs` answers rad_weight_encoding as + * the container would; an expert's key stands without its index, so every expert matches it, + * and the keys run longest first, because the fake matches a key anywhere in the name asked + * (`output.weight` is inside `blk.3.attn_output.weight`). */ +struct Glm53Container { + std::set names; + std::map enc; + std::vector> encs; +}; +const Glm53Container& glm53_container() { + static Glm53Container c; + static bool built = false; + if (built) return c; + built = true; + std::set keys; + auto put = [&](const std::string& name, const char* e) { + if (!c.names.insert(name).second) return; + c.enc[name] = e; + std::string key = name; + const size_t ex = key.find("_exps."); + if (ex != std::string::npos) key = key.substr(0, ex + 5); + if (keys.insert(key).second) c.encs.push_back({ key, container_enc(e) }); + }; + auto at_layer = [](const std::string& n, size_t prefix, int l) { + return "blk." + std::to_string(l) + "." + n.substr(prefix); + }; + for (const ContainerWeight& w : kGlm53Container) { + const std::string n = w.name; + if (n.rfind("blk.0.", 0) == 0) { + const bool dense = n.find(".ffn_") != std::string::npos; + for (int l = 0; l < 45; ++l) + if (l % 4 != 3 && (!dense || l < 3)) put(at_layer(n, 6, l), w.enc); + } else if (n.rfind("blk.3.", 0) == 0) { + const bool moe = n.find(".ffn_") != std::string::npos || + n.find(".glm_router.") != std::string::npos; + for (int l = 3; l < 45; ++l) + if (moe || l % 4 == 3) put(at_layer(n, 6, l), w.enc); + } else { + put(n, w.enc); + } + } + std::stable_sort(c.encs.begin(), c.encs.end(), [](const auto& a, const auto& b) { + return a.first.size() > b.first.size(); + }); + return c; +} + +/* An expert's entry stands for its siblings: any index reads as expert 0's. */ +std::string as_expert_zero(std::string n) { + const size_t ex = n.find("_exps."); + if (ex == std::string::npos) return n; + const size_t dot = n.find('.', ex + 6); + return dot == std::string::npos ? n : n.substr(0, ex + 6) + "0" + n.substr(dot); +} + +} /* 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. */ +TEST(glm53_declares_the_served_containers_names_and_their_encodings) { + const Glm53Container& c = glm53_container(); + MetaKV mk = glm53_meta(); + for (int world : { 8, 1 }) { + RadBuilder b; + b.kv_block = 4; + b.encs = c.encs; + RadBuildCtx ctx = glm53_ctx(world == 8 ? 5 : 0, world); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + std::map declared; + for (const RecWeight& w : b.weights) declared[w.name] = &w; + // The stored entry a declared weight reads: itself, or its source, followed through views. + auto stored = [&](const RecWeight& w) { + std::string n = w.name; + for (int hops = 0; hops < 4; ++hops) { + auto it = declared.find(n); + if (it == declared.end() || !it->second->d.source || n == it->second->d.source) + break; + n = it->second->d.source; + } + return n; + }; + int missing = 0, optional_absent = 0; + for (const RecWeight& w : b.weights) { + const std::string n = as_expert_zero(stored(w)); + if (c.names.count(n)) continue; + if (w.d.optional) { + ++optional_absent; + continue; + } + if (++missing <= 24) + fprintf(stderr, " world %d: '%s' reads '%s', which the container does not hold\n", + world, w.name.c_str(), n.c_str()); + } + CHECK_EQ(missing, 0); + if (optional_absent) + fprintf(stderr, " world %d: %d optional weights the container does not hold\n", world, + optional_absent); + int wrong = 0; + for (const RecOp& r : b.ops) { + if (r.w.empty() || !r.w[0]) continue; + const bool quant = r.op == "gemm_nt_q" || r.op == "gemm_nt_q_gated" || + r.op == "gemm_nt_q_bias" || r.op == "moe_gemm_q" || + r.op == "moe_gemm_q_mod4"; + const bool plain = r.op == "gemm_nt" || r.op == "gemm_nt_bias" || + r.op == "logits_gemm" || r.op == "embed_lookup"; + if (!quant && !plain) continue; + const std::string n = as_expert_zero(stored(b.weights[r.w[0] - 1])); + auto e = c.enc.find(n); + if (e == c.enc.end()) continue; + const char* want = e->second == "fp8_e4m3*f32[128x128]" ? "fp8a8f32" + : e->second == "fp4_e2m1*e8m0[1x32]" ? "mxfp4a8" + : e->second == "bf16" ? "bf16" + : nullptr; + if (!want) continue; + if (quant == (e->second == "bf16") && ++wrong <= 24) { + fprintf(stderr, " world %d: '%s' over '%s' (%s)\n", world, r.op.c_str(), n.c_str(), + e->second.c_str()); + continue; + } + if (pstr(&r, "dtype") != want && ++wrong <= 24) + fprintf(stderr, " world %d: '%s' over '%s' (%s) at dtype %s, not %s\n", world, + r.op.c_str(), n.c_str(), e->second.c_str(), pstr(&r, "dtype").c_str(), want); + } + CHECK_EQ(wrong, 0); + } +}