arch/common: GLM-5.3's blocks, and f32 scales, MXFP4 experts and sigmoid routing in the shared ones

New blocks: mHC (rad_block_mhc.h), KDA and its state (rad_block_glm_kda.h,
rad_block_kda_state.h), absorbed MLA over a latent cache (rad_block_glm_mla.h,
rad_block_mla_latent.h), the DSA indexer and its paged key cache (rad_block_glm_indexer.h,
rad_block_dsa_cache.h), the correction-bias router (rad_block_glm_router.h), and rad_tp_split.h:
a replicated f32 projection computed column-split over the ranks and all-gathered, so every value
is the replicated one's bits (from RADIANCE_GLM_TP_SPLIT_ROWS rows, 256 by default).

The shared blocks gain what GLM's checkpoint stores, each off unless a model asks for it:

- LinearFP8 reads a block-fp8 weight whose scale plane is f32 (dtype fp8a8f32), and the import
  check accepts that form beside bf16 scales.
- GateQuantFP8 serves a clamped SwiGLU (swiglu_clamped), optionally fused with its quantiser.
- MoeFP8 takes MXFP4 experts (format 8) and block-fp8 experts with f32 scales (format 9), the
  sigmoid router with f32 weights, an ungated shared arm, the router/scatter fusion and the
  sort's inverse handed to the gather (moe_scatter_inv, moe_gather_inv) where they resolve.
- The MLP's gated fold excludes the forms it cannot serve (f32 scales, a clamped product).

share_test checks that KDA's convolution weight shards per head across its three parts at TP4.
This commit is contained in:
John McDonough authored and StillDeadcode committed 2026-10-19 20:13:47 +02:00
1 parent 78c58841bf
commit 544753fc40
13 files changed
+1296 -61

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
/* 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
+109
View File
@@ -0,0 +1,109 @@
/* Replicated GLM indexer front end. Casts bridge ordinary linear rows to the
* flattened per-head quantizer and join normalized keys with learned pool gates. */
#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"
namespace rad {
namespace arch {
struct GlmIndexer {
struct Wire {
rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0;
DsaCache::Wire cache{};
};
Geom g{};
Wire w{};
LinearFP8 query{}, key_gate{};
DsaCache cache{};
rad_weight gain = 0, bias = 0, head_weight = 0;
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
SplitF32Proj head_split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention,
rad_kvgroup tail, rad_kvgroup* index) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || !w.input || !w.q_low || !w.q_wide || !w.kg_raw)
return RAD_E_INVAL;
Geom bg = g;
bg.w_bf16 = true;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
RAD_ARCH_TRY(query.declare(b, nm, bg, nm.f("blk.%d.index_query", l), 4096, 1536,
RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wq_b.weight", prefix) }, act(w.q_low), w.q_wide));
RAD_ARCH_TRY(key_gate.declare(
b, nm, bg, nm.f("blk.%d.index_key_gate", l), 256, 4096, RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wk.weight", prefix), nm.ckpt("%s.index_kpool_compress_gate", prefix) },
act(w.input), w.kg_raw, 0, { 128, 128 }));
const char *gn = nm.f("blk.%d.index_norm.weight", l),
*bn = nm.f("blk.%d.index_norm.bias", l),
*hn = nm.f("blk.%d.index_head.weight", l);
RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.k_norm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.k_norm.bias", prefix)));
RAD_ARCH_TRY(map_copy(b, hn, nm.ckpt("%s.weights_proj.weight", prefix)));
gain = decl_w(b, gn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
head_weight = decl_w(b, hn, RAD_F32, { 32, 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!gain || !bias || !head_weight) return RAD_E_INVAL;
op_norm = rw(b,
RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain, bias)),
{ w.kg_raw }, { w.cache.kg });
op_query_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.q_wide }, { w.cache.query });
op_gate_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.kg_raw }, { w.cache.kg });
op_head = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32),
RAD_INT("K", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(head_weight)),
{ w.input }, { w.cache.gate });
RAD_ARCH_TRY(head_split.declare(b, nm, g, nm.f("blk.%d.index_head", l), g.max_tok, 32, 4096,
head_weight, w.input, w.cache.gate));
RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index,
nm.ckpt("%s.index_kpool_compress_ape", prefix)));
return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
query.step(ctx, act(w.q_low), w.q_wide, T);
RAD_ISSUE_N(ctx, op_query_copy, T * 32, brows(w.q_wide, T), brows(w.cache.query, T * 32));
key_gate.step(ctx, act(w.input), w.kg_raw, T);
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
bcol(w.cache.kg, 0, 128, T));
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
bcol(w.cache.kg, 128, 128, T));
if (head_split.takes(T))
head_split.step(ctx, T, brows(w.input, T), head_weight, brows(w.cache.gate, T));
else
RAD_ISSUE_N(ctx, op_head, T, brows(w.input, T), RAD_W(head_weight),
brows(w.cache.gate, T));
cache.step(ctx, batch);
}
};
}
} // namespace rad::arch
#endif
+102
View File
@@ -0,0 +1,102 @@
/* 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. */
#ifndef RAD_BLOCK_GLM_KDA_H
#define RAD_BLOCK_GLM_KDA_H
#include "rad_fp8.h"
#include "rad_block_kda_state.h"
namespace rad {
namespace arch {
struct GlmKda {
struct Wire {
rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0;
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire,
const char* prefix, const KdaState::Src& src, rad_kvgroup state,
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 ||
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 auto group = grp_layer(layer);
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
RAD_ARCH_TRY(qkv.declare(
b, nm, bg, nm.f("blk.%d.attn_qkv", layer), 3 * width, 4096, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.q_proj.weight", prefix), nm.ckpt("%s.k_proj.weight", prefix),
nm.ckpt("%s.v_proj.weight", prefix) },
input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096,
RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) },
input, w.core.beta));
RAD_ARCH_TRY(forget_a.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group,
{ nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low));
RAD_ARCH_TRY(forget_b.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a));
RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096,
RAD_SHARD_NONE, group,
{ nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low));
RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128,
RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) },
act(w.gate_low), w.core.gate));
KdaState::Config cfg;
cfg.heads = heads;
RAD_ARCH_TRY(core.declare(b, nm, bg, layer, state, history, cfg, w.core, src));
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
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 });
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
qkv.step(ctx, input, w.core.qkv, T);
beta.step(ctx, input, w.core.beta, T);
forget_a.step(ctx, input, w.forget_low, T);
forget_b.step(ctx, act(w.forget_low), w.core.a, T);
gate_a.step(ctx, input, w.gate_low, T);
gate_b.step(ctx, act(w.gate_low), w.core.gate, T);
core.step(ctx, batch);
output.step(ctx, act(w.core.out), w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+118
View File
@@ -0,0 +1,118 @@
/* No-RoPE GLM MLA. prepare() exposes normalized Q-lora for the replicated
* indexer; finish() consumes its selection. The caller owns the mHC residual. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_block_mla_latent.h"
namespace rad {
namespace arch {
struct GlmMla {
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
LinearFP8 q_a{}, kv_a{}, q_b{}, output{};
NormQuantFP8 q_norm{};
QuantFP8 attn_quant{};
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, rad_kvgroup group, bool reduce = true,
bool defer_finish = false) {
g = geom;
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 ||
w.attn.x != w.core.out)
return RAD_E_INVAL;
const auto wg = grp_layer(l);
RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), 1536, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.q_a_proj.weight", prefix) }, w.input, w.q_raw));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), 512, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", prefix) }, w.input,
w.kv_raw));
const char* qn = nm.f("blk.%d.attn_q_a_norm.weight", l);
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, qn, nm.ckpt("%s.q_a_layernorm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", prefix)));
q_gain = decl_w(b, qn, RAD_F32, { 1536 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
kv_gain = decl_w(b, kn, RAD_F32, { 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!q_gain || !kv_gain) return RAD_E_INVAL;
RAD_ARCH_TRY(q_norm.declare(b, g, q_gain, w.q_raw, w.q_low, 1536));
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 512),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", "bf16")),
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) },
w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
return defer_finish ? RAD_OK : declare_finish(b, nm, prefix, reduce);
}
int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) {
MlaLatent::Config cfg;
cfg.heads = 64 / 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(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
16384 / 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 });
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
}
void prepare(RadCtx* ctx, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping) {
rad_step_fail(ctx, "GLM MLA requires latent cache slot mapping");
return;
}
const int64_t T = batch->n_tok;
q_a.step(ctx, w.input, w.q_raw, T);
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
q_b.step(ctx, w.q_low, w.core.q, T);
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+82
View File
@@ -0,0 +1,82 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* 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 <cmath>
namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
int norm = 1;
double route_scale = 2.5;
};
struct Src {
const char *weight = nullptr, *correction = nullptr;
};
struct Wire {
rad_buf input = 0, logits = 0, ids = 0, weights = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight projection = 0, correction = 0;
rad_op op_project = 0, op_select = 0;
SplitF32Proj split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
RAD_ARCH_TRY(map_copy(b, cn, src.correction));
projection = decl_w(b, pn, RAD_F32, { c.experts, g.n_embd }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
correction = decl_w(b, cn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
if (!projection || !correction) return RAD_E_INVAL;
op_project = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.experts),
RAD_INT("K", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits));
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
}
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
if (split.takes(rows))
split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection,
brow_slice(w.logits, output_first, rows, c.experts));
else
RAD_ISSUE_N(ctx, op_project, rows, brow_slice(w.input, first, rows, g.n_embd),
RAD_W(projection), brow_slice(w.logits, output_first, rows, c.experts));
}
void step(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
project(ctx, first, rows, output_first);
RAD_ISSUE_N(ctx, op_select, rows, brow_slice(w.logits, output_first, rows, c.experts),
RAD_W(correction), brow_slice(w.ids, output_first, rows, c.top_k),
brow_slice(w.weights, output_first, rows, c.top_k));
}
};
}
} // namespace rad::arch
#endif
+128
View File
@@ -0,0 +1,128 @@
/* 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 <cmath>
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
+136
View File
@@ -0,0 +1,136 @@
/* 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"
#include <cmath>
namespace rad {
namespace arch {
struct ManifoldConn {
struct Config {
int64_t hc = 4, iterations = 20;
double eps = 1e-6, hc_eps = 1e-6;
};
struct Src {
const char *fn = nullptr, *scale = nullptr, *base = nullptr;
};
struct Wire {
rad_buf h = 0, x = 0, y = 0, out = 0;
// Saved by read(), consumed by write() after the block produces y.
rad_buf post = 0, comb = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight w_fn = 0, w_scale = 0, w_base = 0;
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). */
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;
int64_t split_rows = 0, part_row = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src, bool defer_post = false) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 ||
c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 ||
!std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 ||
!w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x ||
w.h == w.y || w.x == w.out || w.y == w.out || w.post == w.comb)
return RAD_E_INVAL;
const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2);
const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name),
*base = nm.f("%s.base", name);
RAD_ARCH_TRY(map_copy(b, fn, src.fn));
RAD_ARCH_TRY(map_copy(b, scale, src.scale));
RAD_ARCH_TRY(map_copy(b, base, src.base));
// Mixing coefficients are F32 in the checkpoint; keep them replicated under TP.
const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight ws = w_scale = decl_w(b, scale, RAD_F32, { 3 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!wf || !ws || !wb) return RAD_E_INVAL;
op_pre = rw(b,
RAD_OP(b, "mhc_pre",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wf, ws, wb)),
{ w.h }, { w.x, w.post, w.comb });
if (!op_pre) return RAD_E_INVAL;
RAD_ARCH_TRY(declare_split(b, nm, name));
return defer_post ? RAD_OK : declare_post(b);
}
int declare_split(RadBuilder* b, Names& nm, const char* name) {
const int64_t total = c.hc * g.n_embd / kChunk;
split_rows = glm_tp_split_rows();
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || !split_rows || total % g.world) {
split_rows = 0;
return RAD_OK;
}
const int64_t mine = total / g.world, T = g.max_tok;
part_row = mine * kPartStride;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { T, part_row });
parts = decl_b(b, nm.f("%s.parts", name), RAD_F32, { T, total * kPartStride });
op_partial =
rw(b,
RAD_OP(b, "mhc_pre_partial",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc),
RAD_INT("chunk", kChunk), RAD_INT("first", g.rank * mine),
RAD_INT("chunks", mine), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fn)),
{ w.h }, { part });
op_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", part_row, T * part_row),
RAD_STR("dtype", "f32"), RAD_INT("row", part_row)),
RAD_NOWEIGHTS),
{ part }, { parts });
op_finish = rw(b,
RAD_OP(b, "mhc_pre_finish",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_INT("chunk", kChunk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_scale, w_base)),
{ parts, w.h }, { w.x, w.post, w.comb });
return part && parts && op_partial && op_gather && op_finish ? RAD_OK : RAD_E_INVAL;
}
int declare_post(RadBuilder* b) {
op_post = rw(b,
RAD_OP(b, "mhc_post",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ w.y, w.h, w.post, w.comb }, { w.out });
return op_post ? RAD_OK : RAD_E_INVAL;
}
void read(RadCtx* ctx, int64_t rows) const {
if (split_rows && rows >= split_rows) {
RAD_ISSUE_N(ctx, op_partial, rows, brows(w.h, rows), RAD_W(w_fn), brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * part_row, brows(part, rows), brows(parts, rows));
RAD_ISSUE_N(ctx, op_finish, rows, brows(parts, rows), brows(w.h, rows), RAD_W(w_scale),
RAD_W(w_base), brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
return;
}
RAD_ISSUE_N(ctx, op_pre, rows, brows(w.h, rows), RAD_W(w_fn), RAD_W(w_scale), RAD_W(w_base),
brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
}
void write(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_post, rows, brows(w.y, rows), brows(w.h, rows), brows(w.post, rows),
brows(w.comb, rows), brows(w.out, rows));
}
};
}
} // namespace rad::arch
#endif
+84
View File
@@ -0,0 +1,84 @@
/* 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 <cmath>
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
+14 -7
View File
@@ -60,13 +60,16 @@ struct MlpFP8 {
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
bool ar_out = false;
/* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch
* (GateQuantFP8::fuse_clamped). */
bool swiglu_quant = false;
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
* rad_fp8.h. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
@@ -76,7 +79,7 @@ struct MlpFP8 {
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_) {
int ar_in, bool ar_out_, double swiglu_limit) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -96,12 +99,16 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */
const char* down_base = nm.f("blk.%d.ffn_down", l);
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
gq_ffn.fuse_clamped = swiglu_quant;
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x,
false, swiglu_limit));
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit, 4-bit and int8
* gate_up weights take the pair. Declared over int8 codes, only a host kernel would take it,
* and that would pin the layer's weights to the host. */
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
* weights to the host. */
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
!gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q, w.h.s },
gq_ffn.want_x
+205 -47
View File
@@ -48,6 +48,7 @@
#define RAD_BLOCK_MOE_FP8_H
#include "rad_fp8.h"
#include "rad_block_glm_router.h"
#include "rad_device.h"
#include <cstdio>
@@ -72,8 +73,10 @@ static const int64_t kMoeRouterFusedRows = 64;
*
* The core's histogram (core/runtime/ctx.cpp) shows which experts were chosen and dbg_resid shows
* each arm's magnitude; neither shows the weights, so a top-k that sums to 0.4 instead of 1 would
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) {
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all.
* `f32`: the weights are f32 rather than bf16 (the sigmoid router). */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew,
bool f32 = false) {
static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
if (!dbg || !ids || !ew) return;
static const int want = (int)std::strtol(dbg, nullptr, 10);
@@ -85,8 +88,9 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
RadStream s = rad_stream(c_);
std::vector<int32_t> vi((size_t)top_k);
std::vector<uint16_t> vw((size_t)top_k);
std::vector<float> vf((size_t)top_k);
rad_memcpy_async(vi.data(), pi, top_k * 4, s);
rad_memcpy_async(vw.data(), pw, top_k * 2, s);
rad_memcpy_async(f32?(void*)vf.data():(void*)vw.data(), pw, top_k * (f32?4:2), s);
rad_stream_sync(s);
std::string line;
@@ -95,6 +99,7 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
const uint32_t u = (uint32_t)vw[(size_t)r] << 16;
float f;
std::memcpy(&f, &u, 4);
if (f32) f = vf[(size_t)r];
sum += f;
char b[48];
std::snprintf(b, sizeof b, "%s%d:%.4f", r ? " " : "", vi[(size_t)r], f);
@@ -167,6 +172,23 @@ struct MoeFP8 {
* units a routed GEMM's tail leaves idle. */
int64_t shared_lo = 0, shared_hi = 0;
int norm_topk = 1; /* renormalise the kept routing weights to sum to one */
/* GLM routing (GlmRouter): sigmoid scores with a correction bias, top-k, `route_scale` on
* the kept weights, which are then f32 in `ew`. */
int sigmoid_router = 0;
/* With `sigmoid_router`: the selection, the scatter and an ungated shared arm's gate fill in
* one launch (`router_sigmoid_topk_scatter`) wherever the pass fits the sort's one
* workgroup; the separate ops otherwise. Byte-identical either way. */
int router_fuse = 0;
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0;
double route_scale = 1.0;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0;
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
int shared_ungated = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
* registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -176,6 +198,8 @@ struct MoeFP8 {
* A packed 4-bit row is K/2 bytes, so a width shard must fall on a scale group; declare()
* checks this per rank. */
int expert_w4 = 0;
/* OCP E2M1 codes with E8M0 scales per 32 of K; kept canonical for host-tier reads. */
int expert_mx = 0;
/* Rotated: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and the
* activation meeting it (the encoding's `fwht128` transform, dtype `w4a8h`; only with
* `expert_w4`).
@@ -242,11 +266,14 @@ struct MoeFP8 {
/* the routing, one row per token */
rad_buf logits = 0; /* [max_tok, n_expert_all] bf16, the model's expert count */
rad_buf ids = 0; /* [max_tok, top_k] i32 */
rad_buf ew = 0; /* [max_tok, top_k] bf16 */
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
rad_buf eoff = 0; /* [n_expert + 1] i32 */
rad_buf ecnt = 0; /* [n_expert] i32 */
/* the expert planes, one row per (token, slot), a pass tall */
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
* table (moe_scatter_inv, moe_gather_inv). Optional. */
rad_buf inv = 0; /* [rows * top_k] i32 */
rad_buf egu = 0; /* [rows * top_k, 2 * n_ff_exp] bf16 */
ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */
rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */
@@ -268,6 +295,7 @@ struct MoeFP8 {
Config cfg{};
const char* norm = nullptr;
const char* router = nullptr; /* mlp.gate.weight, [n_expert, n_embd] bf16 */
const char* router_bias = nullptr; /* GLM noaux_tc correction bias */
const char* experts = nullptr; /* prefix; ".<e>.{gate,up,down}_proj.weight" */
const char* shared = nullptr; /* prefix; ".{gate,up,down}_proj.weight" */
/* Stacked checkpoints (recent releases) store all experts in two tensors:
@@ -287,6 +315,7 @@ struct MoeFP8 {
int layer = 0;
rad_weight w_norm = 0, w_router = 0, w_sgate = 0;
GlmRouter glm_router{};
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
/* The weight runs. Only the first handle and the count reach an issue (RAD_WTAB); the rest are
@@ -297,6 +326,9 @@ struct MoeFP8 {
GateQuantFP8 gq_exp{}, gq_sh{};
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
* the gather reads it (Wire::inv). */
bool scatter_inv = false, gather_inv = false;
/* `router_topk_scatter`, if it resolves: topk and scatter in one launch. The pair is declared
* either way, since the fused form is bounded by the sort's single workgroup and a prefill
* chunk exceeds it. */
@@ -308,6 +340,11 @@ struct MoeFP8 {
rad_op op_router_fused = 0;
int64_t router_fused_rows = 0;
bool router_fused_gate = false;
/* `router_sigmoid_topk_scatter` (Config::router_fuse), up to `sigmoid_scatter_rows` tokens,
* writing the shared gate's fill too when `sigmoid_scatter_gate`. */
rad_op op_sigmoid_scatter = 0;
int64_t sigmoid_scatter_rows = 0;
bool sigmoid_scatter_gate = false;
/* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and
* the caller does not already write `w.hr`. */
rad_op op_hq = 0;
@@ -390,11 +427,11 @@ struct MoeFP8 {
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
* five-bit form per 64; RAD_E_DTYPE otherwise. */
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
static int format_of(const RadEncoding& e);
/* format_of's numbers as the grouped GEMMs' dtype strings. */
static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h" };
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
@@ -424,6 +461,7 @@ struct MoeFP8 {
};
inline int MoeFP8::format_of(const RadEncoding& e) {
if (linear_is_mxfp4(e)) return 8;
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
@@ -443,7 +481,11 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
return 7;
return RAD_E_DTYPE;
}
if (!sc || sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (!sc) return RAD_E_DTYPE;
if (e.n_planes == 2 && e.plane[0].dtype == RAD_F8E4M3 && sc->dtype == RAD_F32 &&
!e.transform[0] && sc->block[0] == 128 && sc->block[1] == 128)
return 9;
if (sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (e.n_planes == 3) {
const RadEncPlane* t = rad_enc_plane(&e, "table");
if (t && t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 &&
@@ -530,7 +572,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
"(fp8_e4m3*bf16[128x128]), four-bit (i4*bf16[1x128], optionally "
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
"f32, or its 32-entry five-bit form at a 64. "
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
"(fp4_e2m1*e8m0[1x32]). "
"Convert it with a recipe that makes one of them.\n", guw, en);
return RAD_E_DTYPE;
}
@@ -542,6 +585,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w5 = f == 7 ? 1 : 0;
cfg->expert_bf16 = f == 3 ? 1 : 0;
cfg->expert_mx = f == 8 ? 1 : 0;
cfg->expert_f32_scale = f == 9 ? 1 : 0;
return RAD_OK;
}
@@ -560,6 +605,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
* all-reduce carries the others' share. */
const bool shared = c.n_ff_shared > 0 && src.shared;
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */
bool sgate_concurrent = false;
@@ -592,7 +638,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
prot.clear();
{
const int want = c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
: c.expert_g64 ? 5 : c.expert_nl ? 4
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
@@ -665,16 +711,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The router is replicated (see Config::n_expert_all): every rank computes the same routing
* from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks
* without a collective. */
* without a collective. The sigmoid router (GlmRouter) declares its own projection. */
if (!c.sigmoid_router) {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router));
w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16,
{c.n_expert_all, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
}
if (!ext_in)
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
if (c.sigmoid_router) {
if (!src.router_bias) return RAD_E_INVAL;
GlmRouter::Config rc;
rc.experts = c.n_expert_all;
rc.top_k = c.top_k;
rc.rows = c.rows;
rc.norm = c.norm_topk;
rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew };
const GlmRouter::Src rs{ src.router, src.router_bias };
RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
w_router = glm_router.projection;
op_router = glm_router.op_project;
op_topk = glm_router.op_select;
} else {
op_router = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
@@ -686,6 +749,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.logits}, {w.ids, w.ew});
}
/* Protected experts are sorted last (`protect`); layers without them declare no protect
* list, so it is the last parameter and cut off. */
const int n_prot = prot_list ? 1 : 0;
@@ -693,8 +757,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const RadParam ps[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
RAD_INT("top_k", c.top_k), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list) };
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
/* With `w.inv` the sort also writes the gather's slot table. It writes everything
* moe_scatter does, so a moe_gather_inv that does not resolve leaves moe_gather to serve. */
if (w.inv && rad_op_declared(b, "moe_scatter_inv") && rad_op_declared(b, "moe_gather_inv"))
op_scatter = rw(b, rad_decl_op(b, "moe_scatter_inv", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt, w.inv});
scatter_inv = op_scatter != 0;
if (!op_scatter)
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
}
/* topk and scatter in one launch. At decode each is a single 256-thread workgroup ranking
@@ -705,9 +776,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* M*top_k <= 1024 and three above (for a stable sort without atomics), and only the first is
* fusible. That covers decode (eight sequences at depth 3 and top_k 10 is 320); prefill
* chunks exceed it. The pair is declared either way, so the graph and buffer plan do not
* depend on it. */
* depend on it. The sigmoid router selects in its own op and takes no fused pair. */
topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows
: kMoeSortRows / c.top_k;
if (c.sigmoid_router || scatter_inv) topk_scatter_rows = 0;
/* Asked for only where a loaded library declares it: a CPU-only engine would refuse the
* declare, and the two separate ops serve without it. */
if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) {
@@ -752,6 +824,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the parity classes. */
const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0;
ncls = c.ff_hi4[0] > 0 ? 4 : 2;
if (c.expert_mx && ncls == 4) {
fprintf(stderr, "radiance: MXFP4 experts use two parity tables; use equal TP width slices\n");
return RAD_E_UNSUPPORTED;
}
if (ncls == 4 && n_reg < 4) {
fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four "
"classes need at least one each\n", l, (long long)n_reg);
@@ -791,7 +867,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
* relayout sees it. */
auto edt_of = [&](int f) {
return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
};
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
@@ -819,19 +895,23 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : 2;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit. `sdiv` is
* how many weight rows or columns one scale covers along the split dimension. */
const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
* dimension. */
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
* experts' encoding or the kernel is not a candidate. */
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
* forms E4M3 per (row, 64 of K) selected with the fixed second level. With two planes it is a
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. `sgk` is the K one declared scale column covers. */
const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
: c.expert_mx ? (uint32_t)RAD_E8M0
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
* planes the same in their own units. */
@@ -880,7 +960,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
true, false));
true, false, c.swiglu_limit));
op_dn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -914,8 +994,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
c.expert_w4 ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
{(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -941,7 +1021,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, sgk));
@@ -1012,8 +1092,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
false, rot));
false, rot, c.swiglu_limit));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
rad_op h = ncls == 4
@@ -1116,7 +1197,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true,
false));
false, c.swiglu_limit));
op_pdn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wp), RAD_INT("n_expert", np),
@@ -1209,18 +1290,20 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
* separate gather would be two dispatches per layer and a 160 KiB round trip. */
gfold = shared;
{
rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate };
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
rad_buf gwr[1] = { w.h.x };
op_gather = RAD_OP(b, "moe_gather",
op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype),
RAD_STR("act", gfold ? "sigmoid" : "none")),
RAD_STR("act", gfold && !c.shared_ungated ? "sigmoid" : "none")),
RAD_NOWEIGHTS);
if (!op_gather) return RAD_E_INVAL;
if (!op_gather) continue;
gather_inv = !form;
rad_op_reads (b, op_gather, grd, gfold ? 5 : 3);
rad_op_writes(b, op_gather, gwr, 1);
}
if (!op_gather) return RAD_E_INVAL;
/* ---- the shared expert. Ordinary dense linears over the same normed input. */
if (shared) {
@@ -1243,7 +1326,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8));
}
if (!w.sff.q || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1258,8 +1341,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{ c.n_ff_shared, c.n_ff_shared },
c.shared_lo, c.shared_hi));
/* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */
gq_sh.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)));
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
c.swiglu_limit));
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ nm.ckpt("%s.down_proj.weight", src.shared) },
@@ -1267,7 +1352,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
c.shared_lo, c.shared_hi));
/* The shared gate, replicated like the router so every rank computes the same gate. One
* output column: the skinny GEMM kernel clamps its N tile rather than masking, so N = 1 is
* legal. */
* legal. An ungated arm (shared_ungated) fills the gate with 1 instead. */
if (c.shared_ungated) {
op_sgate = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", 1),
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS),
{}, {w.sgate});
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate));
w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -1276,6 +1368,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_sgate)),
{w.h.x}, {w.sgate});
}
}
/* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
@@ -1290,7 +1383,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
*
* The parameter list, weights and write set are conditional, so each is an array cut to
* length. */
if (op_topk_scatter && rad_op_declared(b, "router_gemm_topk_scatter")) {
if (op_topk_scatter && !c.shared_ungated && rad_op_declared(b, "router_gemm_topk_scatter")) {
router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows
: kMoeRouterFusedRows;
const bool gate = op_sgate != 0;
@@ -1319,6 +1412,50 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
router_fused_gate = op_router_fused && gate;
}
/* GLM's selection and the sort as one op, plus the ungated shared arm's gate fill. Declared
* here for the reason the fused router above is: it writes `w.sgate` ahead of `op_sgate`'s
* declared index, which is safe only with `sgate` out of the sharing pool. Its other outputs
* and its input are also declared by the ops it replaces, so their planned lifetimes cover it.
* Undeclared or unresolved, the separate ops serve. */
if (c.sigmoid_router && c.router_fuse) {
if (!rad_op_declared(b, "router_sigmoid_topk_scatter")) {
static bool told = false;
if (!told) rad_note(b, "no loaded library declares router_sigmoid_topk_scatter; the "
"selection and the sort stay separate launches");
told = true;
} else {
sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows
? c.rows : kMoeSortRows / c.top_k;
const bool gate = op_sgate != 0 && c.shared_ungated;
if (gate && !sgate_concurrent) {
fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate "
"ahead of its declared writer, which needs `sgate` out of the "
"sharing pool, and it is not\n", l);
return RAD_E_STATE;
}
const RadParam sp[] = {
RAD_RANGE("M", 1, sigmoid_scatter_rows), RAD_INT("n_expert", c.n_expert_all),
RAD_INT("n_local", c.n_expert), RAD_INT("top_k", c.top_k),
RAD_INT("norm", c.norm_topk), RAD_F64("route_scale", c.route_scale),
RAD_STR("dtype", "f32"), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list),
};
const int n_sp = (int)(sizeof(sp) / sizeof(sp[0])) - (prot_list ? 0 : 1);
op_sigmoid_scatter = rad_decl_op(b, "router_sigmoid_topk_scatter", sp, n_sp,
&glm_router.correction, 1);
if (op_sigmoid_scatter) {
const rad_buf rd[1] = { w.logits };
rad_buf wr[7] = { w.ids, w.ew, w.sorted, w.eoff, w.ecnt };
int n_wr = 5;
if (gate) wr[n_wr++] = w.sgate;
if (scatter_inv) wr[n_wr++] = w.inv;
rad_op_reads (b, op_sigmoid_scatter, rd, 1);
rad_op_writes(b, op_sigmoid_scatter, wr, n_wr);
}
sigmoid_scatter_gate = op_sigmoid_scatter && gate;
}
}
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1347,7 +1484,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
if (!c.sigmoid_router && !c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
@@ -1376,7 +1513,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
bool gate_done) const {
/* `gate_done`: the fused router already wrote this pass's gate. */
if (!gate_done)
if (!gate_done && c.shared_ungated)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
else if (!gate_done)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
brow_slice(w.sgate, r0, rows, 1));
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
@@ -1415,7 +1554,18 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
const bool rfused = op_router_fused && rows <= router_fused_rows;
if (rfused)
const bool sfused = op_sigmoid_scatter && rows <= sigmoid_scatter_rows;
if (sfused) {
glm_router.project(c_, r0, rows, r0);
RAD_ISSUE_N(c_, op_sigmoid_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
RAD_W(glm_router.correction), brow_slice(w.ids, r0, rows, k),
brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k),
brows(w.eoff, ne + 1), ecnt,
sigmoid_scatter_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
scatter_inv ? brows(w.inv, rows * k) : RAD_NONE);
} else if (c.sigmoid_router) {
glm_router.step(c_, r0, rows, r0);
} else if (rfused)
RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE,
brow_slice(w.logits, r0, rows, ne_all),
@@ -1426,17 +1576,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
brow_slice(w.logits, r0, rows, ne_all));
/* topk + scatter fused, or the pair. In the fused op `w.ids` is an output. */
if (rfused) {
if (rfused || sfused) {
/* the fused router wrote all five */
} else if (op_topk_scatter && rows <= topk_scatter_rows) {
RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
} else {
if (!c.sigmoid_router)
RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k));
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
if (scatter_inv)
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt,
brows(w.inv, rows * k));
else
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
}
/* The rotated quantisation of the input, when the experts are rotated and the caller did not
@@ -1476,7 +1632,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
brows(w.egu, rows * k));
if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate);
if (shared) shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
if (c.expert_bf16)
@@ -1562,7 +1719,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* the block's delta into `h.x`. */
if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k),
brows(gather_inv ? w.inv : w.sorted, rows * k),
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
brow_slice(w.h.x, r0, rows, g.n_embd));
@@ -1640,9 +1797,10 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
* It reports the last pass, which is the whole step by default (`c.rows` is the prefill
* chunk). With more passes it is a sample, adequate for a popularity estimate.
*
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16.
* Nothing in the core reads it (the heat engine uses `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew);
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16
* (f32 under the sigmoid router). Nothing in the core reads it (the heat engine uses
* `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
RadRouting r{};
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
r.expert_w = nullptr;
+80 -7
View File
@@ -474,6 +474,15 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
struct GateQuantFP8 {
ActFP8 a{};
rad_op op = 0;
/* The swiglu_clamped path (`limit` > 0): `op` writes the clamped bf16 product and `op_quant`
* quantises it into the codes; with `clamped_fused`, `op` is `swiglu_clamped_quant_fp8` doing
* both and `op_quant` is unset. */
rad_op op_quant = 0;
bool clipped = false;
/* Set before declare: serve the clamped path as one `swiglu_clamped_quant_fp8` where a loaded
* library declares it and it resolves (E4M3 codes only). Byte-identical to the pair. */
bool fuse_clamped = false;
bool clamped_fused = false;
/* Whether the bf16 product is written. A consumer of the bf16 value must request it
* (docs/OPS.md), but a block-fp8 down_proj reads only codes and scales; only one that reads
* the bf16 plane (LinearFP8::reads_x) needs it. Skipping it saves [T, n_ff] per layer (18.2 GB
@@ -491,7 +500,7 @@ struct GateQuantFP8 {
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false);
bool rot = false, double limit = 0);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
@@ -500,13 +509,55 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */
inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
int64_t n, const char* act_name, int64_t max_rows,
bool bf16_out, bool rot) {
bool bf16_out, bool rot, double limit) {
a = act;
want_x = bf16_out;
op_quant = 0;
this->n = n;
/* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no
* rotation. */
bf16 = g.w_bf16;
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
if (clipped) {
if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu")) return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op =
RAD_OP(b, "swiglu_clamped_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS);
if (op) {
const rad_buf wr[3] = { a.cq(), a.cs(), a.x };
rad_op_reads(b, op, &gate_up, 1);
rad_op_writes(b, op, wr, want_x ? 3 : 2);
clamped_fused = true;
return RAD_OK;
}
}
want_x = true;
op = rw(b,
RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!bf16) {
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
op_quant =
rw(b,
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
if (!op_quant) return RAD_E_INVAL;
}
return op?RAD_OK:RAD_E_INVAL;
}
if (bf16) {
if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) {
fprintf(stderr, "radiance: a bf16 gate is silu over [gate|up] into a bf16 plane; "
@@ -555,6 +606,22 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
int64_t rows) const {
if (rows <= 0) rows = T - r0;
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
return;
}
if (clipped) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.x, r0, rows, n));
if (op_quant)
RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
return;
}
if (bf16 || op_q) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n));
if (op_q)
@@ -607,6 +674,9 @@ struct LinearFP8 {
/* Plain bf16 weight read by `gemm_nt` over the bf16 activation (Geom::w_bf16): no scale plane,
* no quantiser. */
bool bf16 = false;
/* Block-fp8 weight whose scale plane is f32 rather than bf16 (GLM's checkpoints), read by
* `gemm_nt_q` at dtype fp8a8f32. Read from the weight's encoding. */
bool f32_scale = false;
/* Int8 weight read by `gemm_nt_q` at dtype i8a8: i8 codes with a bf16 scale per row per 128 of
* K (libquant `codes=i8 group=128 scale=bf16`), against an i8 activation with an f32 scale per
* (row, 128). A quarter of E4M3's error at the same bytes, and iu8 WMMA runs at the fp8 rate.
@@ -1268,12 +1338,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
if (known) {
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc ||
(sc->dtype != RAD_BF16 && sc->dtype != RAD_F32) ||
sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they "
"read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], "
"read bf16, fp8_e4m3*bf16[128x128] or *f32[128x128], i8*bf16[1x128], "
"fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the "
"ParoQuant forms. A recipe rule stores the weight in one of them "
"(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en);
@@ -1299,13 +1370,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks"));
const char* sn = nm.f("%s.scale", base);
const auto* fp8_scale = known ? rad_enc_plane(&enc, "scale") : nullptr;
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
* the checkpoint or made so by rad-convert's recipe. */
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n);
ws_row_div = RAD_FP8_BLOCK;
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
access, shard, grp, rp.s, rp.n);
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
if (!w || !ws) return RAD_E_INVAL;
/* An uneven slice; the scale plane takes the same slice in blocks. */
if (span_hi > 0) {
@@ -1326,7 +1399,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", f32_scale?"fp8a8f32":"fp8a8")),
RAD_WEIGHTS(w, ws)),
{ a.q, a.s }, { y });
return RAD_OK;
+72
View File
@@ -0,0 +1,72 @@
/* 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"
#include <cstdlib>
namespace rad {
namespace arch {
/* Rows from which a replicated F32 projection splits its columns over the ranks
* (RADIANCE_GLM_TP_SPLIT_ROWS, 0 never). Below it the collective's latency outweighs the
* saved arithmetic, so decode keeps the replicated form. */
inline int64_t glm_tp_split_rows() {
const char* e = std::getenv("RADIANCE_GLM_TP_SPLIT_ROWS");
if (!e || !*e) return 256;
const long long v = std::strtoll(e, nullptr, 10);
return v > 0 ? (int64_t)v : 0;
}
/* 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 = glm_tp_split_rows();
if (g.world < 2 || !min_rows || 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
+16
View File
@@ -300,4 +300,20 @@ TEST(a_unit_inner_dimension_is_sharded_as_the_matrix_it_leaves) {
CHECK_EQ(weight_share(w, e, 3, stack, 2, 0, s, &why), RAD_E_SHAPE);
}
TEST(glm_kda_tp4_takes_each_head_shard_from_all_three_convolution_parts) {
const auto e = rad_enc_plain(RAD_BF16);
const auto w = decl(e, { 0 }, 3 * 8192, 4, RAD_SHARD_ROW, 4, { 2048, 2048, 2048 });
const int64_t shape[] = { 3 * 8192, 1, 4 };
for (int rank = 0; rank < 4; ++rank) {
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(weight_share(w, e, 3, shape, 4, rank, s, nullptr), RAD_OK);
REQUIRE_EQ(s[0].rects.size(), (size_t)3);
for (int part = 0; part < 3; ++part) {
CHECK_EQ(s[0].rects[part].row0, (int64_t)(part * 8192 + rank * 2048));
CHECK_EQ(s[0].rects[part].rows, (int64_t)2048);
CHECK_EQ(s[0].rects[part].bytes, (int64_t)8);
}
}
}
RAD_TEST_MAIN()