diff --git a/arch/glm5next/CMakeLists.txt b/arch/glm5next/CMakeLists.txt new file mode 100644 index 00000000..4b695812 --- /dev/null +++ b/arch/glm5next/CMakeLists.txt @@ -0,0 +1,7 @@ +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(glm5next LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() +rad_add_plugin(glm5next architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/glm5next.cpp) diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp new file mode 100644 index 00000000..4b443707 --- /dev/null +++ b/arch/glm5next/glm5next.cpp @@ -0,0 +1,552 @@ +/* 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 +#include +#include +#include +#include +#include +#include + +namespace glm5next { +using namespace rad::arch; +struct Layer { + bool full = false, draft = false; + ManifoldConn attn_hc{}, ffn_hc{}; + NormQuantFP8 norm{}; + GlmKda kda{}; + GlmMla mla{}; + GlmIndexer index{}; + MlpFP8 dense{}; + MoeFP8 moe{}; + rad_op residual = 0; +}; +struct Model { + Names nm{}, dnm{ "mtp" }; + Geom g{}; + std::vector layers; + Layer draft{}; + rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; + 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{}; + GlmKda::Wire kw{}; + GlmMla::Wire aw{}; + GlmIndexer::Wire iw{}; + MlpFP8::Wire dw{}; + 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; + bool have_mtp = false; + bool fuse_router = false, fuse_swiglu = false, gather_inverse = false; +}; +static std::unique_ptr models[MAX_RANKS]; +static thread_local std::unique_ptr probe_model; + +static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { + char nested[160]; + 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) { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { x }, { y }); +} +static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) { + 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(w)), + { x }, { y }); +} +static int 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); + 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.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 }); + if (m.gather_inverse) 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_OK; +} +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; + 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))); + const auto gain = + decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096)); + if (lay.full) { + RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true)); + DsaCache::Config c; + c.blocks = (g.max_ctx + 3) / 4 + 1; + c.work = (g.max_tok + 3) / 4 + g.max_seqs; + c.ring = 4 + g.max_spec; + RAD_ARCH_TRY(lay.index.declare(b, nm, g, l, m.iw, nm.ckpt("%s.indexer", ap), c, m.latent, + m.tail, &m.index)); + RAD_ARCH_TRY(lay.mla.declare_finish(b, nm, ap)); + } else { + KdaState::Src s{ nm.ckpt("%s.q_conv1d.weight", ap), nm.ckpt("%s.k_conv1d.weight", ap), + nm.ckpt("%s.v_conv1d.weight", ap), nm.ckpt("%s.A_log", ap), + 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)); + } + 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); + } + if (l < 3) { + auto w = m.dw; + w.x = input; + MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre), + nm.ckpt("%s.mlp.gate_proj.weight", pre), + nm.ckpt("%s.mlp.up_proj.weight", pre), + nm.ckpt("%s.mlp.down_proj.weight", pre) }; + lay.dense.swiglu_quant = m.fuse_swiglu; + RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10)); + } else { + auto w = m.mw; + w.x = input; + MoeFP8::Src s; + s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre); + s.router = nm.ckpt("%s.mlp.gate.weight", pre); + s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre); + s.experts = nm.ckpt("%s.mlp.experts", pre); + 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.rows = g.max_tok; + s.cfg.sigmoid_router = 1; + s.cfg.route_scale = 2.5; + s.cfg.swiglu_limit = 10; + s.cfg.shared_ungated = 1; + s.cfg.router_fuse = m.fuse_router; + s.cfg.swiglu_quant = m.fuse_swiglu; + 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); + } + 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)); + } + if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b)); + return RAD_OK; +} +/* A decode fusion of the MoE block, on unless its variable is 0. Each is byte-identical to the + * launches it replaces, so the switch is about speed alone; 0 restores the separate launches. */ +static int fusion_switch(const char* name, bool* out) { + const char* e = std::getenv(name); + *out = true; + if (!e || !*e || !std::strcmp(e, "1")) return RAD_OK; + if (!std::strcmp(e, "0")) { + *out = false; + return RAD_OK; + } + fprintf(stderr, "radiance: %s='%s'; it is 0 or 1\n", name, e); + return RAD_E_INVAL; +} +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; + 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.n_vocab_all = 154880; + g.n_vocab = shard_extent(154880, world, ctx->rank); + g.vocab_off = shard_begin(154880, world, ctx->rank); + g.rank = ctx->rank; + g.world = world; + g.attn_world = world; + g.attn_rank = ctx->rank; + g.max_tok = ctx->max_tok; + g.max_ctx = ctx->max_ctx; + g.max_seqs = ctx->max_seqs; + g.max_spec = ctx->max_spec; + g.max_logit_rows = std::min(g.max_tok, g.max_seqs * (g.max_spec + 1)); + if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows; + 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(fusion_switch("RADIANCE_GLM_ROUTER_FUSE", &m.fuse_router)); + RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_SWIGLU_QUANT", &m.fuse_swiglu)); + RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_GATHER_INVERSE", &m.gather_inverse)); + 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); + 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"))); + RAD_ARCH_TRY( + map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight"))); + m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + m.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(m.token)), + {}, { m.x }); + m.embed_ar = 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)); + m.contract = rw(b, + RAD_OP(b, "mhc_contract", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_INT("hc", 4), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.h0 }, { m.x }); + m.norm = norm(b, g, m.final_gain, m.x, m.final_hidden); + m.gather = 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.final_hidden }, { m.logit_input }); + m.head_op = + 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.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)); + m.have_mtp = true; + } + rad_note(b, + "GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP %s", + world, m.have_mtp ? "enabled" : "disabled"); + return RAD_OK; +} +static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { + l.norm.step(c, batch->n_tok); + if (l.full) { + l.mla.prepare(c, batch); + l.index.step(c, batch); + l.mla.finish(c, batch); + } else + l.kda.step(c, batch); +} +static void step(RadCtx* c, const RadBatch* batch) { + auto& m = *models[rad_rank(c)]; + const int64_t T = batch->n_tok; + if (batch->enc) { + rad_step_fail(c, "GLM vision is not implemented by this text plugin"); + 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)); + return; + } + RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); + if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE); + for (int i = 0; i < 4; ++i) + RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T)); + for (int i = 0; i < 45; ++i) { + auto& l = m.layers[i]; + l.attn_hc.read(c, T); + attention(c, l, batch); + l.attn_hc.write(c, T); + l.ffn_hc.read(c, T); + if (i < 3) + l.dense.step(c, batch); + else + l.moe.step(c, batch); + l.ffn_hc.write(c, T); + } + RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), brows(m.x, T)); + RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T), + praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.logit_input, batch->n_out)); + RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head), + brows(m.logits, batch->n_out)); + } +} +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; + out->shape_probe_ok = 1; + return RAD_OK; +} +} // namespace glm5next +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(glm5next) +RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0", + "GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP") +#endif diff --git a/data/recipes/glm53-mxfp4.recipe b/data/recipes/glm53-mxfp4.recipe new file mode 100644 index 00000000..f8a805c1 --- /dev/null +++ b/data/recipes/glm53-mxfp4.recipe @@ -0,0 +1,4 @@ +# Decode only the small combined MLA projection, which the absorbed attention reads in bf16. +# Unmatched weights keep their stored encoding, including MXFP4 routed/shared experts +# and the mixed FP8/BF16 trunk and MTP weights. Covers trunk and draft scope names. +*attn_kv_b.weight cast dtype=bf16 diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index f858d8ba..84fbdf83 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -27,6 +27,8 @@ #include #include #include +#include +#include /* ==================================================================== the recording builder */ namespace { @@ -480,6 +482,16 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/embgemma2/embgemma2.cpp" /* Qwen-Image 2.1: a generator conditioned by Qwen3-VL. */ #include "../arch/qwenimage21/qwenimage21.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 { @@ -2298,6 +2310,1377 @@ 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; + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + 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; + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + 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); + } + { + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "64", 1); + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 128; + g.world = 8; + g.rank = 5; + GlmRouter::Config cfg; + cfg.rows = 128; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 128, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 128, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 128, 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); + RadCtx ctx; + router.step(&ctx, 0, 64); + router.step(&ctx, 0, 63); + REQUIRE_EQ(ctx.issues.size(), (size_t)5); + CHECK_EQ(ctx.issues[0].op, router.split.op_part); + CHECK_EQ(ctx.issues[3].op, router.op_project); + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "0", 1); + RadBuilder off; + GlmRouter whole; + auto w2 = w; + w2.input = decl_b(&off, "hidden", RAD_BF16, { 128, 4096 }); + w2.logits = decl_b(&off, "logits", RAD_F32, { 128, 288 }); + w2.ids = decl_b(&off, "ids", RAD_I32, { 128, 8 }); + w2.weights = decl_b(&off, "weights", RAD_F32, { 128, 8 }); + REQUIRE_EQ(whole.declare(&off, nm, g, 3, "blk.3.router", cfg, w2, src), RAD_OK); + CHECK_EQ(count_op(off, "all_gather"), 0); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + } +} + +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); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + 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); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + // 256 is the default threshold; at 2048 the 256- and 1024-row levels lie below it. + const int world = 8, rank = 3; + for (const char* split : { "256", "2048" }) + for (int64_t R : { 256, 3072 }) { + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", split, 1); + 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, + " split %s R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + split, (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]); + } + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); +} + +/* The MoE block's decode fusions (RADIANCE_GLM_*): each switch, alone and with the others, changes + * exactly its launches against the step without switches, over a two-row trunk step, its draft + * pass and a 512-row prefill (past the router fusion's one-workgroup sort), with the step lint + * clean throughout. A switch value other than 0 or 1 is refused. */ +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); + const char* const env[] = { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", + "RADIANCE_GLM_GATHER_INVERSE" }; + const int n_env = (int)(sizeof env / sizeof env[0]); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + auto clear = [&]() { + for (const char* e : env) unsetenv(e); + }; + using Counts = std::map; + /* Launches the first two switches remove (negative) and add, per step: trunk, draft pass, + * prefill. The trunk has 42 MoE layers, each a routed and a shared clamped SwiGLU, and three + * dense ones. The third turns every remaining sort and gather into its inverse form. */ + struct Delta { + const char* op; + int trunk, draft, prefill; + }; + const std::vector deltas[] = { + { { "router_sigmoid_topk_scatter", 42, 1, 0 }, + { "router_sigmoid_topk", -42, -1, 0 }, + { "moe_scatter", -42, -1, 0 }, + { "fill", -42, -1, 0 } }, + { { "swiglu_clamped_quant_fp8", 87, 2, 87 }, + { "swiglu_clamped", -87, -2, -87 }, + { "quant_act_fp8", -87, -2, -87 } }, + }; + for (int world : { 1, 8 }) { + Counts base[3]; + for (int mask = 0; mask < (1 << n_env); ++mask) { + // At one rank only the extremes: no switch reads the world. + if (world == 1 && mask && mask != (1 << n_env) - 1) continue; + for (int e = 0; e < n_env; ++e) setenv(env[e], mask >> e & 1 ? "1" : "0", 1); + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = 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; + CHECK_EQ(inv != 0, (mask & 4) != 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 || !inv) 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); + if (mask == 0) { + for (int k = 0; k < 3; ++k) base[k] = got[k]; + continue; + } + for (int k = 0; k < 3; ++k) { + Counts want = base[k]; + for (int e = 0; e < 2; ++e) + if (mask >> e & 1) + for (const Delta& d : deltas[e]) + want[d.op] += k == 0 ? d.trunk : k == 1 ? d.draft : d.prefill; + if (mask & 4) { + want["moe_scatter_inv"] += want["moe_scatter"]; + want["moe_scatter"] = 0; + want["moe_gather_inv"] += want["moe_gather"]; + want["moe_gather"] = 0; + } + for (auto it = want.begin(); it != want.end();) + it = it->second == 0 ? want.erase(it) : std::next(it); + if (got[k] != want) { + fprintf(stderr, " world %d switches %d step %d:", world, mask, k); + for (const auto& [op, n] : want) + if (got[k][op] != n) + fprintf(stderr, " %s %d (want %d)", op.c_str(), got[k][op], n); + for (const auto& [op, n] : got[k]) + if (!want.count(op)) fprintf(stderr, " %s %d (want 0)", op.c_str(), n); + fprintf(stderr, "\n"); + } + CHECK(got[k] == want); + } + } + } + for (const char* e : env) { + clear(); + setenv(e, "2", 1); + RadBuilder b; + RadBuildCtx build{}; + build.rank = 0; + build.world_size = 8; + build.max_tok = 64; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + CHECK_EQ(glm5next::declare(&b, &meta, &build), RAD_E_INVAL); + } + clear(); +} + +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, 0); + 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); + REQUIRE(rad_enc_valid(&mx)); + CHECK_EQ(MoeFP8::format_of(mx), 8); + for (int world : { 4, 8 }) + for (bool glm : { false, true }) + for (int rank = 0; rank < world; ++rank) { + const int64_t F = 2048 / world; + RadBuilder b; + b.encs = { { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = world; + g.rank = rank; + MoeFP8::Src src{}; + src.router = "mlp.gate.weight"; + src.experts = "mlp.experts"; + src.cfg.n_expert = src.cfg.n_expert_all = 288; + src.cfg.top_k = 8; + src.cfg.n_ff_exp = F; + src.cfg.rows = 32; + if (glm) { + src.router_bias = "mlp.gate.e_score_correction_bias"; + src.shared = "mlp.shared_experts"; + src.cfg.sigmoid_router = 1; + src.cfg.route_scale = 2.5; + src.cfg.swiglu_limit = 10; + src.cfg.shared_ungated = 1; + src.cfg.n_ff_shared = F; + } + for (int q = 0; q < 2; ++q) { + src.cfg.ff_lo[q] = rank * F; + src.cfg.ff_hi[q] = (rank + 1) * F; + } + REQUIRE_EQ(MoeFP8::probe(&b, nm, 3, src, &src.cfg), RAD_OK); + CHECK_EQ(src.cfg.expert_mx, 1); + CHECK_EQ(src.cfg.expert_w4, 0); + MoeFP8::Wire w{}; + auto buf = [&](const char* name, uint32_t dt, int64_t rows, int64_t cols) { + return decl_b(&b, name, dt, { rows, cols }); + }; + w.h.x = buf("h", RAD_BF16, 32, 4096); + REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); + w.logits = buf("logits", glm ? RAD_F32 : RAD_BF16, 32, 288); + w.ids = buf("ids", RAD_I32, 32, 8); + w.ew = buf("ew", glm ? RAD_F32 : RAD_BF16, 32, 8); + w.eoff = decl_b(&b, "offset", RAD_I32, { 289 }); + w.ecnt = decl_b(&b, "count", RAD_I32, { 288 }); + w.sorted = decl_b(&b, "sorted", RAD_I32, { 256 }); + w.egu = buf("gate_up", RAD_BF16, 256, 2 * F); + w.eff.x = buf("ff", RAD_BF16, 256, F); + REQUIRE_EQ(w.eff.declare_qs(&b, nm, g, "ff", F, 256), RAD_OK); + w.edn = buf("down", RAD_BF16, 256, 4096); + if (glm) { + w.sgu = buf("shared_gu", RAD_BF16, 32, 2 * F); + w.sff.x = buf("shared_ff", RAD_BF16, 32, F); + REQUIRE_EQ(w.sff.declare_qs(&b, nm, g, "shared_ff", F), RAD_OK); + w.sout = buf("shared_out", RAD_BF16, 32, 4096); + w.sgate = buf("shared_one", RAD_BF16, 32, 1); + } + MoeFP8 moe; + REQUIRE_EQ(moe.declare(&b, nm, g, 3, w, src, false, false), RAD_OK); + CHECK_EQ(moe.ncls, 2); + if (glm) { + CHECK_EQ(b.weights[moe.w_router - 1].d.dtype, RAD_F32); + CHECK_EQ(b.ops[moe.op_topk - 1].op, std::string("router_sigmoid_topk")); + CHECK_EQ(moe.op_topk_scatter, 0); + CHECK_EQ(moe.op_router_fused, 0); + CHECK_EQ(b.ops[moe.gq_exp.op - 1].op, std::string("swiglu_clamped")); + CHECK_EQ(b.ops[moe.gq_sh.op - 1].op, std::string("swiglu_clamped")); + CHECK_EQ(b.ops[moe.op_sgate - 1].op, std::string("fill")); + CHECK_EQ(moe.w_sgate, 0); + bool plain_shared = false; + for (const auto& p : b.ops[moe.op_gather - 1].p) + if (p.key == "act") plain_shared = p.sval == "none"; + CHECK(plain_shared); + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + moe.pass(&ctx, 8, 4, 4); + const auto ops = issued_ops(b, ctx); + CHECK(std::find(ops.begin(), ops.end(), "router_sigmoid_topk") != ops.end()); + CHECK(std::find(ops.begin(), ops.end(), "router_topk") == ops.end()); + CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 2); + CHECK_EQ(std::count(ops.begin(), ops.end(), "fill"), 1); + for (const auto& issue : ctx.issues) + if (issue.op == moe.op_sgate) { + REQUIRE_EQ(issue.opd.size(), (size_t)1); + CHECK_EQ(issue.opd[0].handle, w.sgate); + CHECK_EQ(issue.opd[0].offset, 4); + } + } + for (int e = 0; e < 288; ++e) { + const auto& gu = b.weights[moe.w_gu[e] - 1]; + const auto& gs = b.weights[moe.w_gus[e] - 1]; + const auto& dn = b.weights[moe.w_dn[e] - 1]; + const auto& ds = b.weights[moe.w_dns[e] - 1]; + CHECK_EQ(gu.d.dtype, RAD_FP4E2M1); + CHECK_EQ(dn.d.dtype, RAD_FP4E2M1); + CHECK_EQ(gs.d.dtype, RAD_E8M0); + CHECK_EQ(ds.d.dtype, RAD_E8M0); + CHECK_EQ(gs.d.shape[0], 2 * F); + CHECK_EQ(gs.d.shape[1], 128); + CHECK_EQ(ds.d.shape[0], 4096); + CHECK_EQ(ds.d.shape[1], F / 32); + CHECK_EQ(gu.span_lo, rank * F); + CHECK_EQ(gs.span_lo, rank * F); + CHECK_EQ(dn.span_lo, rank * F); + CHECK_EQ(ds.span_lo, rank * (F / 32)); + CHECK_EQ(gu.d.access, RAD_ACCESS_CONDITIONAL); + CHECK_EQ(dn.d.access, RAD_ACCESS_CONDITIONAL); + } + for (rad_op h : { moe.op_gu, moe.op_dn }) { + const RecOp* op = b.op_of(h); + REQUIRE(op != nullptr); + CHECK_EQ(op->op, std::string("moe_gemm_q")); + bool found = false; + for (const auto& p : op->p) + if (p.key == "dtype") { + CHECK_EQ(p.sval, std::string("mxfp4a8")); + found = true; + } + CHECK(found); + } + } +} + /* A quantised container may keep one linear as the checkpoint holds it. Flash-Next's recipe leaves * the QSA indexer's projection plain bf16 (its top-k is a hard choice between blocks), so in a * four-bit model with fp8 linears it is declared bf16 and read by `gemm_nt` over its input's bf16 @@ -8092,6 +9475,61 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } +/* With the decode fusions switched off, GLM declares and steps the graph and launches it had + * before them, 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_without_fusion_switches_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, 0xd48139cb64abf0b1ull, 0x6982726c635df529ull }, + { 8, 0x90fc5bc69f1cfb10ull, 0x197c95726131b817ull } }; + for (const char* e : + { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) + setenv(e, "0", 1); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + 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); + } + for (const char* e : + { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) + unsetenv(e); +} + /* 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/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index e471b4c5..10bc8aa2 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -89,8 +89,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { } const std::set> want = { { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" }, - { "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, - { "qwen35", "" }, + { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, + { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };