diff --git a/arch/unlimitedocr_bf16/CMakeLists.txt b/arch/unlimitedocr_bf16/CMakeLists.txt new file mode 100644 index 00000000..b413ff05 --- /dev/null +++ b/arch/unlimitedocr_bf16/CMakeLists.txt @@ -0,0 +1,12 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/unlimitedocr_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the +# same rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(unlimitedocr_bf16 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(unlimitedocr_bf16 architectures + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/unlimitedocr_bf16.cpp) diff --git a/arch/unlimitedocr_bf16/attn_llama.h b/arch/unlimitedocr_bf16/attn_llama.h new file mode 100644 index 00000000..1d00573a --- /dev/null +++ b/arch/unlimitedocr_bf16/attn_llama.h @@ -0,0 +1,220 @@ +/* attn_llama.h -- one plain multi-head attention block, bf16 operands, paged KV. PRIVATE to + * arch/unlimitedocr_bf16 (the arch/qwen35_bf16 + siglip2.h precedent: a header beside the plugin + * that composes it). + * + * rmsnorm -> q gemm, k gemm, v gemm -> rope(q), rope(k) + * -> kv_store -> paged attention (causal) -> o gemm -> [all_reduce] -> residual add + * + * It is rad_block_attn_gated.h with the Qwen3.5-specific parts removed, and the removals are the + * model: Unlimited-OCR's decoder is a plain Llama-MoE (modeling_deepseekv2.py's + * SlidingWindowLlamaAttention is MHA with `use_mla: false`), so + * + * * there is NO output gate: `q_proj` is [n_embd, n_head*head_dim] and holds only the query, so + * no de-interleaving, no `sigmoid`, no `mul`; + * * there is NO per-head q/k norm: the config's `qk_nope_head_dim`/`qk_rope_head_dim` are 0 and + * the reference rotates the projections straight; + * * the rotary is FULL head_dim (rot = head_dim = 128) and NeoX-half (`rotate_half` in the + * reference), not partial, not mrope; + * * q, k and v are three [1280, 1280] projections kept as three GEMMs and three contiguous + * operands, exactly as rad_block_attn_gated.h argues: a fused [k|v] row is not expressible as + * an operand a head-wise reader can walk. + * + * Everything the gated block gets right about paged KV is copied through unchanged: the attention + * declared BEFORE the store so block_size derives from the resolved kernel, the ranged `q_len` + * band, the ragged-step cu_seqlens, the collective emitted by the plugin and not the core. + */ +#ifndef UNLIMITEDOCR_ATTN_LLAMA_H +#define UNLIMITEDOCR_ATTN_LLAMA_H + +#include + +namespace rad { +namespace arch { + +struct AttnLlamaBF16 { + struct Wire { + rad_buf x = 0; /* [max_tok, n_embd] the residual stream */ + rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */ + rad_buf q = 0; /* [max_tok, q_dim] rotated */ + rad_buf k = 0; /* [max_tok, kv_dim] rotated */ + rad_buf v = 0; /* [max_tok, kv_dim] */ + rad_buf attn = 0; /* [max_tok, q_dim] */ + }; + + struct Src { + const char* norm = nullptr; /* input_layernorm.weight */ + const char* q = nullptr; + const char* k = nullptr; + const char* v = nullptr; + const char* o = nullptr; + }; + + Geom g{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + int64_t n_rot = 0; + + rad_weight w_norm = 0, w_q = 0, w_k = 0, w_v = 0, w_o = 0; + rad_op op_norm = 0, op_q = 0, op_k = 0, op_v = 0; + rad_op op_rope_q = 0, op_rope_k = 0; + rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + int64_t rotary_dim, const Wire& wire, const Src& src); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, + rad_kvgroup group, int64_t rotary_dim, const Wire& wire, + const Src& src) { + g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim; + + const int64_t q_dim = g.q_dim(); + const int64_t kv_dim = g.kv_dim(); + + if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) { + fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n", + (long long)n_rot, (long long)g.head_dim); + return RAD_E_INVAL; + } + /* The KV-head-replication refusal rad_block_attn_gated.h states: this block declares its k/v + * with the plain even row-shard and passes no row span, so a world above the KV head count + * would hand a rank half of one KV head. Say so at declare. */ + if (g.world > g.n_head_kv_all) { + fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d " + "with n_head_kv = %lld.\n", __func__, g.world, + (long long)g.n_head_kv_all); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), src.q)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), src.v)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o)); + + w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l)); + + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + op_q = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_q)), + {w.h}, {w.q}); + op_k = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_k)), + {w.h}, {w.k}); + op_v = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_v)), + {w.h}, {w.v}); + + /* Full-head rotary, NeoX halves: the reference's rotate_half. The q call names n_head query + * heads and no kv heads (the buffers are separate); the k call names the kv heads. */ + op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"), + {w.q}, {w.q}); + op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"), + {w.k}, {w.k}); + + /* Declared before kv_store so block_size derives from the resolved attention kernel (spec + * §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. P1 serves the plain + * causal rule; the R-SWA window is P4 and re-declares this op with its own rule. */ + op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", 0), + RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), + RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + + op_kv_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + + op_o = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd), + RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_o)), + {w.attn}, {w.h}); + + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + + return RAD_OK; +} + +inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const { + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + + const int64_t T = batch->n_tok; + + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + RAD_ISSUE(c, op_q, brows(w.h, T), RAD_W(w_q), brows(w.q, T)); + RAD_ISSUE(c, op_k, brows(w.h, T), RAD_W(w_k), brows(w.k, T)); + RAD_ISSUE(c, op_v, brows(w.h, T), RAD_W(w_v), brows(w.v, T)); + + RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T)); + + RAD_ISSUE(c, op_kv_store, + brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, layer), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn, T)); + + RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T)); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* UNLIMITEDOCR_ATTN_LLAMA_H */ diff --git a/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp new file mode 100644 index 00000000..459e8ff1 --- /dev/null +++ b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp @@ -0,0 +1,489 @@ +/* unlimitedocr_bf16 -- baidu/Unlimited-OCR's decoder: a small Llama-MoE, bf16 weights and bf16 + * activations. + * + * P1 scope (aijuus/plans/UNLIMITED-OCR-PLUGIN.md): the TEXT-ONLY trunk. The DeepEncoder vision + * tower (SAM ViT-B/16 + CLIP ViT-L/14, `model.vision_tower`/`model.projector`) is P2 and not + * declared here; the R-SWA ring KV is P4 and every layer serves plain causal paged attention; the + * windowed no-repeat-ngram sampler is P5. + * + * ============================== THE SHAPE (config.json) ============================== + * + * 12 layers, hidden 1280, 10 heads x 128 head_dim, 10 kv-heads (MHA, `use_mla: false` -- the + * DeepseekV2 class names in the repo are packaging, the graph is Llama) + * full rotary over head_dim, theta 10000, plain RMSNorm eps 1e-6 (NOT 1 + w) + * vocab 129280, lm_head TIED to embed_tokens (the checkpoint ships both tensors) + * layer 0 dense (first_k_dense_replace 1, inter 6848); layers 1..11 MoE: + * 64 routed experts (moe_intermediate_size 896), top-6, scoring softmax, + * norm_topk_prob False, routed_scaling_factor 1.0 -- an ordinary softmax gate, + * 2 shared experts packed as ONE dense MLP 2x896 = 1792 wide, summed ungated + * + * The MoE block is arch/common/rad_block_moe_fp8.h in its plain-bf16 expert mode (probe() reads + * format 3 off the first expert's encoding), declared EXTERNAL-INPUT (src.norm null): its + * post-attention norm is declared by this plugin because the shared expert reads the SAME normed + * input and the block's gather overwrites that input with the routed delta (`h.x` is the + * fold target). The shared arm therefore lives here: gate|up -> silu_mul -> down -> add, beside + * the routed arm, exactly `y = y + shared_experts(x)` in modeling_deepseekv2.py:627. + * + * The attention is this plugin's private attn_llama.h: the gated bf16 block minus the output gate + * and the q/k head norms, which this model does not have. + */ +#include +#include +#include + +#include "attn_llama.h" + +#include + +namespace unlimitedocr_bf16 { + +using namespace rad::arch; + +struct Layer { + int dense = 0; /* 1 = the first_k_dense layer, plain SwiGLU */ + AttnLlamaBF16 attn; + MlpBF16 mlp; /* dense layers */ + MoeFP8 moe; /* routed layers */ + /* The routed layer's external norm and the plugin-owned shared arm: the gain, the two dense + * linears' weights, and the ops. Per layer -- the ACTIVATION buffers are shared across the + * layers (spec §8) and the ops are declared per layer, as every block here does. */ + rad_weight w_norm = 0, w_sh_gate_up = 0, w_sh_down = 0; + rad_op op_moe_norm = 0; /* x -> h.x, the MoE block's external prepared input */ + rad_op op_sh_gu = 0, op_sh_act = 0, op_sh_down = 0, op_sh_ar = 0, op_sh_add = 0; +}; + +struct Model { + Names nm{""}; + Geom g{}; + int64_t n_rot = 0; + int64_t first_dense = 1; /* layers [0, first_dense) are dense MLPs */ + + rad_kvgroup kv_full = 0; + + /* the residual stream and the vocabulary edges */ + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + /* attention */ + rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0; + /* dense feed-forward (layer 0) */ + rad_buf b_gate_up = 0, b_ffn = 0; + /* routing -- one row per token */ + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_eoff = 0, b_ecnt = 0; + /* expert planes -- one row per (token, slot), a pass tall */ + rad_buf b_sorted = 0, b_egu = 0, b_edn = 0; + ActFP8 a_eff{}; + /* the shared arm reads the block's prepared input (h) before the gather overwrites it, then + * the dense linear's planes */ + rad_buf b_sgu = 0, b_sff = 0, b_sout = 0; + + MoeFP8::Config moecfg{}; + + rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0; + + std::vector layers; +}; + +static Model g_model[MAX_RANKS]; + +/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode, + * and the shared expert must read the same normed row the routed experts do; the block's gather + * folds the routed delta into h.x, so the shared arm is issued while h.x still holds the normed + * row, BEFORE the block. */ +static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) { + Geom& g = m.g; + Names& nm = m.nm; + Layer& lay = m.layers[(size_t)l]; + + const char* wname = nm.f("blk.%d.ffn_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, wname, nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", + (long long)l))); + lay.w_norm = decl_w(b, wname, RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + const int64_t n_ff_sh = m.moecfg.n_ff_shared; + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), + { nm.ckpt("model.layers.%lld.mlp.shared_experts.gate_proj.weight", + (long long)l), + nm.ckpt("model.layers.%lld.mlp.shared_experts.up_proj.weight", + (long long)l) }, 0)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down_shexp.weight", l), + nm.ckpt("model.layers.%lld.mlp.shared_experts.down_proj.weight", + (long long)l))); + lay.w_sh_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), RAD_BF16, + {2 * n_ff_sh, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0, + {n_ff_sh, n_ff_sh}); + lay.w_sh_down = decl_w(b, nm.f("blk.%d.ffn_down_shexp.weight", l), RAD_BF16, + {g.n_embd, n_ff_sh}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l)); + + /* The routed arm's own norm: x -> h.x, the buffer the block takes as its prepared input and + * the buffer its gather writes the routed delta back into. */ + lay.op_moe_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_norm)), + {m.b_x}, {m.b_h}); + + lay.op_sh_gu = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * n_ff_sh), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_sh_gate_up)), + {m.b_h}, {m.b_sgu}); + lay.op_sh_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n_ff_sh), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_sgu}, {m.b_sff}); + lay.op_sh_down = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd), + RAD_INT("K", n_ff_sh), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_sh_down)), + {m.b_sff}, {m.b_sout}); + /* Column-sharded like the dense MLP's down_proj: every rank holds a partial sum, reduced + * once per step before the residual add. */ + if (g.world > 1) + lay.op_sh_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {m.b_sout}, {m.b_sout}); + lay.op_sh_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x, m.b_sout}, {m.b_x}); + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + Geom& g = m.g; + Names& nm = m.nm; + + /* Plain RMSNorm (DeepseekV2RMSNorm is x_hat * w), not the GemmaRMSNorm `1 + w`. */ + g.wadd = 0.0f; + /* The linears are the checkpoint's own bf16: no scale planes, no quantised activations. The + * MoeFP8 block in particular requires it (its external-input check reads it). */ + g.w_bf16 = true; + + /* ---- geometry RadModelMeta does not name. */ + const int64_t n_expert_all = meta->n_expert > 0 + ? meta->n_expert : rad_meta_geti(meta, "n_routed_experts", 0); + const int64_t top_k = meta->n_expert_used > 0 + ? meta->n_expert_used : rad_meta_geti(meta, "num_experts_per_tok", 0); + const int64_t moe_ff = rad_meta_geti(meta, "moe_intermediate_size", 0); + const int64_t n_shared = rad_meta_geti(meta, "n_shared_experts", 0); + m.first_dense = rad_meta_geti(meta, "first_k_dense_replace", 1); + if (n_expert_all <= 0 || top_k <= 0 || top_k > n_expert_all || moe_ff <= 0 || + m.first_dense < 0 || m.first_dense >= g.n_layer) { + fprintf(stderr, "radiance: unlimitedocr: the container does not describe the routed " + "decoder (n_routed_experts %lld, num_experts_per_tok %lld, " + "moe_intermediate_size %lld, first_k_dense_replace %lld of %lld layers)\n", + (long long)n_expert_all, (long long)top_k, (long long)moe_ff, + (long long)m.first_dense, (long long)g.n_layer); + return RAD_E_INVAL; + } + /* The gate is an ordinary softmax top-k. A container that states a scheme this plugin does not + * serve is refused by name rather than served as a softmax gate (spec §17). */ + if (const char* sf = rad_meta_gets(meta, "scoring_func", nullptr); sf && *sf && + std::strcmp(sf, "softmax") != 0) { + fprintf(stderr, "radiance: unlimitedocr: scoring_func '%s' is not implemented; the gate " + "this plugin declares is the softmax top-k\n", sf); + return RAD_E_UNSUPPORTED; + } + const double rsf = rad_meta_getf(meta, "routed_scaling_factor", 1.0); + if (!(rsf > 0.0) || rsf != 1.0) { + fprintf(stderr, "radiance: unlimitedocr: routed_scaling_factor %g is not 1.0 and this " + "plugin declares no router output scale\n", rsf); + return RAD_E_UNSUPPORTED; + } + const int64_t topk_group = rad_meta_geti(meta, "topk_group", 1); + const int64_t n_group = rad_meta_geti(meta, "n_group", 1); + if (topk_group != 1 || n_group != 1) { + fprintf(stderr, "radiance: unlimitedocr: grouped routing (n_group %lld, topk_group %lld) " + "is not implemented; the reference's greedy top-k over one group is\n", + (long long)n_group, (long long)topk_group); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "use_mla", 0)) { + fprintf(stderr, "radiance: unlimitedocr: use_mla is set; this decoder is the MHA graph " + "(q/k/v projections), not the DeepSeek MLA\n"); + return RAD_E_UNSUPPORTED; + } + /* The full-head rotary: no rope_parameters object is present, so yarn_from answers + * "default" and theta stays the container's (the reference default 10000). */ + m.n_rot = g.head_dim; + RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot)); + + /* ---- the routed geometry. n_expert is NOT divided (every rank holds every expert and routes + * identically); the intermediate width is. */ + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = n_expert_all; + mc.n_expert_all = n_expert_all; + mc.top_k = top_k; + int s; + if ((s = divide_or_fail(moe_ff, g.world, "moe_intermediate_size", &mc.n_ff_exp)) < 0) + return s; + /* The shared experts are packed as ONE dense MLP n_shared x moe_ff wide (DeepseekV2Model: + * `intermediate_size = moe_intermediate_size * n_shared_experts`), summed ungated. The + * MoeFP8 shared arm is the SIGMOID-gated family's shape; this model's arm is declared by the + * plugin (declare_moe_norm_and_shared) and the block declares none. */ + const int64_t sh_all = n_shared * moe_ff; + mc.n_ff_shared = 0; + int64_t n_ff_sh = 0; + if (sh_all > 0 && (s = divide_or_fail(sh_all, g.world, "n_shared_experts width", + &n_ff_sh)) < 0) + return s; + mc.norm_topk = rad_meta_geti(meta, "norm_topk_prob", 0) ? 1 : 0; + const int64_t moe_rows = 2048; + mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; + + /* ---- KV: one full group. R-SWA (P4) turns this into a windowed group with the window set at + * prefill end; P1 is the plain full-cache decode the plan uses as the P1-P3 baseline. */ + RadKVGroupDecl fd{}; + fd.kind = RAD_KV_FULL; + fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.n_head_kv = g.n_head_kv; + fd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + g.kv_dtype = rad_dtype_name(fd.dtype); + + /* ---- activation buffers. */ + m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, g.kv_dim()}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, g.kv_dim()}); + m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()}); + + m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); + m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); + + const int64_t R = g.max_tok, K = mc.rows * mc.top_k; + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert_all}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k}); + m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k}); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K}); + m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert_all + 1}); + /* PERSIST: its only reader, rad_route_report, is not a declared op. See qwen4exp_fp8. */ + m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST); + m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp}); + m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd}); + + if (n_ff_sh > 0) { + mc.n_ff_shared = n_ff_sh; /* sizes nothing in the block (arm null there); kept for + the shared-arm ops below */ + m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * n_ff_sh}); + m.b_sff = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, n_ff_sh}); + m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); + } + + m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- vocabulary edges. The lm_head is TIED: the checkpoint ships lm_head.weight, and a + * release that ships only the embedding is served by the same map (first source present + * wins). Both edges are row-sharded with the vocabulary (spec §9). */ + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), + nm.ckpt("model.embed_tokens.weight"))); + + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_lm_head = decl_w(b, nm.f("output.weight"), + weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16), + {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + if (g.world > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- the expert FORMAT: the checkpoint's plain bf16, read off the first routed layer's + * first expert. A quantised container is a sibling plugin's (the recipe registry's w4/mxfp4 + * tiers are the plan's post-P5 follow-up). */ + { + MoeFP8::Src probe_src{}; + probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", + (long long)m.first_dense); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)m.first_dense, probe_src, &mc)); + if (!mc.expert_bf16) { + fprintf(stderr, "radiance: unlimitedocr_bf16 serves plain bf16 experts; layer %lld's " + "expert 0 is quantised. Serve that container with its quantised " + "plugin.\n", (long long)m.first_dense); + return RAD_E_UNSUPPORTED; + } + } + + AttnLlamaBF16::Wire aw{}; + aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn; + + MlpBF16::Wire mw{}; + mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn; + + MoeFP8::Wire fw{}; + fw.x = m.b_x; + fw.h.x = m.b_h; /* external input: the plugin's own rmsnorm writes it */ + fw.logits = m.b_rlogits; fw.ids = m.b_eids; fw.ew = m.b_ew; + fw.eoff = m.b_eoff; fw.ecnt = m.b_ecnt; + fw.sorted = m.b_sorted; fw.egu = m.b_egu; + fw.eff.x = m.a_eff.x; + fw.edn = m.b_edn; /* moe, sgu, sff, sout, sgate stay null: no block arm */ + + m.layers.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.dense = (l < m.first_dense) ? 1 : 0; + + AttnLlamaBF16::Src as{}; + as.norm = nm.ckpt("model.layers.%lld.input_layernorm.weight", (long long)l); + as.q = nm.ckpt("model.layers.%lld.self_attn.q_proj.weight", (long long)l); + as.k = nm.ckpt("model.layers.%lld.self_attn.k_proj.weight", (long long)l); + as.v = nm.ckpt("model.layers.%lld.self_attn.v_proj.weight", (long long)l); + as.o = nm.ckpt("model.layers.%lld.self_attn.o_proj.weight", (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as)); + + if (lay.dense) { + MlpBF16::Src ms{}; + ms.norm = nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", (long long)l); + ms.gate = nm.ckpt("model.layers.%lld.mlp.gate_proj.weight", (long long)l); + ms.up = nm.ckpt("model.layers.%lld.mlp.up_proj.weight", (long long)l); + ms.down = nm.ckpt("model.layers.%lld.mlp.down_proj.weight", (long long)l); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms)); + } else { + /* The block's norm, the shared arm and its linears, then the block. The block's norm + * is declared by the plugin (external input) because its gather folds the routed + * delta into h.x, and the shared arm reads its own copy of the normed row. */ + RAD_ARCH_TRY(declare_moe_norm_and_shared(b, m, (int)l)); + + MoeFP8::Src fs{}; + fs.cfg = mc; + fs.norm = nullptr; /* external: declared above */ + fs.router = nm.ckpt("model.layers.%lld.mlp.gate.weight", (long long)l); + fs.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l); + fs.shared = nullptr; /* the ungated shared arm lives in the plugin */ + RAD_ARCH_TRY(lay.moe.declare(b, nm, g, (int)l, fw, fs)); + } + } + + m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out_norm)), + {m.b_x}, {m.b_h}); + + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + + m.op_logits = 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", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_lm_head)), + {m.b_hout}, {m.b_logits}); + + rad_note(b, "rank %d/%d: %lld layers, layer 0 dense (n_ff %lld), layers %lld..%lld MoE: " + "%lld experts top-%lld (softmax, norm_topk %d), shared arm %lld wide, " + "n_head=%lld n_head_kv=%lld head_dim=%lld vocab=[%lld,%lld) tied head", + g.rank, g.world, (long long)g.n_layer, (long long)g.n_ff, + (long long)m.first_dense, (long long)(g.n_layer - 1), + (long long)mc.n_expert_all, (long long)mc.top_k, mc.norm_topk, + (long long)mc.n_ff_shared, + (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim, + (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + rad_note(b, "R-SWA is NOT served by this plugin pass: every layer decodes full-cache causal. " + "The ring (sliding_window_size %lld) is the plan's P4 (per-sequence RAD_KV_WINDOW " + "window set at prefill end, causal=0 over reference+ring)", + (long long)rad_meta_geti(meta, "sliding_window_size", 0)); + rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=35 -- the " + "plan's P5 sample_ngram_ban op; temp-0 parity checks run with it off"); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_rank(c)]; + + /* No encoder pass is declared (the vision tower is P2). */ + if (batch->enc) return; + + RAD_ISSUE(c, m.op_embed, + praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok), + brows(m.b_x, batch->n_tok)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd, + brows(m.b_x, batch->n_tok), RAD_NONE); + + for (const Layer& l : m.layers) { + l.attn.step(c, batch); + if (l.dense) { + l.mlp.step(c, batch); + } else { + const int64_t T = batch->n_tok; + /* The MoE block's norm (x -> h.x), then the shared arm beside the routed arm: both + * read the same prepared input, so the shared arm is issued while h.x still holds the + * normed row and BEFORE the block's gather overwrites it with the routed delta. The + * two residual adds commute: x += shared, then the block's x += routed. */ + RAD_ISSUE(c, l.op_moe_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_sh_gu, brows(m.b_h, T), RAD_W(l.w_sh_gate_up), + brows(m.b_sgu, T)); + RAD_ISSUE(c, l.op_sh_act, brows(m.b_sgu, T), brows(m.b_sff, T)); + RAD_ISSUE(c, l.op_sh_down, brows(m.b_sff, T), RAD_W(l.w_sh_down), + brows(m.b_sout, T)); + if (l.op_sh_ar) + RAD_ISSUE_N(c, l.op_sh_ar, T * m.g.n_embd, brows(m.b_sout, T), RAD_NONE); + RAD_ISSUE(c, l.op_sh_add, brows(m.b_x, T), brows(m.b_sout, T), brows(m.b_x, T)); + l.moe.step(c, batch); + } + } + + RAD_ISSUE(c, m.op_final_norm, + brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok)); + + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, + brows(m.b_h, batch->n_tok), + praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, + brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head), + brows(m.b_logits, batch->n_out)); + } +} + +} /* namespace unlimitedocr_bf16 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0", + "baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), " + "bf16 weights and activations, full rotary MHA; text-only until the P2 vision " + "tower lands") +#endif diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 800c549d..0790347d 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -247,6 +247,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0)); m.n_vocab = gi("vocab_size", 0); m.n_ctx_train = gi("max_position_embeddings", 0); + /* THE DEEPSEEK SPELLING. Unlimited-OCR's decoder is a DeepSeek-V2 MoE and states its expert + * count as `n_routed_experts`; a routed config names the count under one of the three and + * never under more than one, so the chain is a rename, not a guess. */ m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0))); m.n_expert_used = gi("num_experts_per_tok", 0); m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts", diff --git a/data/recipes/unlimited-ocr-bf16.recipe b/data/recipes/unlimited-ocr-bf16.recipe new file mode 100644 index 00000000..79ceec7a --- /dev/null +++ b/data/recipes/unlimited-ocr-bf16.recipe @@ -0,0 +1,17 @@ +# unlimited-ocr-bf16.recipe -- baidu/Unlimited-OCR from its bf16 checkpoint, served at the +# checkpoint's own precision. +# +# rad-convert --recipe data/recipes/unlimited-ocr-bf16.recipe \ +# -o unlimited-ocr-bf16.rad +# +# No rules: every decoder weight is plain bf16 as the checkpoint ships it, and the bf16 plugin +# (arch/unlimitedocr_bf16) probes the first routed expert, reads the plain encoding and serves the +# experts through the bf16 grouped GEMM. The checkpoint carries no quantization_config. +# +# The container this writes is the P0/P1 decoder only: the plugin's name map covers the 12-layer +# Llama-MoE trunk and its tied head, and the DeepEncoder vision tensors are left out until the P2 +# tower is declared (aijuus/plans/UNLIMITED-OCR-PLUGIN.md). Reconvert with the same recipe then. +# +# Quantisation follow-ups (after P5) get their own recipes: the 64-expert MoE is the qwen4exp +# w4/w4nl64 tier's shape (moe_intermediate_size 896 = 7 x 128 scale groups, n_embd 1280 = 10 x 128 +# -- whole scale blocks both ways), with the tied 331 MB head and the vision tower kept bf16. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 67460da9..3db092d4 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -557,6 +557,18 @@ std::vector build_cases() { HS("dtype", dt) }); add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 0), HS("dtype", dt) }); + /* The pair and the pair behind the router GEMM: the whole-model form and a rank's slice + * with a nonzero expert base, since the sort's slicing is the part the fuse adds. */ + add("router_topk_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), + HI("norm", 1), HS("dtype", dt) }); + add("router_topk_scatter", { HI("M", 9), HI("n_expert", 8), HI("n_local", 4), + HI("top_k", 2), HI("norm", 0), HI("expert_base", 2), + HS("dtype", dt) }); + add("router_gemm_topk_scatter", { HI("M", 9), HI("K", 128), HI("n_expert", 8), + HI("top_k", 2), HI("norm", 0), HS("dtype", dt) }); + add("router_gemm_topk_scatter", { HI("M", 9), HI("K", 128), HI("n_expert", 8), + HI("n_local", 4), HI("top_k", 2), HI("norm", 1), + HI("expert_base", 2), HS("dtype", dt) }); add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt) }); /* The shared-expert fold: `shared`/`shared_gate` are always described, so always * present; this case uses sigmoid, the one above "none". */ diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index e5b14941..fca40a77 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -106,7 +106,8 @@ int avx_par_force(int threads); /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ - X(moe_gemm_q_mod4) X(pair_argmax) \ + X(moe_gemm_q_mod4) X(pair_argmax) \ + X(router_topk_scatter) X(router_gemm_topk_scatter) \ /* ---- gated delta net */ \ X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \ X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \ diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index fea717a5..31a5a395 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -1218,10 +1218,14 @@ AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); } /* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in * ascending slot j (see the file header). The inverse permutation is built once per batch. */ AVX_KERNEL(moe_gather) { + /* NOT `rad_args_have(a, 6)`: the required operands are not a prefix -- the shared pair at 3 + * and 4 is a NULL SLOTS form for a layer whose shared arm runs beside the block, and the + * prefix test reads a legal unfolded call as a missing operand. */ if (!a || !a->t || a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL; const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5]; /* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both * operands or neither, as in libref. */ + if (!ye->data || !ew->data || !sorted->data || !Y->data) return RAD_E_INVAL; const RadTensor *sh = rad_arg_in(a, 3), *sg = rad_arg_in(a, 4); if ((sh != nullptr) != (sg != nullptr)) return RAD_E_INVAL; const char* act = p_str(a, "act", "none"); @@ -1492,3 +1496,76 @@ AVX_KERNEL(pair_argmax) { } return RAD_OK; } + +/* ------------------------------------------------------------------ router_topk_scatter */ +/* THE PAIR AS ONE OP: `router_topk` then `moe_scatter` over the ids it just wrote. The selection + * reads the whole router's `n_expert` logits; the sort runs over THIS RANK'S SLICE, which is the + * fused op's `n_local` standing where `moe_scatter`'s `n_expert` names the slice it owns. + * + * The operands line up with `router_topk`'s own first three slots (logits, ids, weights), so the + * selection is the sibling kernel called on this very RadArgs -- no copy, no re-derivation of the + * softmax -- and the sort is `moe_scatter` over the four operands it takes. */ +AVX_KERNEL(router_topk_scatter) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const int64_t ne = p_int(a, "n_expert", 0); + const int64_t nl = p_int(a, "n_local", ne); + const int64_t k = p_int(a, "top_k", 1); + if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_SHAPE; + + const int rc = AVX_FN(avx_router_topk)(a, stream); + if (rc != RAD_OK) return rc; + + const RadTensor t2[] = { a->t[1], a->t[3], a->t[4], a->t[5] }; + const RadParam sp[] = { RAD_INT("n_expert", nl), RAD_INT("top_k", k), + RAD_INT("expert_base", p_int(a, "expert_base", 0)), + RAD_STR("protect", p_str(a, "protect", nullptr)) }; + const RadArgs sa{ t2, 4, sp, 4, a->scratch, a->scratch_bytes, a->instance, a->rank, + a->world_size }; + return AVX_FN(avx_moe_scatter)(&sa, stream); +} + +/* ------------------------------------------------------------------ router_gemm_topk_scatter */ +/* THE ROUTER GEMM IN FRONT OF THE PAIR, and with `gate_b`/`gate` present the shared expert's + * one-column gate over the same input, at N = 1. `gate_b` and `gate` come together or not at all, + * and the operand count says which. */ +extern "C" int AVX_FN(avx_gemm_nt)(const RadArgs*, RadStream); + +AVX_KERNEL(router_gemm_topk_scatter) { + /* NOT `rad_args_have`: the required operands are not a prefix -- `gate_b` sits between the + * router's weight and the outputs, and it and `gate` are null slots in the gate-absent form. */ + if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL; + const bool gate_b = a->t[2].data != nullptr; + const bool gate = a->n_t > 9 && a->t[9].data != nullptr; + if (gate_b != gate) return RAD_E_INVAL; + for (int i : {0, 1, 3, 4, 5, 6, 7, 8}) + if (!a->t[i].data) return RAD_E_INVAL; + const int64_t ne = p_int(a, "n_expert", 0); + const int64_t nl = p_int(a, "n_local", ne); + const int64_t k = p_int(a, "top_k", 1); + const int64_t K = p_int(a, "K", 0); + if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne || K <= 0) return RAD_E_SHAPE; + const char* dt = p_str(a, "dtype", "bf16"); + + const RadTensor g3[] = { a->t[0], a->t[1], a->t[3] }; + const RadParam gp[] = { RAD_INT("N", ne), RAD_INT("K", K), RAD_STR("dtype", dt) }; + const RadArgs ga{ g3, 3, gp, 3, a->scratch, a->scratch_bytes, a->instance, a->rank, + a->world_size }; + const int gc = AVX_FN(avx_gemm_nt)(&ga, stream); + if (gc != RAD_OK) return gc; + + if (gate) { + const RadTensor p3[] = { a->t[0], a->t[2], a->t[9] }; + const RadParam pp[] = { RAD_INT("N", 1), RAD_INT("K", K), RAD_STR("dtype", dt) }; + const RadArgs pa{ p3, 3, pp, 3, a->scratch, a->scratch_bytes, a->instance, a->rank, + a->world_size }; + const int pc = AVX_FN(avx_gemm_nt)(&pa, stream); + if (pc != RAD_OK) return pc; + } + + /* The pair over the logits the GEMM just wrote. Every parameter the pair reads is a parameter + * of this op, under the same name -- the fused lists are unions. */ + const RadTensor t6[] = { a->t[3], a->t[4], a->t[5], a->t[6], a->t[7], a->t[8] }; + const RadArgs fa{ t6, 6, a->p, a->n_p, a->scratch, a->scratch_bytes, a->instance, a->rank, + a->world_size }; + return AVX_FN(avx_router_topk_scatter)(&fa, stream); +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 602ac0c6..d5de6ff6 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -387,6 +387,26 @@ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT( static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count") }; +/* THE PAIR AS ONE OP, and the router GEMM in front of it: libref's schemas for the same two rows, + * where the operand lists are unions and `expert_ids`/`logits` are named once as outputs. */ +static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"), + P_INTO("n_local"), P_INT("top_k"), + P_INT("norm"), P_STR("dtype"), + P_INTO("expert_base"), + P_STRO("protect") }; +static const RadOperandSpec oRouterTopkScatter[] = { OPD("logits"), OUT("expert_ids"), + OUT("expert_w"), OUT("sorted_tok"), + OUT("expert_offset"), + OUT("expert_count") }; +static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"), + P_INT("n_expert"), P_INTO("n_local"), + P_INT("top_k"), P_INT("norm"), + P_STR("dtype"), P_INTO("expert_base"), + P_STRO("protect") }; +static const RadOperandSpec oRouterGemmTopkScatter[] = { + OPD("a"), WGT("b"), WGT_O("gate_b"), OUT("logits"), OUT("expert_ids"), OUT("expert_w"), + OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count"), OUT_O("gate") }; + static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"), P_INT("top_k"), P_STR("a_order"), P_STR("dtype") }; static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"), @@ -979,6 +999,10 @@ static const RadOpSchema kSchemas[] = { { "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid), "Single-group sigmoid routing; correction bias selects experts, original scores weight them." }, { "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." }, +{ "router_topk_scatter", ARR(pRouterTopkScatter), ARR(oRouterTopkScatter), + "the selection and the sort in one op, run as exactly the pair." }, +{ "router_gemm_topk_scatter", ARR(pRouterGemmTopkScatter), ARR(oRouterGemmTopkScatter), + "the router GEMM, the shared expert's gate GEMM and the pair, run as exactly the launches." }, { "moe_scatter", ARR(pScatter), ARR(oScatter), "stable counting sort of routing slots by expert." }, { "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm), "grouped GEMM over the expert-sorted rows." }, @@ -1514,6 +1538,12 @@ SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routin L(router_topk)), SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT, L(router_sigmoid_topk)), +SIMPLE("avx_router_topk_scatter", "router_topk_scatter", "moe", + "the selection and the sort in one op, run as exactly the pair", DT_FLOAT, + L(router_topk_scatter)), +SIMPLE("avx_router_gemm_topk_scatter", "router_gemm_topk_scatter", "moe", + "the router GEMM, the shared expert's gate GEMM and the pair, run as exactly the launches", + DT_FLOAT, L(router_gemm_topk_scatter)), SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert", "i32 indices", L(moe_scatter)), SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT, diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index e8ccd9ad..57f6621b 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -46,6 +46,9 @@ set(R4D_UNITS "r4d_attn_paged_h256_gqa2|" # Gemma 3 sliding window: head_dim 128, 2 queries per KV head, windowed decode and prefill. "r4d_attn_paged_h128_gqa2w|" + # One query head per KV head at 128 wide: plain MHA, the Unlimited-OCR decoder (10 over 10). + # Both legs, prefill and decode; see the file's header for why it is not a drafter-shaped unit. + "r4d_attn_paged_h128_gqa1|" # Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128 # (MiniCPM5-2B). "r4d_attn_paged_gqa8|" diff --git a/libr4d/r4d_attn_paged_h128_gqa1.hip b/libr4d/r4d_attn_paged_h128_gqa1.hip new file mode 100644 index 00000000..326840e6 --- /dev/null +++ b/libr4d/r4d_attn_paged_h128_gqa1.hip @@ -0,0 +1,20 @@ +/* r4d_attn_paged_h128_gqa1.hip -- head_dim 128 with ONE query head per KV head: plain MHA. + * + * Everything else in this library pages attention through a grouped ratio (4, 6, 8 or 12 queries + * per KV head). The Unlimited-OCR decoder has 10 query heads over 10 KV heads at 128 wide, so the + * ratio is 1 and none of the existing legs matches it; the engine reports every band of that + * geometry as having no kernel rather than serving it on the host. + * + * The device code is the generic body (r4d_attn_paged_gqa8.hip, which is parameterised by + * R4D_ATTN_GQA rather than fixed at 8) instantiated at ratio 1: the same templated prefill and + * split-KV decode kernels, with GQA=1 substituted. No new kernel, no new masking path. + * + * This unit ships BOTH legs, unlike the h128/gqa4 drafter unit: a decoder runs prefill as well as + * decode, and the caller-side fallback the drafter relies on is an order of magnitude slower. + * The prefill option set is the h128 set (G8_P_OPT_128), which is the one compiled and measured + * for this head width. */ +#define R4D_ATTN_GQA 1 +#define R4D_ATTN_H128 1 +#define R4D_ATTN_H256 0 + +#include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 6b74b26f..8a16e50c 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -261,6 +261,13 @@ int r4d_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa8_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa8_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h128_gqa8_scratch(const RadArgs*); +/* ONE query a KV head, head_dim 128 -- plain MHA, the Unlimited-OCR decoder (10 over 10). Both + * legs from the generic body instantiated at ratio 1 (r4d_attn_paged_h128_gqa1.hip). */ +int r4d_rad_attn_prefill_h128_gqa1_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h128_gqa1_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa1_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa1_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h128_gqa1_scratch(const RadArgs*); /* Four queries per KV head, head_dim 256 only (Qwen3.5-0.8B); same body, another instantiation * (r4d_attn_paged_h256_gqa4.hip). */ int r4d_rad_attn_prefill_h256_gqa4_fp8 (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4cd29805..98462ecb 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3731,6 +3731,28 @@ static const RadConstraint cAttnDecodeH128G8Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; + +/* head_dim 128 at ratio ONE: plain MHA (the Unlimited-OCR decoder, 10 query heads over 10), from + * r4d_attn_paged_h128_gqa1.hip. The decode leg caps at 64 query rows, which at this ratio is a + * plain q_len <= 64; the prefill leg has no query-row cap. */ +static const RadConstraint cAttnPrefillH128G1Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH128G1Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnDecodeH128G1Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH128G1Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +};/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's + * `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The + * predicate -- "bf16, and nothing else" -- is unchanged. */ /* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 pair's * constraints with the ratio and the decode verify width changed together. A decode workgroup * holds 64 (query, head) rows, so q_len <= 32 at gqa 2. */ @@ -5775,6 +5797,44 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h128_gqa1_fp8kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 128, 1 query per kv head (plain MHA), paged block 16, varlen", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128G1Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa1_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h128_gqa1_bf16kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 128, 1 query per kv head (plain MHA), paged block 16, varlen", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128G1Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa1_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa1_fp8kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify)", + "head_dim 128, 1 query per kv head (plain MHA), paged block 16, q_len <= 64, no window", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128G1Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa1_fp8, r4d_rad_attn_decode_h128_gqa1_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa1_bf16kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify)", + "head_dim 128, 1 query per kv head (plain MHA), paged block 16, q_len <= 64, no window", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128G1Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa1_bf16, r4d_rad_attn_decode_h128_gqa1_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 8 queries per kv head, paged block 16, varlen", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1e7e0e69..1a7853e9 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -22968,6 +22968,10 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0); attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); + attn_case(pl, "attn_prefill_h128_gqa1_bf16kv", 128, 1, 32, "bf16", 1); + attn_case(pl, "attn_prefill_h128_gqa1_fp8kv", 128, 1, 32, "fp8_e4m3", 1); + attn_case(pl, "attn_decode_h128_gqa1_bf16kv", 128, 1, 1, "bf16", 0); + attn_case(pl, "attn_decode_h128_gqa1_fp8kv", 128, 1, 1, "fp8_e4m3", 0); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); /* Gemma 4 dense sliding window, decode, with the model's window of 1024: exercises the diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index 6a771405..e277c90e 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -147,6 +147,84 @@ int ref_moe_scatter(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ router_topk_scatter */ +/* THE PAIR AS ONE OP, and the reference is the pair: the fused device kernel's whole claim is that + * it is byte-identical to these two launches, so the oracle that checks that claim is exactly + * these two, in order, over the operands the fused op carries. The selection runs over the whole + * router's `n_expert` logits; the sort runs over THIS RANK'S SLICE, which is the fused op's + * `n_local` standing where `moe_scatter`'s `n_expert` names the slice it owns. */ +int ref_router_topk_scatter(const RadArgs* a, RadStream s) { + if (!have(a, 6)) return RAD_E_INVAL; + const int64_t ne = p_int(a, "n_expert", 0); + const int64_t nl = p_int(a, "n_local", ne); + const int64_t k = p_int(a, "top_k", 1); + if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_SHAPE; + + const RadParam rp[] = { RAD_INT("n_expert", ne), RAD_INT("top_k", k), + RAD_INT("norm", p_int(a, "norm", 0)), + RAD_STR("dtype", p_str(a, "dtype", "bf16")) }; + const RadArgs ra{ a->t, 3, rp, 4, nullptr, 0, nullptr, a->rank, a->world_size }; + const int rc = ref_router_topk(&ra, s); + if (rc != RAD_OK) return rc; + + /* The fused op's operands with `expert_w` removed -- the sort's input is the selection's + * output, named once, and `moe_scatter` takes it in operand slot 0. RadArgs reads a + * contiguous tensor array, so the four descriptors are laid out here, by value. */ + const RadTensor t2[] = { a->t[1], a->t[3], a->t[4], a->t[5] }; + const RadParam sp[] = { RAD_INT("n_expert", nl), RAD_INT("top_k", k), + RAD_INT("expert_base", p_int(a, "expert_base", 0)), + RAD_STR("protect", p_str(a, "protect", nullptr)) }; + const RadArgs sa{ t2, 4, sp, 4, nullptr, 0, nullptr, a->rank, a->world_size }; + return ref_moe_scatter(&sa, s); +} + +/* ------------------------------------------------------------------ router_gemm_topk_scatter */ +/* THE ROUTER GEMM IN FRONT OF THE PAIR, and with `gate_b`/`gate` present the shared expert's + * one-column gate over the same input. As with the pair, the reference IS the launches it stands + * in for: the router's `gemm_nt`, the gate's `gemm_nt` at N = 1, then `router_topk_scatter` over + * the logits -- the fused kernel's claim is byte-identity to exactly these. `gate_b` and `gate` + * come together or not at all, and the operand count says which. */ +int ref_router_gemm_topk_scatter(const RadArgs* a, RadStream s) { + /* NOT `have`: the required operands are not a prefix -- `gate_b` sits between the router's + * weight and the outputs, and it and `gate` are null slots in the gate-absent form. The nine + * required slots are checked by name; the pair is checked to come together or not at all. */ + if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL; + const bool gate_b = a->n_t > 2 && a->t[2].data != nullptr; + const bool gate = a->n_t > 9 && a->t[9].data != nullptr; + if (gate_b != gate) return RAD_E_INVAL; + for (int i : {0, 1, 3, 4, 5, 6, 7, 8}) + if (!a->t[i].data) return RAD_E_INVAL; + const int64_t ne = p_int(a, "n_expert", 0); + const int64_t nl = p_int(a, "n_local", ne); + const int64_t k = p_int(a, "top_k", 1); + const int64_t K = p_int(a, "K", 0); + if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne || K <= 0) return RAD_E_SHAPE; + const char* dt = p_str(a, "dtype", "bf16"); + + /* The router: a [M, K] x b [n_expert, K]^T -> logits. gemm_nt takes a, b, y contiguously. */ + const RadTensor g3[] = { a->t[0], a->t[1], a->t[3] }; + const RadParam gp[] = { RAD_INT("N", ne), RAD_INT("K", K), RAD_STR("dtype", dt) }; + const RadArgs ga{ g3, 3, gp, 3, nullptr, 0, nullptr, a->rank, a->world_size }; + const int gc = ref_gemm_nt(&ga, s); + if (gc != RAD_OK) return gc; + + /* The shared expert's gate: the same arithmetic at N = 1, beside the router, over the same + * `a`. The pair was checked to come together. */ + if (gate) { + const RadTensor p3[] = { a->t[0], a->t[2], a->t[9] }; + const RadParam pp[] = { RAD_INT("N", 1), RAD_INT("K", K), RAD_STR("dtype", dt) }; + const RadArgs pa{ p3, 3, pp, 3, nullptr, 0, nullptr, a->rank, a->world_size }; + const int pc = ref_gemm_nt(&pa, s); + if (pc != RAD_OK) return pc; + } + + /* The pair over the logits the GEMM just wrote. Every parameter the pair reads is a parameter + * of this op, under the same name -- the fused lists are unions, so `a`'s list passes through. */ + const RadTensor t6[] = { a->t[3], a->t[4], a->t[5], a->t[6], a->t[7], a->t[8] }; + const RadArgs fa{ t6, 6, a->p, a->n_p, nullptr, 0, nullptr, a->rank, a->world_size }; + return ref_router_topk_scatter(&fa, s); +} + /* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */ /* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks * row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 3c72d4cc..be06287d 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -237,6 +237,8 @@ int ref_dflash_conv (const RadArgs*, RadStream); /* ---- mixture of experts */ int ref_router_topk (const RadArgs*, RadStream); int ref_moe_scatter (const RadArgs*, RadStream); +int ref_router_topk_scatter(const RadArgs*, RadStream); +int ref_router_gemm_topk_scatter(const RadArgs*, RadStream); int ref_moe_gemm (const RadArgs*, RadStream); int ref_moe_gemm_q (const RadArgs*, RadStream); int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream); @@ -469,6 +471,8 @@ REF_SHAPE_FN(ref_dflash_conv); REF_SHAPE_FN(ref_router_topk); REF_SHAPE_FN(ref_moe_scatter); +REF_SHAPE_FN(ref_router_topk_scatter); +REF_SHAPE_FN(ref_router_gemm_topk_scatter); REF_SHAPE_FN(ref_moe_gemm); REF_SHAPE_FN(ref_moe_gemm_q); REF_SHAPE_FN(ref_moe_gemm_q_mod4); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index fbf5cbe3..797ea083 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -472,6 +472,29 @@ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("t static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count") }; +/* THE PAIR AS ONE OP: the union of the two parameter lists, and their operands with the shared + * `expert_ids` named once, as an output. Same schema as libr4d's fused row. */ +static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"), + P_INTO("n_local"), P_INT("top_k"), + P_INT("norm"), P_STR("dtype"), + P_INTO("expert_base"), + P_STRO("protect") }; +static const RadOperandSpec oRouterTopkScatter[] = { OPD("logits"), OUT("expert_ids"), + OUT("expert_w"), OUT("sorted_tok"), + OUT("expert_offset"), + OUT("expert_count") }; + +/* THE ROUTER GEMM IN FRONT OF THE PAIR, and the gate's one-column GEMM beside it: the union of + * the three operand lists with `logits` named once, as the GEMM's output. */ +static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"), + P_INT("n_expert"), P_INTO("n_local"), + P_INT("top_k"), P_INT("norm"), + P_STR("dtype"), P_INTO("expert_base"), + P_STRO("protect") }; +static const RadOperandSpec oRouterGemmTopkScatter[] = { + OPD("a"), WGT("b"), WGT_O("gate_b"), OUT("logits"), OUT("expert_ids"), OUT("expert_w"), + OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count"), OUT_O("gate") }; + /* `a_order` says which rows the activation has; a routed block's two grouped GEMMs differ. gate_up * reads the block input, one row per token, so sorted row i gathers `a[sorted_tok[i] / top_k]`. * down reads gate_up's output, already one row per (token, slot) in scatter order, so row i is row @@ -1356,6 +1379,16 @@ static const RadOpSchema kSchemas[] = { "sorts only its own slice, and the slots that went elsewhere simply contribute nothing to this " "rank's partial -- which the block's end-of-block all-reduce then sums. `expert_base` absent " "or 0 with n_expert the model's count is the whole-model case." }, +{ "router_topk_scatter", ARR(pRouterTopkScatter), ARR(oRouterTopkScatter), + "`router_topk` then `moe_scatter`, in one launch: exactly those two and in that order, over " + "the operands they share. The reference IS the pair -- the fused device kernel claims to be " + "byte-identical to these two launches, and this is what it is measured against. The sort's " + "outputs are sized by `n_local`, this rank's slice; absent it is the router's count." }, +{ "router_gemm_topk_scatter", ARR(pRouterGemmTopkScatter), ARR(oRouterGemmTopkScatter), + "`gemm_nt` of `a` against the router `b`, then `router_topk_scatter` over those logits, and " + "with `gate_b`/`gate` present the shared expert's `gemm_nt` at N = 1 over the same `a`. As " + "with the pair, the reference IS the launches: the gate weight and output come together or not " + "at all, and the operand count says which." }, { "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm), "y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range contains i. " "`a_order` picks row(i): \"token\" gathers a[sorted_tok[i] / top_k] from an activation with one " @@ -2100,6 +2133,12 @@ SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routin ref_router_topk), SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert", "i32 indices", ref_moe_scatter), +SIMPLE("ref_router_topk_scatter", "router_topk_scatter", "moe", + "the selection and the sort in one op, run as exactly the pair", DT_FLOAT, + ref_router_topk_scatter), +SIMPLE("ref_router_gemm_topk_scatter", "router_gemm_topk_scatter", "moe", + "the router GEMM, the selection and the sort in one op, run as exactly the launches", + DT_FLOAT, ref_router_gemm_topk_scatter), SIMPLE("ref_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT, ref_moe_gemm), ROW_CB("ref_moe_gemm_q", "moe_gemm_q", "moe", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index efa78320..9525055c 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1653,8 +1653,55 @@ int ref_moe_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("moe_scatter", operand, out); } -/* `a_order` decides the activation's row count: one per token, or one per (token, slot) in - * scatter order. */ +/* The two shape lists concatenated, with `expert_ids` named ONCE as an output -- it is what the + * selection writes and what the sort reads. The sort's three outputs are sized by THIS RANK'S + * SLICE (`n_local`, absent means the slice is the router), exactly as in libr4d's shape. */ +int ref_router_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t ne = gi(p, n_p, "n_expert", 0); + const int64_t k = gi(p, n_p, "top_k", 0); + const int64_t nl = gi(p, n_p, "n_local", ne); + if (M <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, ne }); /* logits */ + o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */ + o.t(D, { M, k }); /* expert_w */ + o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */ + o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */ + o.t((uint32_t)RAD_I32, { nl }); /* expert_count */ + return o.finish("router_topk_scatter", operand, out); +} + +/* The router GEMM's list, the pair's list, and -- with the gate present -- the gate's one-column + * list, with `logits` named once as the GEMM's output. `gate_b`/`gate` come together or not: the + * operand count carries it, as in libr4d's shape. */ +int ref_router_gemm_topk_scatter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t K = gi(p, n_p, "K", 0); + const int64_t ne = gi(p, n_p, "n_expert", 0); + const int64_t k = gi(p, n_p, "top_k", 0); + const int64_t nl = gi(p, n_p, "n_local", ne); + if (M <= 0 || K <= 0 || ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, K }); /* a */ + o.t(D, { ne, K }); /* b: the router */ + o.t(D, { 1, K }); /* gate_b: the shared expert's gate */ + o.t(D, { M, ne }); /* logits */ + o.t((uint32_t)RAD_I32, { M, k }); /* expert_ids */ + o.t(D, { M, k }); /* expert_w */ + o.t((uint32_t)RAD_I32, { M * k }); /* sorted_tok */ + o.t((uint32_t)RAD_I32, { nl + 1 }); /* expert_offset */ + o.t((uint32_t)RAD_I32, { nl }); /* expert_count */ + o.t(D, { M, 1 }); /* gate */ + return o.finish("router_gemm_topk_scatter", operand, out); +} + +/* `a_order` decides the activation's row count: one per token, or one per (token, slot) already + * in the scatter's order. A described case that got this wrong would build the operand at the + * extent the WRONG reading wants, and the fault it names would go unseen. */ static inline bool sorted_a_order(const RadParam* p, int n_p) { const char* s = gs(p, n_p, "a_order"); return s && std::strcmp(s, "sorted") == 0; diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 052f5835..6f2c9a5e 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -945,7 +945,8 @@ TEST(op_vocabulary) { /* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that * issues them has no other host path. */ "qsa_score", "qsa_select", "qsa_tail_store", "qsa_work", "dflash_conv", - "router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", + "router_topk", "moe_scatter", "router_topk_scatter", "router_gemm_topk_scatter", + "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather", "row_topk", "row_topk_merge", "pair_argmax", "logit_rerank", "gdn_conv_prep", "gdn_conv_update", "gdn_kkt_solve", "gdn_chunk_scan", @@ -3932,6 +3933,50 @@ TEST(op_router_topk) { CHECK_NEAR(w2.at(1), 0.26894142f, 1e-6); } +TEST(op_router_gemm_topk_scatter) { + /* THE GATE-ABSENT FORM: the plugin-owned shared arm issues the gate itself, so the fused op + * resolves with `gate_b` and `gate` as NULL SLOTS. Two tokens, three columns, four experts, + * top-two. */ + const int64_t M = 2, K = 3, ne = 4, k = 2; + T x(RAD_F32, {M, K}); x.f({1, 0, 0, 0, 1, 0}); + T w(RAD_F32, {ne, K}); w.f({1, 0, 0, 0, 2, 0, 0, 0, 3, 1, 1, 0}); + T lg(RAD_F32, {M, ne}); + T ids(RAD_I32, {M, k}), ew(RAD_F32, {M, k}); + T sorted(RAD_I32, {M * k}), eoff(RAD_I32, {ne + 1}), ecnt(RAD_I32, {ne}); + A a; a.t(x).t(w).tnull().t(lg).t(ids).t(ew).t(sorted).t(eoff).t(ecnt).tnull() + .i("M", M).i("K", K).i("n_expert", ne).i("n_local", ne).i("top_k", k).i("norm", 0) + .s("dtype", "f32").i("expert_base", 0); + CHECK_OK(run("router_gemm_topk_scatter", a)); + /* Row 0: logits {1, 0, 0, 1} -- experts 0 and 3 tie at 1, the LOWER id is selected first, + * then 3; row 1: {0, 2, 0, 1} -- 1 at 2, then 3 at 1. */ + CHECK_EQ(ids.iat(0), 0LL); CHECK_EQ(ids.iat(1), 3LL); + CHECK_EQ(ids.iat(2), 1LL); CHECK_EQ(ids.iat(3), 3LL); + CHECK_NEAR(lg.at(3), 1.0f, 1e-6); + CHECK_NEAR(lg.at(5), 2.0f, 1e-6); + /* The sort: expert 0 has slot 0, expert 1 slot 2, expert 3 slots 1 and 3 -- sorted by pair. */ + CHECK_EQ(eoff.iat(0), 0LL); CHECK_EQ(eoff.iat(1), 1LL); CHECK_EQ(eoff.iat(2), 2LL); + CHECK_EQ(eoff.iat(3), 2LL); CHECK_EQ(eoff.iat(4), 4LL); + CHECK_EQ(sorted.iat(0), 0LL); CHECK_EQ(sorted.iat(1), 2LL); + CHECK_EQ(sorted.iat(2), 1LL); CHECK_EQ(sorted.iat(3), 3LL); + CHECK_NEAR(ew.at(0) + ew.at(1), + (std::exp(0.0f) + std::exp(0.0f)) / + (2.0f * std::exp(0.0f) + 2.0f * std::exp(-1.0f)), 1e-5); + + /* THE GATE PRESENT: `gate` = x @ gate_b^T at N = 1, beside the router, over the same x. */ + T gb(RAD_F32, {1, K}); gb.f({2, 3, 0}); + T gate(RAD_F32, {M, 1}); + T lg2(RAD_F32, {M, ne}); + T ids2(RAD_I32, {M, k}), ew2(RAD_F32, {M, k}); + T sorted2(RAD_I32, {M * k}), eoff2(RAD_I32, {ne + 1}), ecnt2(RAD_I32, {ne}); + A b; b.t(x).t(w).t(gb).t(lg2).t(ids2).t(ew2).t(sorted2).t(eoff2).t(ecnt2).t(gate) + .i("M", M).i("K", K).i("n_expert", ne).i("n_local", ne).i("top_k", k).i("norm", 1) + .s("dtype", "f32").i("expert_base", 0); + CHECK_OK(run("router_gemm_topk_scatter", b)); + CHECK_NEAR(gate.at(0), 2.0f, 1e-6); + CHECK_NEAR(gate.at(1), 3.0f, 1e-6); + CHECK_NEAR(ew2.at(0) + ew2.at(1), 1.0f, 1e-6); /* renormalised to sum to one */ +} + /* The four-class grouped GEMM: expert e is entry e / 4 of class e % 4, each class at its own * width, and a narrower class's columns past its width are zero. Ten experts, so classes 0 and 1 * hold three and 2 and 3 hold two (the shape of a layer with 510 quantised experts), and class 1 @@ -7824,6 +7869,11 @@ std::vector geometries() { G("scale_rows", "M", 3, a.i("M", R).i("n", 8).s("act", "sigmoid").s("dtype", "f32")), G("router_topk", "M", 3, a.i("M", R).i("n_expert", 6).i("top_k", 2).i("norm", 1) .s("dtype", "f32")), + G("router_topk_scatter", "M", 3, a.i("M", R).i("n_expert", 6).i("n_local", 4) + .i("top_k", 2).i("norm", 1).s("dtype", "f32")), + G("router_gemm_topk_scatter", "M", 3, a.i("M", R).i("K", 32).i("n_expert", 4) + .i("n_local", 4).i("top_k", 2).i("norm", 0) + .s("dtype", "f32")), G("moe_scatter", "M", 3, a.i("M", R).i("n_expert", 6).i("top_k", 2)), G("moe_gemm", "M", 3, a.i("M", R).i("N", 16).i("K", 32).i("n_expert", 4).i("top_k", 2) .s("a_order", "token").s("dtype", "f32")), diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 78a8a144..9b9348e9 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -94,7 +94,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, - { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; + { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, + { "unlimitedocr", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); if (got != want)