Archived
Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port
Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
mtp_couple_propose.
Also ignores /baseline-models/ (local model copies).
Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
45f3b510c7
365 files changed
+56942
-6331
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/bailing_hybrid -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(bailing_hybrid LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(bailing_hybrid architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid.cpp)
|
||||
@@ -0,0 +1,885 @@
|
||||
/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`,
|
||||
* BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them
|
||||
* (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe).
|
||||
*
|
||||
* ============================== WHAT IT SERVES ==============================
|
||||
*
|
||||
* layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense
|
||||
* latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA
|
||||
* KDA 32 heads of 128, separate q/k/v projections each with its own causal
|
||||
* convolution, a full-rank per-channel forget gate (`f_proj`) and output gate
|
||||
* (`g_proj`), lower bound -5
|
||||
* MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs),
|
||||
* heads of 128 + 64, values of 128, a sigmoid gate per head
|
||||
* feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under
|
||||
* group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an
|
||||
* ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers
|
||||
* (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and
|
||||
* SGLang serve it; HF's reference ignores it)
|
||||
*
|
||||
* The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the
|
||||
* feed-forward MoeFP8. The KDA and MLA blocks around them are in this file.
|
||||
*
|
||||
* ============================== THE LATENT ATTENTION ==============================
|
||||
*
|
||||
* The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and
|
||||
* their nope rows (row maps over q_proj), so each is a plain [T, heads * width] plane: `rope` turns
|
||||
* the first, and the second is absorbed into the latent through kv_b's key rows (mla_project).
|
||||
* `mla_attn_paged` scores against a cache row of [normed latent 512 | rotated key 64] and returns
|
||||
* the latent, gated per head; kv_b's value rows expand it. The cache row is stored as one KV head
|
||||
* of 288, the latent's first 288 values in the K slot and the rest in the V slot.
|
||||
*
|
||||
* ============================== THE DRAFTER ==============================
|
||||
*
|
||||
* The MTP layer (checkpoint layer 42: an MLA layer with the full routed feed-forward) is a serial
|
||||
* drafter around GlmMtp, declared when the deployment speculates.
|
||||
*
|
||||
* docs/ARCHITECTURES.md describes the model and its traps. */
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_glm_kda.h>
|
||||
#include <arch/rad_block_glm_mtp.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
|
||||
namespace bailing_hybrid {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* The released geometry this graph is written for; a checkpoint that differs is refused by name. */
|
||||
struct Shape {
|
||||
int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0,
|
||||
latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0,
|
||||
ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0;
|
||||
double lower = -5, route_scale = 1;
|
||||
std::vector<double> lim_exp, lim_shared;
|
||||
};
|
||||
|
||||
/* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and
|
||||
* its all-reduce. */
|
||||
struct LingKda {
|
||||
struct Wire {
|
||||
ActFP8 input{};
|
||||
rad_buf out = 0;
|
||||
ActFP8 core_out{};
|
||||
KdaState::Wire core{};
|
||||
};
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
KdaState core{};
|
||||
LinearFP8 qkv{}, beta{}, forget{}, gate{}, output{};
|
||||
QuantFP8 out_quant{};
|
||||
rad_op op_ar = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l,
|
||||
const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) {
|
||||
g = geom;
|
||||
w = wire;
|
||||
const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim;
|
||||
const auto grp = grp_layer(l);
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre),
|
||||
nm.ckpt("%s.v_proj.weight", pre) },
|
||||
w.input, w.core.qkv, 0, { width, width, width }));
|
||||
RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) },
|
||||
w.input, w.core.beta));
|
||||
RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) },
|
||||
w.input, w.core.a));
|
||||
RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
|
||||
w.input, w.core.gate));
|
||||
KdaState::Config kc;
|
||||
kc.heads = heads;
|
||||
kc.dim = sh.head_dim;
|
||||
kc.width = sh.conv;
|
||||
kc.lower = sh.lower;
|
||||
KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre),
|
||||
nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre),
|
||||
nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) };
|
||||
RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks));
|
||||
const char* on = nm.f("blk.%d.attn_output", l);
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) }));
|
||||
if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width));
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out));
|
||||
op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
qkv.step(c, w.input, w.core.qkv, T);
|
||||
beta.step(c, w.input, w.core.beta, T);
|
||||
forget.step(c, w.input, w.core.a, T);
|
||||
gate.step(c, w.input, w.core.gate, T);
|
||||
core.step(c, batch);
|
||||
out_quant.step(c, T);
|
||||
output.step(c, w.core_out, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
/* A dense MLA layer, attending in the latent (the file's head comment). The latent cache is
|
||||
* replicated: every rank projects and stores the whole row, and splits the heads. */
|
||||
struct LingMla {
|
||||
struct Wire {
|
||||
ActFP8 input{};
|
||||
rad_buf q_rope = 0; /* [T, heads * rope] */
|
||||
rad_buf q_nope = 0; /* [T, heads * nope] */
|
||||
rad_buf row = 0; /* [T, latent + rope], the cache row */
|
||||
rad_buf q_lat = 0; /* [T, heads, latent] */
|
||||
rad_buf gate = 0; /* [T, heads] */
|
||||
rad_buf attn = 0; /* [T, heads, latent] */
|
||||
ActFP8 value{}; /* [T, heads * v] */
|
||||
rad_buf out = 0;
|
||||
};
|
||||
Geom g{};
|
||||
Shape s{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
int64_t heads = 0, qw = 0, cw = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{};
|
||||
QuantFP8 value_quant{};
|
||||
rad_weight kv_gain = 0, kv_b = 0;
|
||||
rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0,
|
||||
op_expand = 0, op_ar = 0;
|
||||
int64_t block = 0;
|
||||
|
||||
static constexpr int64_t kBlock = 16;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& shape, int l,
|
||||
const Wire& wire, const char* pre, rad_kvgroup group) {
|
||||
g = geom;
|
||||
s = shape;
|
||||
w = wire;
|
||||
layer = l;
|
||||
kv = group;
|
||||
heads = s.heads / g.world;
|
||||
qw = s.rope + s.nope;
|
||||
cw = s.latent + s.rope;
|
||||
const auto grp = grp_layer(l);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
/* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS
|
||||
* maps for one name extend it in call order (rad_builder.h), eight pieces a map. */
|
||||
const char* qsrc = nm.ckpt("%s.q_proj.weight", pre);
|
||||
auto part = [&](const char* name, int64_t off, int64_t width) -> int {
|
||||
for (int64_t h0 = 0; h0 < s.heads; h0 += 8) {
|
||||
RadNameMap m = map_base(name, RAD_MAP_ROWS);
|
||||
for (int64_t h = h0; h < std::min(h0 + 8, s.heads); ++h) {
|
||||
m.src[m.n_src] = qsrc;
|
||||
m.src_index[m.n_src] = (int)(h * qw + off);
|
||||
m.src_rows[m.n_src] = width;
|
||||
++m.n_src;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_decl_name_map(b, &m));
|
||||
}
|
||||
return RAD_OK;
|
||||
};
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope));
|
||||
RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope));
|
||||
q_rope_proj.mapped = q_nope_proj.mapped = true;
|
||||
RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope,
|
||||
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope));
|
||||
RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope,
|
||||
g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope));
|
||||
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd,
|
||||
RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) },
|
||||
w.input, w.row));
|
||||
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre)));
|
||||
kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
if (!kv_gain) return RAD_E_INVAL;
|
||||
op_kv_norm = rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.latent),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(kv_gain)),
|
||||
{ w.row }, { w.row });
|
||||
op_q_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, heads, 0, s.rope, "gptj"), { w.q_rope },
|
||||
{ w.q_rope });
|
||||
op_k_rope = rw(b, decl_rope(b, g, g.max_tok, s.rope, 1, 0, s.rope, "gptj"), { w.row },
|
||||
{ w.row });
|
||||
/* The first op after the group to carry a block size claims it (rad_builder.cpp,
|
||||
* find_kv_consumer). */
|
||||
op_store = rw(b,
|
||||
RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cw / 2),
|
||||
RAD_INT("n_head_kv", 1), RAD_INT("block_size", kBlock),
|
||||
RAD_STR("kv_dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.row }, {});
|
||||
const char* bn = nm.f("blk.%d.attn_kv_b.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre)));
|
||||
kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_ROW, grp);
|
||||
if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) 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", heads),
|
||||
RAD_INT("head_dim", s.nope), RAD_INT("latent_dim", s.latent),
|
||||
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(kv_b)),
|
||||
{ w.q_nope }, { w.q_lat });
|
||||
RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd,
|
||||
RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) },
|
||||
w.input, w.gate));
|
||||
op_attn = rw(b,
|
||||
RAD_OP(b, "mla_attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
|
||||
RAD_INT("latent_dim", s.latent), RAD_INT("rope_dim", s.rope),
|
||||
RAD_INT("block_size", kBlock),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)qw)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.q_lat, w.q_rope, w.gate }, { w.attn });
|
||||
op_expand = rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", heads),
|
||||
RAD_INT("head_dim", s.v_dim), RAD_INT("latent_dim", s.latent),
|
||||
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(kv_b)),
|
||||
{ w.attn }, { w.value.x });
|
||||
if (!op_absorb || !op_attn || !op_expand) return RAD_E_INVAL;
|
||||
block = rad_kv_block_size(b, kv);
|
||||
if (block != kBlock) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the latent cache's block is %lld tokens and "
|
||||
"its ops are declared at %lld\n", (long long)block, (long long)kBlock);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const char* on = nm.f("blk.%d.attn_output", l);
|
||||
RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) }));
|
||||
if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim));
|
||||
RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.dense.weight", pre) }, w.value, w.out));
|
||||
op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
if (!kb || !kb->slot_mapping || !kb->block_table || !kb->seqused) {
|
||||
rad_step_fail(c, "bailing_hybrid MLA requires the latent cache's slot mapping, block "
|
||||
"table and sequence lengths");
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
q_rope_proj.step(c, w.input, w.q_rope, T);
|
||||
q_nope_proj.step(c, w.input, w.q_nope, T);
|
||||
kv_a.step(c, w.input, w.row, T);
|
||||
g_proj.step(c, w.input, w.gate, T);
|
||||
RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain),
|
||||
bcol(w.row, 0, s.latent, T));
|
||||
RAD_ISSUE_N(c, op_q_rope, T, brows(w.q_rope, T), pos);
|
||||
RAD_ISSUE_N(c, op_k_rope, T, bcol(w.row, s.latent, s.rope, T), pos);
|
||||
RAD_ISSUE_N(c, op_store, T, bcol(w.row, 0, cw / 2, T), bcol(w.row, cw / 2, cw / 2, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_absorb, T, brows(w.q_nope, T), RAD_W(kv_b), brows(w.q_lat, T));
|
||||
RAD_ISSUE_N(c, op_attn, T, brows(w.q_lat, T), brows(w.q_rope, T), kv_cache(kv, layer),
|
||||
praw2(kb->block_table, RAD_I32, S, kb->block_table_pitch),
|
||||
praw(kb->seqused, RAD_I32, S), praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
brows(w.gate, T), brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_expand, T, brows(w.attn, T), RAD_W(kv_b), brows(w.value.x, T));
|
||||
value_quant.step(c, T);
|
||||
output.step(c, w.value, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.out, T), RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
bool mla = false, dense = false;
|
||||
rad_weight gain = 0;
|
||||
NormQuantFP8 norm{};
|
||||
LingKda kda{};
|
||||
LingMla attn{};
|
||||
rad_op op_add = 0;
|
||||
MlpFP8 mlp{};
|
||||
MoeFP8 moe{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
Shape s{};
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, state = 0, conv = 0;
|
||||
rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0;
|
||||
ActFP8 act{};
|
||||
LingKda::Wire kw{};
|
||||
LingMla::Wire aw{};
|
||||
MlpFP8::Wire dw{};
|
||||
MoeFP8::Wire mw{};
|
||||
rad_weight token = 0, head = 0, final_gain = 0;
|
||||
rad_op embed = 0, embed_ar = 0, norm = 0, gather = 0, head_op = 0;
|
||||
/* The draft head and its layer, declared only when the deployment speculates. */
|
||||
bool have_mtp = false;
|
||||
GlmMtp mtp{};
|
||||
Layer draft{};
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
return rad_meta_geti(m, key, fallback);
|
||||
}
|
||||
|
||||
static std::vector<double> cfg_list(const RadModelMeta* m, const char* key) {
|
||||
std::vector<double> v;
|
||||
for_each_token(rad_meta_gets(m, key, ""), [&](const char* t, size_t) {
|
||||
v.push_back(std::strtod(t, nullptr));
|
||||
return true;
|
||||
});
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Layer l's SwiGLU clamp from a per-layer list; 0 (none) past its end or where it says 0. */
|
||||
static double limit_at(const std::vector<double>& v, int64_t l) {
|
||||
return l < (int64_t)v.size() && v[(size_t)l] > 0 ? v[(size_t)l] : 0;
|
||||
}
|
||||
|
||||
/* The last layer of each group of `layer_group_size` is MLA, and so is every layer of an
|
||||
* incomplete last group. */
|
||||
static bool is_mla(const Shape& s, int64_t l) {
|
||||
return (l + 1) % s.group_size == 0 || l >= s.n_layer / s.group_size * s.group_size;
|
||||
}
|
||||
|
||||
static int read_shape(const RadModelMeta* meta, Shape& s) {
|
||||
s.n_embd = meta->n_embd;
|
||||
s.n_layer = meta->n_layers;
|
||||
s.heads = cfg(meta, "num_attention_heads", 0);
|
||||
s.head_dim = cfg(meta, "head_dim", 0);
|
||||
s.nope = cfg(meta, "qk_nope_head_dim", 0);
|
||||
s.rope = cfg(meta, "qk_rope_head_dim", 0);
|
||||
s.v_dim = cfg(meta, "v_head_dim", 0);
|
||||
s.latent = cfg(meta, "kv_lora_rank", 0);
|
||||
s.experts = cfg(meta, "num_experts", 0);
|
||||
s.top_k = cfg(meta, "num_experts_per_tok", 0);
|
||||
s.groups = cfg(meta, "n_group", 1);
|
||||
s.topk_groups = cfg(meta, "topk_group", s.groups);
|
||||
s.ff_exp = cfg(meta, "moe_intermediate_size", 0);
|
||||
s.ff_shared = cfg(meta, "moe_shared_expert_intermediate_size", 0) *
|
||||
cfg(meta, "num_shared_experts", 0);
|
||||
s.ff_dense = cfg(meta, "intermediate_size", 0);
|
||||
s.dense_layers = cfg(meta, "first_k_dense_replace", 0);
|
||||
s.group_size = cfg(meta, "layer_group_size", 0);
|
||||
s.conv = cfg(meta, "short_conv_kernel_size", 0);
|
||||
s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0);
|
||||
s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0);
|
||||
s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list");
|
||||
s.lim_shared = cfg_list(meta, "share_expert_swiglu_limit_list");
|
||||
const struct {
|
||||
const char* what;
|
||||
bool ok;
|
||||
} need[] = {
|
||||
{ "head_dim 128 (KDA)", s.head_dim == 128 },
|
||||
{ "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim },
|
||||
{ "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) },
|
||||
{ "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) },
|
||||
{ "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 },
|
||||
{ "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 },
|
||||
{ "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 },
|
||||
{ "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) },
|
||||
{ "rope_interleave", cfg(meta, "rope_interleave", 0) != 0 },
|
||||
{ "head-wise gated attention",
|
||||
!std::strcmp(rad_meta_gets(meta, "gated_attention_proj_granularity_type", ""),
|
||||
"head_wise") },
|
||||
{ "sigmoid scoring", !std::strcmp(rad_meta_gets(meta, "score_function",
|
||||
rad_meta_gets(meta, "scoring_func", "")),
|
||||
"sigmoid") },
|
||||
{ "one shared expert", cfg(meta, "num_shared_experts", 0) == 1 },
|
||||
{ "a layer group", s.group_size > 1 },
|
||||
{ "a 4-tap short convolution", s.conv == 4 },
|
||||
{ "experts, top-k and groups", s.experts > 0 && s.top_k > 0 && s.groups >= 1 &&
|
||||
s.experts % s.groups == 0 && s.topk_groups >= 1 &&
|
||||
s.topk_groups <= s.groups },
|
||||
{ "a positive routed_scaling_factor", s.route_scale > 0 },
|
||||
{ "no rope scaling", !rad_meta_gets(meta, "rope_scaling.type", nullptr) &&
|
||||
!rad_meta_gets(meta, "rope_scaling.rope_type", nullptr) },
|
||||
};
|
||||
for (const auto& n : need)
|
||||
if (!n.ok) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: this plugin serves %s, and the checkpoint "
|
||||
"differs\n", n.what);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A rank's slice of a width of `blocks` 128-column blocks: blocks [lo, hi) in the order of the
|
||||
* ranks starting at `first`, the first `blocks % world` ranks of that order one block wider. */
|
||||
static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo, int64_t* hi) {
|
||||
const int p = ((rank - first) % world + world) % world;
|
||||
const int64_t base = blocks / world, extra = blocks % world;
|
||||
*lo = p * base + std::min<int64_t>(p, extra);
|
||||
*hi = *lo + base + (p < extra ? 1 : 0);
|
||||
}
|
||||
|
||||
/* ============================== The trunk's buffers ============================== */
|
||||
|
||||
static int buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& s = m.s;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim;
|
||||
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
|
||||
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
|
||||
};
|
||||
m.x = bf("residual", { T, E });
|
||||
m.y = bf("attn_delta", { T, E });
|
||||
m.act.x = bf("normed", { T, E });
|
||||
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E));
|
||||
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST);
|
||||
m.logit_input = bf("logit_input", { g.max_logit_rows, E });
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
auto& kw = m.kw;
|
||||
kw.input = m.act;
|
||||
kw.out = m.y;
|
||||
kw.core.qkv = bf("kda_qkv", { T, 3 * W });
|
||||
kw.core.conv = bf("kda_convolved", { T, 3 * W });
|
||||
kw.core.a = bf("kda_forget", { T, W });
|
||||
kw.core.beta = bf("kda_beta", { T, H });
|
||||
kw.core.gate = bf("kda_gate", { T, W });
|
||||
kw.core.out = bf("kda_out", { T, W });
|
||||
kw.core_out.x = kw.core.out;
|
||||
RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W));
|
||||
|
||||
auto& aw = m.aw;
|
||||
aw.input = m.act;
|
||||
aw.out = m.y;
|
||||
aw.q_rope = bf("mla_q_rope", { T, H * s.rope });
|
||||
aw.q_nope = bf("mla_q_nope", { T, H * s.nope });
|
||||
aw.row = bf("mla_row", { T, s.latent + s.rope });
|
||||
aw.q_lat = bf("mla_q_latent", { T, H * s.latent });
|
||||
aw.gate = bf("mla_gate", { T, H });
|
||||
aw.attn = bf("mla_attn_latent", { T, H * s.latent });
|
||||
aw.value.x = bf("mla_value", { T, H * s.v_dim });
|
||||
RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim));
|
||||
|
||||
auto& dw = m.dw;
|
||||
dw.x = m.x;
|
||||
dw.h = m.act;
|
||||
dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff });
|
||||
dw.ffn.x = bf("dense_ff", { T, g.n_ff });
|
||||
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k;
|
||||
auto bf = [&](const char* n, std::initializer_list<int64_t> shape) {
|
||||
return decl_b(b, nm.f("%s", n), RAD_BF16, shape);
|
||||
};
|
||||
auto& mw = m.mw;
|
||||
mw.x = m.x;
|
||||
mw.h = m.act;
|
||||
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, mc.n_expert_all });
|
||||
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, k });
|
||||
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, k });
|
||||
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { mc.n_expert + 1 });
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { mc.n_expert });
|
||||
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k });
|
||||
mw.egu = bf("expert_gate_up", { T * k, 2 * F });
|
||||
mw.eff.x = bf("expert_ff", { T * k, F });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k));
|
||||
mw.edn = bf("expert_down", { T * k, E });
|
||||
if (mc.expert_rot) {
|
||||
mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E });
|
||||
mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK });
|
||||
if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL;
|
||||
}
|
||||
if (mc.n_ff_shared > 0) {
|
||||
mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared });
|
||||
mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared });
|
||||
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared));
|
||||
mw.sout = bf("shared_out", { T, E });
|
||||
mw.sgate = bf("shared_one", { T, 1 });
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ============================== declare ============================== */
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
/* A sizing declare writes scratch: the step reads g_model, filled by the real declare at the
|
||||
* real max_tok (RadBuildCtx::shape_probe). */
|
||||
static thread_local Model probe_model;
|
||||
Model& m = ctx->shape_probe ? probe_model : g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& g = m.g;
|
||||
auto& s = m.s;
|
||||
auto& nm = m.nm;
|
||||
RAD_ARCH_TRY(read_shape(meta, s));
|
||||
if (world != 1 && world != 2 && world != 4) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: --tp %d; the head and expert splits are built "
|
||||
"for 1, 2 or 4 ranks\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (s.heads % world || s.ff_exp % RAD_FP8_BLOCK || s.ff_shared % RAD_FP8_BLOCK ||
|
||||
s.ff_exp / RAD_FP8_BLOCK < world) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: %lld heads and experts of %lld do not split "
|
||||
"over %d ranks in whole heads and 128-column blocks\n",
|
||||
(long long)s.heads, (long long)s.ff_exp, world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_spec > 31) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the KDA verify pass takes at most 32 rows a "
|
||||
"sequence, so --num-speculative-tokens is at most 31\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the latent and KDA caches are bf16; run with "
|
||||
"--kv-cache-dtype bf16\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(geom_from(g, meta, ctx, "bf16", RAD_BF16));
|
||||
g.head_dim = s.head_dim;
|
||||
|
||||
/* ---- the routed experts' slice of this rank: whole at one rank, halves at two, and at four
|
||||
* the six 128-column blocks of an expert split 2, 2, 1, 1 over the ranks, rotated by the
|
||||
* expert's number mod 4, so every rank carries six blocks per four experts (moe_gemm_q_mod4).
|
||||
* The shared expert splits the same way, unrotated. */
|
||||
MoeFP8::Config mc;
|
||||
mc.n_expert = mc.n_expert_all = s.experts;
|
||||
mc.top_k = s.top_k;
|
||||
mc.sigmoid_router = 1;
|
||||
mc.route_scale = s.route_scale;
|
||||
mc.norm_topk = cfg(meta, "norm_topk_prob", 1) != 0;
|
||||
mc.n_group = s.groups;
|
||||
mc.topk_group = s.topk_groups;
|
||||
mc.shared_ungated = 1;
|
||||
mc.swiglu_step = 1;
|
||||
mc.rows = g.max_tok;
|
||||
/* GPTQ calibration (RADIANCE_CALIB_DIR): the tap writes each expert's down Hessian over its
|
||||
* whole width, so a calibration run gives every rank whole experts (below). */
|
||||
mc.calib = calib_dir() != nullptr ? 1 : 0;
|
||||
mc.probed_expert = (int64_t)g.rank * (s.experts / world);
|
||||
const int64_t eb = s.ff_exp / RAD_FP8_BLOCK, sb = s.ff_shared / RAD_FP8_BLOCK;
|
||||
if (world == 4) {
|
||||
int64_t widest = 0;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
int64_t lo, hi;
|
||||
slice_of(eb, world, g.rank, q, &lo, &hi);
|
||||
mc.ff_lo4[q] = lo * RAD_FP8_BLOCK;
|
||||
mc.ff_hi4[q] = hi * RAD_FP8_BLOCK;
|
||||
widest = std::max(widest, mc.ff_hi4[q] - mc.ff_lo4[q]);
|
||||
}
|
||||
mc.n_ff_exp = widest;
|
||||
} else if (eb % world == 0) {
|
||||
mc.n_ff_exp = s.ff_exp / world;
|
||||
} else {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: experts of %lld do not halve into 128-column "
|
||||
"blocks\n", (long long)s.ff_exp);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (sb % world == 0) {
|
||||
mc.n_ff_shared = s.ff_shared / world;
|
||||
} else {
|
||||
int64_t lo, hi;
|
||||
slice_of(sb, world, g.rank, 0, &lo, &hi);
|
||||
mc.shared_lo = lo * RAD_FP8_BLOCK;
|
||||
mc.shared_hi = hi * RAD_FP8_BLOCK;
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
}
|
||||
if (s.ff_dense % (world * RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: bailing_hybrid: the dense feed-forward's %lld columns do not "
|
||||
"split over %d ranks in 128-column blocks\n", (long long)s.ff_dense, world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
g.n_ff_all = s.ff_dense;
|
||||
g.n_ff = s.ff_dense / world;
|
||||
|
||||
/* ---- each routed layer's expert format, read before any buffer is declared: rotated experts
|
||||
* need the rotated activation pair, sized here. The MTP layer follows the trunk's. */
|
||||
const bool mtp = ctx->max_spec > 0 && cfg(meta, "num_nextn_predict_layers", 0) == 1;
|
||||
std::vector<MoeFP8::Src> msrc((size_t)s.n_layer + 1);
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
const char* pre = nm.ckpt("model.layers.%d", l);
|
||||
MoeFP8::Src& ms = msrc[(size_t)l];
|
||||
ms.cfg = mc;
|
||||
ms.cfg.swiglu_limit = limit_at(s.lim_exp, l);
|
||||
ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l);
|
||||
ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
|
||||
ms.router = nm.ckpt("%s.mlp.gate.weight", pre);
|
||||
ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre);
|
||||
ms.experts = nm.ckpt("%s.mlp.experts", pre);
|
||||
ms.shared = nm.ckpt("%s.mlp.shared_experts", pre);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg));
|
||||
if (ms.cfg.expert_rot) mc.expert_rot = 1;
|
||||
if (ms.cfg.expert_bf16) mc.expert_bf16 = 1;
|
||||
}
|
||||
/* ---- whole experts per rank for a calibration run and for bf16 experts (a slice of a bf16
|
||||
* expert is not one container run), as qwen4exp does: rank r owns experts [r E/W, (r+1) E/W).
|
||||
* Served to calibrate and compare, not for decode speed. */
|
||||
if (world > 1 && (mc.calib || mc.expert_bf16)) {
|
||||
int64_t per = 0;
|
||||
RAD_ARCH_TRY(divide_or_fail(s.experts, world, "num_experts", &per));
|
||||
for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) {
|
||||
auto& c = msrc[(size_t)l].cfg;
|
||||
c.n_expert = per;
|
||||
c.expert_base = (int64_t)g.rank * per;
|
||||
c.n_ff_exp = s.ff_exp;
|
||||
for (int q = 0; q < 4; ++q) c.ff_lo4[q] = c.ff_hi4[q] = 0;
|
||||
}
|
||||
mc.n_expert = per;
|
||||
mc.expert_base = (int64_t)g.rank * per;
|
||||
mc.n_ff_exp = s.ff_exp;
|
||||
rad_note(b, "%s: rank %d owns experts [%lld, %lld) of %lld whole",
|
||||
mc.calib ? "calibration (each expert's Hessian is over its whole width)"
|
||||
: "bf16 experts",
|
||||
g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per),
|
||||
(long long)s.experts);
|
||||
}
|
||||
RAD_ARCH_TRY(buffers(b, m));
|
||||
RAD_ARCH_TRY(moe_buffers(b, m, mc));
|
||||
|
||||
/* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution
|
||||
* history. */
|
||||
{
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = (s.latent + s.rope) / 2;
|
||||
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
|
||||
d = {};
|
||||
d.kind = RAD_KV_LINEAR;
|
||||
d.dtype = RAD_F32;
|
||||
d.n_head_kv = s.heads / world;
|
||||
d.state_dim[0] = d.state_dim[1] = s.head_dim;
|
||||
m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d);
|
||||
d = {};
|
||||
d.kind = RAD_KV_CONV;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 3 * (s.heads / world) * s.head_dim;
|
||||
d.conv_width = s.conv;
|
||||
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
|
||||
if (!m.latent || !m.state || !m.conv) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- the embedding, the layers, the final norm and the head. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
m.token = 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.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_ROW, grp_model());
|
||||
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { g.n_embd },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.token)),
|
||||
{}, { m.x });
|
||||
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
|
||||
|
||||
m.layers.resize((size_t)s.n_layer);
|
||||
for (int l = 0; l < (int)s.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.mla = is_mla(s, l);
|
||||
lay.dense = l < s.dense_layers;
|
||||
const char* pre = nm.ckpt("model.layers.%d", l);
|
||||
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
|
||||
lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd));
|
||||
const char* ap = nm.ckpt("%s.attention", pre);
|
||||
if (lay.mla) {
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, s, l, m.aw, ap, m.latent));
|
||||
} else {
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.state));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.conv));
|
||||
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, s, l, m.kw, ap, m.state, m.conv));
|
||||
}
|
||||
lay.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", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.x, m.y }, { m.x });
|
||||
if (!lay.op_add) return RAD_E_INVAL;
|
||||
if (lay.dense) {
|
||||
MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
|
||||
nm.ckpt("%s.mlp.gate_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.up_proj.weight", pre),
|
||||
nm.ckpt("%s.mlp.down_proj.weight", pre) };
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds));
|
||||
} else {
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l]));
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
|
||||
m.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_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.final_gain)),
|
||||
{ m.x }, { m.final_hidden });
|
||||
m.gather = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ m.final_hidden }, { m.logit_input });
|
||||
m.head_op =
|
||||
rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)),
|
||||
{ m.logit_input }, { m.logits });
|
||||
if (!m.embed || !m.norm || !m.gather || !m.head_op) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the drafter: GlmMtp at Ling's width and checkpoint names around one more MLA layer
|
||||
* with the routed feed-forward. It shares the trunk's buffers, latent cache, embedding and
|
||||
* head. */
|
||||
if (mtp) {
|
||||
const int l = (int)s.n_layer;
|
||||
auto& mt = m.mtp;
|
||||
mt.width = g.n_embd;
|
||||
mt.prefix = nm.ckpt("model.layers.%d", l);
|
||||
mt.layer = l;
|
||||
mt.norm_src = "final_layernorm.weight";
|
||||
const GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
|
||||
RAD_ARCH_TRY(mt.declare_inputs(b, g, tw, false));
|
||||
Layer& d = m.draft;
|
||||
d.mla = true;
|
||||
const char* pre = mt.prefix;
|
||||
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
|
||||
d.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
RAD_ARCH_TRY(d.norm.declare(b, g, d.gain, mt.x, m.act, g.n_embd));
|
||||
RAD_ARCH_TRY(d.attn.declare(b, nm, g, s, l, m.aw, nm.ckpt("%s.attention", pre), m.latent));
|
||||
RAD_ARCH_TRY(mt.declare_join(b, m.y));
|
||||
auto mw = m.mw;
|
||||
mw.x = mt.x;
|
||||
RAD_ARCH_TRY(d.moe.declare(b, nm, g, l, mw, msrc[(size_t)l]));
|
||||
RAD_ARCH_TRY(mt.declare_head(b));
|
||||
m.have_mtp = true;
|
||||
}
|
||||
rad_note(b,
|
||||
"Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts "
|
||||
"top-%lld in %lld groups (%lld kept), MTP %s",
|
||||
world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size),
|
||||
(long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k,
|
||||
(long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ============================== step ============================== */
|
||||
|
||||
/* RADIANCE_LING_DUMP=DIR: the residual stream after each layer's attention and feed-forward, every
|
||||
* row of every step, as `<DIR>/s<step>.t<rows>.l<layer>.<attn|ffn>.r<rank>.bf16` ([rows, n_embd]
|
||||
* bf16). A diagnostic for comparing against a reference model layer by layer; it synchronises the
|
||||
* stream. */
|
||||
static void dump(RadCtx* c, const RadBatch* batch, rad_buf x, int64_t E, int layer,
|
||||
const char* site) {
|
||||
static const char* dir = std::getenv("RADIANCE_LING_DUMP");
|
||||
if (!dir || !*dir) return;
|
||||
const int64_t T = batch->n_tok;
|
||||
void* p = rad_buf_ptr(c, x);
|
||||
if (!p) return;
|
||||
std::vector<uint16_t> h((size_t)(T * E));
|
||||
if (rad_memcpy_async(h.data(), p, T * E * 2, rad_stream(c)) < 0) return;
|
||||
rad_stream_sync(rad_stream(c));
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/s%d.t%lld.l%d.%s.r%d.bf16", dir, batch->step,
|
||||
(long long)T, layer, site, rad_rank(c));
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(h.data(), 2, h.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
/* A draft pass as GLM-5.3's (glm5next.cpp): the head's inputs, its MLA layer over every row (a
|
||||
* history pass fills the draft layer's latent cache for all of them), then on the proposal rows the
|
||||
* residual join, the routed feed-forward and the head. */
|
||||
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
|
||||
if (!m.have_mtp || batch->draft_pass == 1) {
|
||||
rad_step_fail(c, "bailing_hybrid MTP pass is not declared or has invalid round 1");
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
m.mtp.step_inputs(c, batch);
|
||||
auto& l = m.draft;
|
||||
l.norm.step(c, T);
|
||||
l.attn.step(c, batch);
|
||||
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
|
||||
m.mtp.step_join(c, batch, m.y);
|
||||
l.moe.step_rows(c, GlmMtp::head_rows(batch));
|
||||
m.mtp.step_head(c, batch);
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
if (batch->enc) {
|
||||
rad_step_fail(c, "bailing_hybrid serves text");
|
||||
return;
|
||||
}
|
||||
if (batch->draft_pass) {
|
||||
draft_pass(c, m, batch);
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T));
|
||||
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * E, brows(m.x, T), RAD_NONE);
|
||||
for (size_t i = 0; i < m.layers.size(); ++i) {
|
||||
const Layer& l = m.layers[i];
|
||||
l.norm.step(c, T);
|
||||
if (l.mla)
|
||||
l.attn.step(c, batch);
|
||||
else
|
||||
l.kda.step(c, batch);
|
||||
RAD_ISSUE_N(c, l.op_add, T, brows(m.x, T), brows(m.y, T), brows(m.x, T));
|
||||
dump(c, batch, m.x, E, (int)i, "attn");
|
||||
if (l.dense)
|
||||
l.mlp.step(c, batch);
|
||||
else
|
||||
l.moe.step(c, batch);
|
||||
dump(c, batch, m.x, E, (int)i, "ffn");
|
||||
}
|
||||
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.logit_input, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
/* The default draft depth for `--num-speculative-tokens auto`: GlmMtp's operating point, when the
|
||||
* checkpoint carries its one MTP layer. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
|
||||
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace bailing_hybrid */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(bailing_hybrid)
|
||||
RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0",
|
||||
"Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts")
|
||||
#endif
|
||||
+47
-3
@@ -17,6 +17,7 @@
|
||||
#include "rad_yarn.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -123,6 +124,36 @@ inline const char* calib_dir() {
|
||||
return d && *d ? d : nullptr;
|
||||
}
|
||||
|
||||
/* Whether layer `layer` taps (RADIANCE_CALIB_LAYERS: comma-separated layers and "lo-hi" ranges;
|
||||
* unset, every layer). A model whose per-expert Hessians do not fit the host at once (Nemotron-3.5
|
||||
* Bolt's are 169 GiB) calibrates in several runs over disjoint ranges; each run writes only its
|
||||
* layers' files, so the runs share one directory. */
|
||||
inline bool calib_layer_on(int layer) {
|
||||
static const std::vector<std::pair<int, int>> ranges = [] {
|
||||
std::vector<std::pair<int, int>> r;
|
||||
const char* s = std::getenv("RADIANCE_CALIB_LAYERS");
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long lo = std::strtol(s, &e, 10);
|
||||
if (e == s) break;
|
||||
long hi = lo;
|
||||
if (*e == '-') {
|
||||
const char* h = e + 1;
|
||||
hi = std::strtol(h, &e, 10);
|
||||
if (e == h) break;
|
||||
}
|
||||
r.emplace_back((int)lo, (int)hi);
|
||||
s = *e == ',' ? e + 1 : e;
|
||||
if (*s && *s != ',' && !std::isdigit((unsigned char)*s)) break;
|
||||
}
|
||||
return r;
|
||||
}();
|
||||
if (!std::getenv("RADIANCE_CALIB_LAYERS")) return true;
|
||||
for (const auto& r : ranges)
|
||||
if (layer >= r.first && layer <= r.second) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Token count at which the tap dumps and switches itself off (RADIANCE_CALIB_TOKENS, default
|
||||
* 65536). Whether the tap runs at all is calib_dir()'s decision. */
|
||||
inline long long calib_target() {
|
||||
@@ -980,7 +1011,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.plain_norm = c->plain_norm;
|
||||
g.plain_norm = c->plain_norm != 0;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
@@ -1504,7 +1535,12 @@ inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
|
||||
return "draft.transformer_layer_config.";
|
||||
return "draft.";
|
||||
}
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
|
||||
/* `kv_repl_ok`: the drafter block reads its k and v at Geom::kv_off (rad_block_dflash2.h does), so
|
||||
* fewer KV heads than ranks are replicated as geom_from replicates the target's: world a multiple
|
||||
* of the head count, one KV head a rank, `kv_off` its first row in the unsharded k/v projection.
|
||||
* Otherwise such a world is refused, as before. */
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what,
|
||||
bool kv_repl_ok = false) {
|
||||
dg = target;
|
||||
const char* pre = drafter_layer_prefix(meta);
|
||||
char key[160];
|
||||
@@ -1529,7 +1565,15 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
|
||||
/* The target's kv_off is the target's; the drafter's is set here or zero. */
|
||||
dg.kv_off = 0;
|
||||
if (kv_repl_ok && dg.world > dg.n_head_kv_all && dg.world % dg.n_head_kv_all == 0) {
|
||||
dg.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
|
||||
dg.kv_off = (dg.rank / (dg.world / dg.n_head_kv_all)) * dg.head_dim;
|
||||
} else {
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads",
|
||||
&dg.n_head_kv));
|
||||
}
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
|
||||
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
|
||||
if (dvocab != dg.n_vocab_all) {
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
* the GEMM output directly.
|
||||
* - No output gate. The attention output goes straight into the out-projection.
|
||||
*
|
||||
* `rotary_dim` 0 is attention without positions (NoPE, Nemotron-H's attention layers): no `rope`
|
||||
* is declared, and position reaches the model through its recurrent layers alone.
|
||||
*
|
||||
* That allows a fused q|k|v, which the gated block cannot have (its query projection is [q|gate]
|
||||
* interleaved per head). The three weights concatenate along dim 0 into one
|
||||
* [q_dim + 2*kv_dim, n_embd], and `rope` takes that row as is: q heads, then k heads, v untouched
|
||||
@@ -81,19 +84,21 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
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)) {
|
||||
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;
|
||||
}
|
||||
|
||||
/* No KV-head replication: the fused [q|k|v] uses the plain even row shard, so above the KV head
|
||||
* count a rank would read the wrong rows. rad_block_attn_gated_fp8.h is the block that uses
|
||||
* geom_from's `kv_off`. */
|
||||
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);
|
||||
/* Above the KV head count geom_from replicates KV heads (rad_arch.h): each of the fused row's
|
||||
* three parts takes its own span (as gemma4's q|k|v does), q this rank's heads and k and v the
|
||||
* shared head at `kv_off`, where the even shard would hand a rank part of a head. A smaller
|
||||
* attention world (Geom::attn_world) is not served here. */
|
||||
const bool kv_repl = g.world > g.n_head_kv_all;
|
||||
if (kv_repl && g.attn_world != g.world) {
|
||||
fprintf(stderr, "radiance: %s replicates KV heads but declares no attention-zero ranks; "
|
||||
"world_size = %d must be a multiple of n_head_kv = %lld.\n", __func__,
|
||||
g.world, (long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -107,9 +112,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
if (kv_repl) {
|
||||
const int64_t lo[3] = { g.rank * q_dim, g.kv_off, g.kv_off };
|
||||
const int64_t hi[3] = { lo[0] + q_dim, lo[1] + kv_dim, lo[2] + kv_dim };
|
||||
const int64_t tot[3] = { g.n_head_all * g.head_dim, g.n_head_kv_all * g.head_dim,
|
||||
g.n_head_kv_all * g.head_dim };
|
||||
RAD_ARCH_TRY(qkv.span_parts(b, lo, hi, tot, 3));
|
||||
}
|
||||
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
|
||||
{w.qkv}, {w.qkv});
|
||||
if (n_rot > 0)
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, g.n_head_kv, n_rot, mode),
|
||||
{w.qkv}, {w.qkv});
|
||||
|
||||
/* Copies the query out of the fused row: libr4d's paged attention reads `q` as a dense
|
||||
* [total_q, n_head, head_dim] block with no pitch argument (r4d_attn_args.h, fill_paged), so a
|
||||
@@ -179,7 +192,7 @@ inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
qkv.step(c, w.h, w.qkv, T);
|
||||
/* In place over the fused row: rotates n_head query heads, then n_head_kv key heads, and
|
||||
* leaves the value heads alone. */
|
||||
RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
if (op_rope) RAD_ISSUE(c, op_rope, brows(w.qkv, T), rope_posmc(g, batch, T));
|
||||
|
||||
/* k and v are column slices of the fused row, at q_dim and q_dim + kv_dim. */
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
|
||||
@@ -458,8 +458,10 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (g.w_bf16) {
|
||||
RAD_ARCH_TRY(gate_pair(w.gate));
|
||||
} else {
|
||||
if (rad_op_declared(b, "gate_quant_fp8"))
|
||||
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
/* Rotated int8 codes (ActFP8::q8_rot): gate_had_quant_i8g, had_quant_act_i8g's codes. */
|
||||
const char* gq = w.attn.q8_rot ? "gate_had_quant_i8g" : "gate_quant_fp8";
|
||||
if (rad_op_declared(b, gq))
|
||||
op_gq = rw(b, RAD_OP(b, gq,
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
@@ -487,7 +489,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* and quantiser read, so one op merges, gates, rounds and quantises (byte-identical to the
|
||||
* pair). Declared only with a selection: the dense path also uses the prefill kernel, which
|
||||
* has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 &&
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16 && !w.attn.q8_rot &&
|
||||
rad_op_declared(b, "attn_paged_gate_quant")) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
|
||||
+129
-58
@@ -47,6 +47,13 @@
|
||||
* hp = hidden_projection(x) the selector's query, rank 256
|
||||
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
|
||||
*
|
||||
* ============================== LILICORR ==============================
|
||||
*
|
||||
* Config::lili is NVIDIA's LiLiCorr backbone (Nemotron-3.5-Bolt's drafter): the same layers with a
|
||||
* learned sink logit a query head in the attention (attn_paged_sink, `attention_sink_bias`), and no
|
||||
* selector or draft head here. The query pass ends with the gather into `sel_h`; the plugin then
|
||||
* runs rad_block_lilicorr.h's correlator over those rows, which reads the target's own head.
|
||||
*
|
||||
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
|
||||
*
|
||||
* The embedding table and lm_head. The checkpoint (81 tensors) ships neither, and
|
||||
@@ -68,6 +75,8 @@
|
||||
*
|
||||
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
|
||||
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
|
||||
* Fewer KV heads than ranks are replicated (drafter_geom's `kv_repl_ok`): each rank reads its
|
||||
* head's k/v rows at `kv_off` and keeps that head in its cache.
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
|
||||
* context pass every step. Split by rows over the ranks and all-gathered, and
|
||||
@@ -152,6 +161,9 @@ struct Dflash2 {
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
/* LiLiCorr's backbone (the LILICORR section above): sinks, and the head left to the
|
||||
* plugin. sel_rank and sel_topk are then unused. */
|
||||
int lili = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
@@ -294,6 +306,9 @@ struct Dflash2 {
|
||||
int64_t block_lo = 0;
|
||||
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
/* LiLiCorr: the attention with each layer's sinks, a weight, so one op a layer. */
|
||||
rad_weight w_sink[MAX_LAYERS] = {};
|
||||
rad_op op_attn_sink[MAX_LAYERS] = {};
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
* that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm),
|
||||
@@ -353,7 +368,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
(long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || (!cfg.lili && (cfg.sel_rank <= 0 || cfg.sel_topk <= 0)))
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
@@ -401,23 +416,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
}
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
|
||||
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
|
||||
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
|
||||
|
||||
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* The 2-bit draft head, declared as the MTP head's is (rad_block_mtp_fp8.h):
|
||||
* `dflash.draft_head.weight` is the target's lm_head under its own name, quantised by the
|
||||
@@ -427,35 +429,53 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* When sharded, each rank's `row_topk` reports global ids, an all_gather moves R pairs a row,
|
||||
* and `row_topk_merge` reduces them to exactly the unsharded global top-R, ties included
|
||||
* (docs/OPS.md). This runs before the selector, so every rank holds the same candidates for
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16). */
|
||||
* the replicated codebooks. The all_gather is `world * R` pairs a row (2 KiB at R = 16).
|
||||
*
|
||||
* LiLiCorr has neither the selector nor this head (its correlator reads the target's). */
|
||||
enum { DF_W2_GROUP = 128 };
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q
|
||||
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
if (!cfg.lili) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
|
||||
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
|
||||
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
|
||||
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which
|
||||
* gemm_nt_q reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN,
|
||||
dh_split, grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
@@ -492,6 +512,13 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
|
||||
/* Fewer KV heads than ranks (drafter_geom's `kv_repl_ok`): k and v are this rank's
|
||||
* replicated head, rows [kv_off, kv_off + kv_dim) of the unsharded projection, where the
|
||||
* even shard would hand a rank part of a head. q stays an even share of the heads. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
RAD_ARCH_TRY(w_k[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
RAD_ARCH_TRY(w_v[i].span(b, g.kv_off, g.kv_off + kvd));
|
||||
}
|
||||
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
@@ -520,6 +547,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
|
||||
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
/* LiLiCorr's sink logit a query head, split with the heads. */
|
||||
if (cfg.lili) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_sinks", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.attention_sink_bias", ck, i)));
|
||||
w_sink[i] = decl_w(b, nm.f("dflash.blk.%d.attn_sinks", i), RAD_F32, {g.n_head},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i));
|
||||
if (!w_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -529,15 +564,35 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
*
|
||||
* Declared before both kv_stores, which read the resolved `block_size` back with
|
||||
* rad_kv_block_size(); before this declaration it returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), 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});
|
||||
if (!cfg.lili) {
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), 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});
|
||||
} else {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_attn_sink[i] = rw(b, RAD_OP(b, "attn_paged_sink",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block),
|
||||
RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window),
|
||||
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_WEIGHTS(w_sink[i])),
|
||||
{w.q}, {w.attn});
|
||||
if (!op_attn_sink[i]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* Every linear is `fp8a8` (or `mxfp4a8` for a 4-bit recipe; DenseFP8 reads which from the
|
||||
@@ -555,12 +610,15 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
if (fc_rows) {
|
||||
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
|
||||
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance).
|
||||
* The message is a range, as the all-reduce's: a fixed numel follows max_tok, and the
|
||||
* arena's sizing declare (RadBuildCtx::shape_probe) refuses a fixed parameter that
|
||||
* changes with the step size. */
|
||||
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
|
||||
g.n_embd);
|
||||
op_cgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", crows * g.n_embd),
|
||||
RAD_RANGE("numel", g.n_embd, crows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.cpart}, {w.c});
|
||||
@@ -884,6 +942,8 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.sel_h});
|
||||
/* LiLiCorr's head is the plugin's (rad_block_lilicorr.h), over sel_h. */
|
||||
if (cfg.lili) return RAD_OK;
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
@@ -1090,7 +1150,8 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
if (fc_rows) {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.cpart, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cgath, T * g.n_embd, bcol(w.cpart, fc_off, fc_share, T),
|
||||
brows(w.c, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
@@ -1188,13 +1249,22 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
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));
|
||||
if (cfg.lili)
|
||||
RAD_ISSUE_N(c, op_attn_sink[i], batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
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),
|
||||
RAD_W(w_sink[i]), brows(w.attn, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
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_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
@@ -1238,6 +1308,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
|
||||
if (cfg.lili) return; /* the plugin's correlator takes sel_h from here */
|
||||
|
||||
/* `dsum` is group-major, [n_embd/group][ceil(M/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
|
||||
@@ -0,0 +1,958 @@
|
||||
/* rad_block_dspark_bf16.h -- the DSpark drafter over bf16 weights, at the widths a Spark layer
|
||||
* uses: a few plain attention layers that denoise a whole block of masked positions in one pass,
|
||||
* conditioned on the trunk's residual stream at a handful of layers, with a rank-N Markov head
|
||||
* over the target's own output table.
|
||||
*
|
||||
* ============================== WHY A SECOND DSPARK BLOCK ==============================
|
||||
*
|
||||
* rad_block_dspark.h is the same drafter shape for a block-fp8 release: its linears are DenseFP8
|
||||
* behind `quant_act_fp8`, its feed-forward is `silu_mul`, its norms carry q/k gains, and its draft
|
||||
* head is a 2-bit copy of the target's. The published Spark drafts (`dflash` GGUFs, and the HF
|
||||
* Spark drafter releases behind them) ship the other way: bf16 linears, no q/k norms, one sigmoid
|
||||
* gate a head on the attention output, exact-erf GELU, one RMS gain per tap, and a sliding window.
|
||||
* Those are different ops, not different parameters, so this block declares its own graph and
|
||||
* uses an explicit anchor-window attention op and a full-vocabulary Markov selector so neither
|
||||
* semantic distinction is silently folded into the generic per-row window or candidate-lattice ops.
|
||||
*
|
||||
* Nothing here is quantised. The drafter is 624M parameters read whole a draft pass, so bf16 costs
|
||||
* 1.2 GiB of residency and one extra weight pass a step; quantising it is a separate measurement
|
||||
* (it can only move acceptance, since every draft is verified by the target).
|
||||
*
|
||||
* ============================== THE FORWARD PASS ==============================
|
||||
*
|
||||
* The reference is llama.cpp's `llama_model_dflash::graph<false>` (XHToken/llama.cpp
|
||||
* 22c0ae1871b, the branch the Spark draft cards name), which mirrors the HF export:
|
||||
*
|
||||
* tap(l) = rmsnorm(residual after trunk layer l) * fc_norm[l] one gain row per tap
|
||||
* ctx = rmsnorm(fc(concat_l tap(l))) hidden_norm
|
||||
* per draft layer (x5):
|
||||
* h_n = input_layernorm(h)
|
||||
* q,k,v = q_proj/k_proj/v_proj(h_n); k_ctx, v_ctx = k_proj/v_proj(ctx)
|
||||
* rope(q, k); attention over [the layer's context K/V, this block] non-causally,
|
||||
* inside a `window` positions
|
||||
* h += o_proj(sigmoid(g_proj(h)) * attn) one gate a head, no q/k norms
|
||||
* h += mlp(post_attention_layernorm(h)) gelu(gate) * up, then down
|
||||
* logits = target.lm_head(output_norm(h)) + markov_w2 @ markov_w1[prev]
|
||||
*
|
||||
* The two projections of `ctx` are the drafter's own k_proj and v_proj, one pair per layer, and
|
||||
* they run over every committed token; the drafter's layers never see the context rows. That is
|
||||
* the context pass below, and the block above is the query pass -- the same split
|
||||
* rad_block_dspark.h makes, and the same `RAD_DRAFT_BLOCK` drive.
|
||||
*
|
||||
* ============================== THE TAPS ARE NORMED, NOT JUST READ ==================
|
||||
*
|
||||
* `fc_norm` is [n_taps, n_embd]: the residual entering each tap layer is normed with its own gain
|
||||
* before the concatenation, so `fc` sees n_taps unit-scaled streams instead of one sum whose
|
||||
* magnitudes the trunk happens to have. One `rmsnorm` per tap over that tap's column slice of the
|
||||
* tap buffer, into the same slice layout of a normed copy; `fc` then reads one contiguous
|
||||
* [n_taps * n_embd] row.
|
||||
*
|
||||
* ============================== THE SHARED ANCHOR WINDOW ==========================
|
||||
*
|
||||
* The pinned llama.cpp oracle increments the configured history from 512 to 513 and repeats the
|
||||
* anchor row's mask for every row in the denoising block. `attn_paged_anchor_window` implements
|
||||
* that exact predicate: every row sees keys through the end of the staged context whose absolute
|
||||
* position is less than 513 behind the anchor. The query row does not move the lower cutoff. The
|
||||
* same 513-token width is passed to the KV group and scheduler, so rollback, cache recycling and
|
||||
* block staging all retain the exact history the drafter reads.
|
||||
*
|
||||
* ============================== ROW ALIGNMENT ==============================
|
||||
*
|
||||
* Every row predicts, the anchor included (`dflash.sample_from_anchor`, which the GGUF import
|
||||
* refuses when false): row j of [anchor, MASK x (block-1)] proposes the token at the anchor's
|
||||
* position plus j + 1, so `steps()` is `block` and the head runs over all the block's rows. The
|
||||
* core stages the block against `RadDrafterDecl::block` and runs the head over the last `depth`
|
||||
* rows, which covers this and Dflash2's shift-by-one convention (abi/rad_builder.h).
|
||||
*
|
||||
* ============================== THE MARKOV HEAD ==============================
|
||||
*
|
||||
* The draft logits get a learned bigram bias
|
||||
*
|
||||
* score[l, token] = logits[l, token] + markov_w2[token] . markov_w1[prev(l)]
|
||||
* prev(0) = the anchor; prev(l) = the greedy token chosen at l - 1
|
||||
*
|
||||
* `dflash_markov_greedy` scans the full vocabulary at every position and greedily chooses the
|
||||
* largest biased score, following the structure of the pinned reference's serial Markov walk.
|
||||
* Base logits are F32; reduction order and tie behavior can still differ from the reference. It
|
||||
* does not prune to the base head's top K, use a joint-path heap, or apply confidence to logits.
|
||||
*
|
||||
* The confidence head (`conf_proj`, one sigmoid a position predicting acceptance) is imported and
|
||||
* ignored: it exists to let a serving loop cut the block short, this engine's depth is fixed at
|
||||
* declare, and it changes nothing the drafter proposes.
|
||||
*
|
||||
* ============================== PRECISION ==============================
|
||||
*
|
||||
* bf16 for every weight and activation except the residual stream, which is f32 exactly as the
|
||||
* Spark trunk keeps it (rad_block_dspark.h's fp8 graphs fold the residual into the norm; here the
|
||||
* norms read the f32 stream and write bf16, and `add` keeps the sum in f32). The reference runs
|
||||
* bf16 weights against an f32 residual, so rounding the drafter's stream to bf16 would be a third
|
||||
* opinion on every layer's output for no saved bytes worth having at `block` rows.
|
||||
*
|
||||
* ============================== NOT DONE ==============================
|
||||
*
|
||||
* The head and full-vocabulary Markov scan are read replicated, so a vocab-sharded deployment
|
||||
* cannot draft with them. The plugin refuses `world > 1` rather than scoring only one rank's
|
||||
* slice of the vocabulary.
|
||||
*
|
||||
* The drafter's linears are four GEMMs and one attention a layer with no folding: the norms are
|
||||
* plain `rmsnorm`, not a fused norm-add-quantise, because nothing here quantises. At seven rows
|
||||
* a pass the launches, not the bytes, are the cost.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DSPARK_BF16_H
|
||||
#define RAD_BLOCK_DSPARK_BF16_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* The builder refuses a declaration it cannot serve and says why in its own words; this names which
|
||||
* handle did not come back, so that message reads against a line of this file. An op that resolves
|
||||
* to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so
|
||||
* without this a missing kernel surfaces as a bare "invalid argument" at startup. */
|
||||
#define DS_REFUSED(...) ::rad::arch::drafter_refused({ __VA_ARGS__ })
|
||||
inline int drafter_refused(std::initializer_list<const char*> what) {
|
||||
std::string list;
|
||||
for (const char* w : what) { if (!list.empty()) list += ", "; list += w; }
|
||||
std::fprintf(stderr, "DSpark drafter: the builder gave no handle for %s\n", list.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
struct DsparkBF16 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
/* The drafter's config beyond its geometry. Everything here comes from the container's
|
||||
* `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only
|
||||
* moves acceptance, which is the one number the user cannot see. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */
|
||||
int64_t rank = 0; /* markov_rank: the codebooks' width */
|
||||
int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */
|
||||
int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */
|
||||
int causal = 0;
|
||||
int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */
|
||||
int qk_norm = 0; /* per-head q/k gains, and no output gate */
|
||||
int gate = 0; /* one sigmoid gate a head on the attention output */
|
||||
const char* act = "gelu"; /* the feed-forward's activation */
|
||||
int64_t steps() const { return block; } /* every row predicts */
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* ---- the context pass, one row per committed token */
|
||||
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
|
||||
rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */
|
||||
rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */
|
||||
rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] and its V */
|
||||
|
||||
/* ---- the query pass, `block` rows per sequence */
|
||||
rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */
|
||||
rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */
|
||||
rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */
|
||||
rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0;
|
||||
rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */
|
||||
rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */
|
||||
rad_buf gate_up = 0; rad_buf ff = 0;
|
||||
|
||||
/* ---- the head and the walk, one row per draft position */
|
||||
rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */
|
||||
rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */
|
||||
rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */
|
||||
};
|
||||
|
||||
Geom g{}; /* the drafter's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
rad_weight w_fc = 0, w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */
|
||||
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
|
||||
rad_weight w_tok = 0; /* the target's embedding table */
|
||||
rad_weight w_head = 0; /* the target's output table */
|
||||
|
||||
/* ---- per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
rad_weight w_q[MAX_LAYERS] = {}, w_k[MAX_LAYERS] = {}, w_v[MAX_LAYERS] = {}, w_o[MAX_LAYERS] = {};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {};
|
||||
rad_weight w_gu[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
|
||||
/* ---- the context pass */
|
||||
rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */
|
||||
rad_op op_cfc = 0, op_cnorm = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
rad_op op_crope = 0, op_cstore = 0;
|
||||
|
||||
/* ---- the query pass. The weightless ops are declared once and issued per layer; the ones
|
||||
* with weights are per layer, since a weight's prefetch interval and residency class come
|
||||
* from the op that declares it. */
|
||||
rad_op op_embed = 0, op_widen = 0, op_add = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {};
|
||||
rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_widen2 = 0, op_widen3 = 0;
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_sig = 0, op_gate_heads = 0, op_act = 0;
|
||||
|
||||
/* ---- the head and the walk */
|
||||
rad_op op_dlogits = 0, op_markov = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck, const char* ck_head,
|
||||
const Wire& wire);
|
||||
/* The context pass, one row per committed token. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass, the head and the Markov walk, `block` rows per sequence. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
private:
|
||||
int64_t q_dim() const { return g.n_head * g.head_dim; }
|
||||
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int DsparkBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
int base_layer, rad_kvgroup group, rad_weight tok_embd,
|
||||
const char* ck, const char* ck_head, const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !ck_head || !w_tok) return DS_REFUSED("ck", "ck_head", "w_tok");
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter has %lld layers; this block carries at "
|
||||
"most %d\n", (long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank <= 0)
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm && cfg.gate) {
|
||||
fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head "
|
||||
"output gate; no published drafter ships both, and this block would have "
|
||||
"to guess which one the checkpoint trained with\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The full-vocabulary head and Markov scan are read replicated; partial-vocabulary drafting
|
||||
* would need an exact distributed argmax and replicated codebook access. */
|
||||
if (g.world > 1) {
|
||||
fprintf(stderr, "radiance: the bf16 DSpark drafter reads the target's whole output table "
|
||||
"and cannot draft at tp %d; run it at tp 1\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd;
|
||||
crows = g.max_tok;
|
||||
qrows = g.max_seqs * cfg.block;
|
||||
if (qrows > g.max_tok) qrows = g.max_tok;
|
||||
srows = g.max_seqs * cfg.steps(); /* every row predicts */
|
||||
if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t rot = cfg.rot ? cfg.rot : g.head_dim;
|
||||
|
||||
/* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s
|
||||
* parameters are geometry, and only the weights differ per layer. */
|
||||
auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(wt)),
|
||||
{x}, {y});
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.fc.weight"), nm.ckpt("%s.fc.weight", ck)));
|
||||
w_fc = decl_w(b, nm.f("dspark.fc.weight"), RAD_BF16, {E, cfg.n_taps * E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fc || !w_hnorm || !w_norm) return DS_REFUSED("w_fc", "w_hnorm", "w_norm");
|
||||
|
||||
/* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */
|
||||
if (cfg.tap_norm) {
|
||||
const char* src = nm.ckpt("%s.fc_norm.weight", ck);
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i),
|
||||
{ { src, (int)t, 1 } }));
|
||||
w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_fcnorm[i]) return DS_REFUSED("w_fcnorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so
|
||||
* `w2 @ w1[prev]` is `<w1[prev], w2[token]>`. RAD_ACCESS_VOCAB: each walk position reads one
|
||||
* predecessor row and scans every successor row. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
|
||||
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
|
||||
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
|
||||
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_mk1 || !w_mk2) return DS_REFUSED("w_mk1", "w_mk2");
|
||||
|
||||
/* The target's output table under the drafter's own name: one stored tensor, two arch weights,
|
||||
* as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter
|
||||
* reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.head.weight"), ck_head));
|
||||
w_head = decl_w(b, nm.f("dspark.head.weight"), RAD_BF16, {g.n_vocab_all, E},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
if (!w_head) return DS_REFUSED("w_head");
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights
|
||||
*
|
||||
* One name map and one declaration a weight, spelled out: the list is the readable form of
|
||||
* which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a
|
||||
* table would only hide it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup grp = grp_layer(first_layer + i);
|
||||
|
||||
/* A norm gain: f32, read whole, never sharded. */
|
||||
auto norm_w = [&](rad_weight* out, const char* suffix, const char* from,
|
||||
std::initializer_list<int64_t> shape) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from)));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
/* A linear: bf16. More than one source is a concatenation, whose row parts say where each
|
||||
* piece begins (RadWeightDecl::row_parts), so `act_mul` can read [gate | up] as one
|
||||
* weight. */
|
||||
auto lin_w = [&](rad_weight* out, const char* suffix,
|
||||
std::initializer_list<const char*> srcs,
|
||||
std::initializer_list<int64_t> shape,
|
||||
std::initializer_list<int64_t> parts = {}) -> int {
|
||||
const char* name = nm.f("dspark.blk.%d.%s", i, suffix);
|
||||
if (srcs.size() > 1) RAD_ARCH_TRY(map_concat(b, name, srcs));
|
||||
else RAD_ARCH_TRY(map_copy(b, name, *srcs.begin()));
|
||||
*out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp, 0,
|
||||
parts);
|
||||
return *out ? RAD_OK : RAD_E_INVAL;
|
||||
};
|
||||
|
||||
#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i)
|
||||
RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}));
|
||||
RAD_ARCH_TRY(lin_w(&w_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}));
|
||||
RAD_ARCH_TRY(lin_w(&w_gu[i], "ffn_gate_up",
|
||||
{ SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") },
|
||||
{2 * g.n_ff, E}, { g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(lin_w(&w_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") },
|
||||
{E, g.n_ff}));
|
||||
if (cfg.gate)
|
||||
RAD_ARCH_TRY(lin_w(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") },
|
||||
{g.n_head, E}));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight",
|
||||
{g.head_dim}));
|
||||
RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight",
|
||||
{g.head_dim}));
|
||||
}
|
||||
#undef SRC
|
||||
}
|
||||
|
||||
/* Non-causal: every query row sees its whole block and the context the trunk committed
|
||||
* (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the
|
||||
* resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */
|
||||
op_attn = rw(b, RAD_OP(b, cfg.window > 0 ? "attn_paged_anchor_window" : "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), 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", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {w.attn});
|
||||
if (!op_attn) return DS_REFUSED("op_attn");
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* One row per committed token, run once per trunk step: the taps become the drafter's own K
|
||||
* and V. Nothing here is per query row, so its cost follows the trunk's token count, not the
|
||||
* block's. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fcnorm[i])),
|
||||
{w.src}, {w.srcn});
|
||||
if (!op_tapn[i]) return DS_REFUSED("op_tapn[i]");
|
||||
}
|
||||
op_cfc = gemm(crows, E, cfg.n_taps * E, w_fc, w.srcn, w.c);
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.cn});
|
||||
if (!op_cfc || !op_cnorm) return DS_REFUSED("op_cfc", "op_cnorm");
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* One op per weight: an op's declared weight list gives each weight its prefetch interval
|
||||
* and residency class. */
|
||||
op_ck[i] = gemm(crows, kvd, E, w_k[i], w.cn, w.ck);
|
||||
op_cv[i] = gemm(crows, kvd, E, w_v[i], w.cn, w.cv);
|
||||
if (!op_ck[i] || !op_cv[i]) return DS_REFUSED("op_ck[i]", "op_cv[i]");
|
||||
if (cfg.qk_norm) {
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ckn});
|
||||
if (!op_cknorm[i]) return DS_REFUSED("op_cknorm[i]");
|
||||
}
|
||||
}
|
||||
|
||||
/* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is
|
||||
* n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context
|
||||
* row is rotated by its own absolute position, as the reference's single concatenated rope
|
||||
* does. */
|
||||
op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck});
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), 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),
|
||||
{cfg.qk_norm ? w.ckn : w.ck, w.cv}, {});
|
||||
if (!op_crope || !op_cstore) return DS_REFUSED("op_crope", "op_cstore");
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass
|
||||
*
|
||||
* `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the
|
||||
* linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the
|
||||
* activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.h});
|
||||
op_widen = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.x});
|
||||
/* One widen and one add serve both residual sites a layer: same shapes, same buffers. */
|
||||
op_widen2 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.delta});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.delta}, {w.x});
|
||||
if (!op_embed || !op_widen || !op_widen2 || !op_add)
|
||||
return DS_REFUSED("op_embed", "op_widen", "op_widen2", "op_add");
|
||||
|
||||
/* Invariant: the norms are declared where step() issues them. Declaration order is the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that
|
||||
* touch it: each layer's two norms in the loop, the final one after everything the layers
|
||||
* issue. Declared up front, the stream's lifetime would end before the layers and the planner
|
||||
* could overlay a feed-forward temporary on it. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_qp[i] = gemm(qrows, qd, E, w_q[i], w.h, w.q);
|
||||
op_kp[i] = gemm(qrows, kvd, E, w_k[i], w.h, w.k);
|
||||
op_vp[i] = gemm(qrows, kvd, E, w_v[i], w.h, w.v);
|
||||
op_op[i] = gemm(qrows, E, qd, w_o[i], cfg.gate ? w.attng : w.attn, w.h);
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_gu[i] = gemm(qrows, 2 * g.n_ff, E, w_gu[i], w.h, w.gate_up);
|
||||
op_dn[i] = gemm(qrows, E, g.n_ff, w_dn[i], w.ff, w.h);
|
||||
if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] ||
|
||||
!op_gu[i] || !op_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.qk_norm) {
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.qn});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.kn});
|
||||
if (!op_qn[i] || !op_kn[i]) return DS_REFUSED("op_qn[i]", "op_kn[i]");
|
||||
}
|
||||
if (cfg.gate) {
|
||||
op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate);
|
||||
if (!op_gp[i]) return DS_REFUSED("op_gp[i]");
|
||||
}
|
||||
}
|
||||
|
||||
op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q});
|
||||
op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"),
|
||||
{cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k});
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), 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),
|
||||
{cfg.qk_norm ? w.kn : w.k, w.v}, {});
|
||||
/* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */
|
||||
if (cfg.gate) {
|
||||
op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate}, {w.gaten});
|
||||
op_gate_heads = rw(b, RAD_OP(b, "scale_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("act", "none"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn, w.gaten}, {w.attng});
|
||||
if (!op_sig || !op_gate_heads) return DS_REFUSED("op_sig", "op_gate_heads");
|
||||
}
|
||||
/* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark
|
||||
* drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh
|
||||
* approximation and is not what the reference runs. */
|
||||
op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ff});
|
||||
op_outnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm)
|
||||
return DS_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm");
|
||||
|
||||
/* ---------------------------------------------------------------- the head and full-vocabulary walk
|
||||
*
|
||||
* Every row predicts, so the head scores all `steps` rows, anchor included. The row order is
|
||||
* sequence-major, which is the selector's [sequence, position, vocabulary] contract. The
|
||||
* greedy Markov op scans all vocabulary entries at every position and feeds each winning id
|
||||
* into the next position's bigram bias.
|
||||
*/
|
||||
op_dlogits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_head)),
|
||||
{w.h}, {w.dlog});
|
||||
op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs),
|
||||
RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_mk1, w_mk2)),
|
||||
{w.dlog}, {w.best_score, w.best_token, w.tokens});
|
||||
if (!op_dlogits || !op_markov) return DS_REFUSED("op_dlogits", "op_markov");
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void DsparkBF16::context(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int64_t E = g.n_embd;
|
||||
|
||||
/* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the
|
||||
* same slice layout of one row-per-token buffer. */
|
||||
for (int64_t t = 0; t < cfg.n_taps; ++t) {
|
||||
const int i = (int)t;
|
||||
if (!cfg.tap_norm) continue;
|
||||
RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]),
|
||||
bcol(w.srcn, t * E, E, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_cfc, T, cfg.tap_norm ? brows(w.srcn, T) : brows(w.src, T), RAD_W(w_fc),
|
||||
brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(w_k[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(w_v[i]), brows(w.cv, T));
|
||||
if (cfg.qk_norm)
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
|
||||
brows(w.ckn, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void DsparkBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
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 RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
|
||||
/* The block the core staged: the token the sampler just chose, then the mask token in every
|
||||
* unfilled slot. */
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
|
||||
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(w_q[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(w_k[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(w_v[i]), brows(w.v, T));
|
||||
if (cfg.qk_norm) {
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]),
|
||||
brows(w.kn, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos);
|
||||
RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos);
|
||||
/* The block's own K and V go into the cache past `seqused`, which is how every row of the
|
||||
* block attends to every other; the next context pass overwrites them, which is the
|
||||
* reference's `crop(start)`. */
|
||||
RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i),
|
||||
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));
|
||||
if (cfg.gate) {
|
||||
/* One gate a head, applied to that head's whole row of the attention output, before
|
||||
* o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */
|
||||
RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T));
|
||||
RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T));
|
||||
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1);
|
||||
const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head,
|
||||
g.head_dim);
|
||||
RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(w_o[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(w_gu[i]), brows(w.gate_up, T));
|
||||
RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T),
|
||||
bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T));
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(w_dn[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T));
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
/* The predicting rows, named by the scheduler through `out_ids`. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.h, S), RAD_W(w_head), brows(w.dlog, S));
|
||||
RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
|
||||
brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
/* ================================================================== the trunk's side of it
|
||||
*
|
||||
* The taps, and one call a target plugin makes to put a drafter on. Both live here because both
|
||||
* are the drafter's contract with the trunk: which residual streams it reads, where its blocks
|
||||
* live, and how deep a proposal it makes. */
|
||||
|
||||
/* The residual streams a drafter reads, captured as the trunk passes them. */
|
||||
struct DsparkTaps {
|
||||
enum { MAX_TAPS = DsparkBF16::MAX_LAYERS };
|
||||
|
||||
int n = 0;
|
||||
int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */
|
||||
rad_buf src = 0; /* [rows, n * n_embd] f32, one column slice a tap */
|
||||
rad_op op = 0; /* the residual stream, copied into that slice */
|
||||
|
||||
/* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when
|
||||
* the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are
|
||||
* dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */
|
||||
int read(const RadModelMeta* meta, int64_t n_layer) {
|
||||
n = 0;
|
||||
const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr);
|
||||
n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The copy that saves a tap. A drafter reads the trunk's own residual stream, which is f32
|
||||
* here and stays f32: the widening the fp8 graphs do is theirs, not this one's. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual) {
|
||||
if (n <= 0) return RAD_OK;
|
||||
src = decl_b(b, nm.f("draft_src"), RAD_F32, {rows, (int64_t)n * g.n_embd});
|
||||
if (!src) return DS_REFUSED("src");
|
||||
/* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a
|
||||
* tap's slice, and every issue site passes the slice it is writing. */
|
||||
op = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", "f32"), RAD_STR("to", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{residual}, {src});
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the
|
||||
* drafter conditions on every committed token's residual stream. */
|
||||
void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const {
|
||||
if (!op) return;
|
||||
for (int t = 0; t < n; ++t)
|
||||
if (layer[t] == l)
|
||||
RAD_ISSUE(c, op, brows(residual, rows),
|
||||
bcol(src, (int64_t)t * n_embd, n_embd, rows));
|
||||
}
|
||||
};
|
||||
|
||||
/* Put a DSpark drafter on a trunk: its config from the container's `draft.` keys, its own KV
|
||||
* group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute
|
||||
* layer its first block takes, one past the trunk's last.
|
||||
*
|
||||
* Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not
|
||||
* implement is refused by name, because a silently ignored gate, window or block length only moves
|
||||
* acceptance -- the one number a user cannot see in the output.
|
||||
*
|
||||
* The plugin calls it last, after its own head and logits: a drafter's passes run after the whole
|
||||
* trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it
|
||||
* earlier would let a trunk temporary land on the stream the drafter is still reading. */
|
||||
inline int declare_dspark(DsparkBF16* ds, DsparkBF16::Wire* w, rad_kvgroup* kv, RadBuilder* b,
|
||||
Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
const Geom& target, const DsparkTaps& taps, int base_layer,
|
||||
rad_weight tok_embd, const char* ck_head) {
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DSpark"));
|
||||
/* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the
|
||||
* target's -- so a draft that disagrees is a draft for another model, and its `fc` would be
|
||||
* read at a shape it was not trained at. */
|
||||
const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size",
|
||||
rad_meta_geti(meta, "draft.dflash_config.hidden_size",
|
||||
dg.n_embd));
|
||||
if (want_embd != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld "
|
||||
"wide; they are not the same model\n", (long long)want_embd,
|
||||
(long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
DsparkBF16::Config c{};
|
||||
c.n_taps = taps.n;
|
||||
c.rank = rad_meta_geti(meta, "draft.markov_rank", 0);
|
||||
c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0;
|
||||
c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0;
|
||||
c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 0) ? 1 : 0;
|
||||
c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0;
|
||||
const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu");
|
||||
c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu"
|
||||
: (!std::strcmp(act, "silu")) ? "silu" : nullptr;
|
||||
if (!c.act) {
|
||||
fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf "
|
||||
"gelu (what the Spark drafts train with) or silu, and the two are not the "
|
||||
"same function\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid");
|
||||
if (c.gate && std::strcmp(gate_mode, "sigmoid")) {
|
||||
fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block "
|
||||
"applies a sigmoid\n", gate_mode);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* Every row predicts, the anchor included. Without it a block row's worth of proposals is
|
||||
* missing and the head reads rows the drafter never filled. */
|
||||
if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) {
|
||||
fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus "
|
||||
"anchor slot this block has no rows for\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The reference applies the bigram bias to the full vocabulary before each greedy choice. */
|
||||
if (c.rank <= 0 || c.rank % 32 || c.rank > 512) {
|
||||
fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; the walk that applies "
|
||||
"the bigram bias takes a multiple of 32 up to 512\n", (long long)c.rank);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The block is both the number of noise rows and the number of drafts: every row, the anchor
|
||||
* included, predicts the token after it, so the depth is `block_size` rather than the
|
||||
* `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one
|
||||
* block length and has no partial block, so any other depth is refused. */
|
||||
const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (trained < 2) {
|
||||
fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked "
|
||||
"positions it denoises is not a number this engine may choose.\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if ((long long)ctx->max_spec != trained) {
|
||||
fprintf(stderr, "radiance: the drafter was trained at block_size %lld, which is %lld draft "
|
||||
"tokens, and this serve asks for %d. A block-diffusion drafter denoises a "
|
||||
"fixed number of mask positions; run it at %lld.\n",
|
||||
(long long)trained, (long long)trained, ctx->max_spec, (long long)trained);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
c.block = trained;
|
||||
|
||||
/* The reference gives every row of the block the anchor's history. `window` is the configured
|
||||
* number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when
|
||||
* anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */
|
||||
int64_t window = 0;
|
||||
if (rad_meta_geti(meta, "draft.use_sliding_window", 0))
|
||||
window = rad_meta_geti(meta, "draft.sliding_window", 0);
|
||||
if (window < 0 || (window && window < c.block)) {
|
||||
fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token "
|
||||
"block it denoises\n", (long long)window, (long long)c.block);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (window > 0 && window == INT64_MAX) return RAD_E_INVAL;
|
||||
c.window = window > 0 ? window + 1 : 0; /* llama.cpp dflash: n_swa += 1 */
|
||||
const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor",
|
||||
rad_meta_getf(meta,
|
||||
"draft.rope_parameters.partial_rotary_factor", 1.0));
|
||||
const double rot = (double)dg.head_dim * prf;
|
||||
if (!(prf > 0.0) && prf != 0.0) {
|
||||
fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) {
|
||||
fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot,
|
||||
(long long)dg.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim;
|
||||
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv));
|
||||
|
||||
/* Activations: one row per committed token for the context pass, one row per block position
|
||||
* for the query pass. Both are small; the drafter's cost is its weights. */
|
||||
const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim;
|
||||
int64_t qr = dg.max_seqs * c.block;
|
||||
if (qr > dg.max_tok) qr = dg.max_tok;
|
||||
const int64_t sr = dg.max_seqs * c.steps();
|
||||
DsparkBF16::Wire& dw = *w;
|
||||
dw.src = taps.src;
|
||||
dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd});
|
||||
dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd});
|
||||
dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd});
|
||||
if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd});
|
||||
dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd});
|
||||
dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd});
|
||||
dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd});
|
||||
if (c.qk_norm) {
|
||||
dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd});
|
||||
dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd});
|
||||
}
|
||||
dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd});
|
||||
if (c.gate) {
|
||||
dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head});
|
||||
dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd});
|
||||
}
|
||||
dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff});
|
||||
dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff});
|
||||
dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab});
|
||||
const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64;
|
||||
dw.best_score = decl_b(b, nm.f("ds_markov_score"), RAD_F32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32,
|
||||
{dg.max_seqs, n_markov_tiles});
|
||||
/* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's
|
||||
* own walk, never through the sampler's token buffer. */
|
||||
dw.tokens = decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()});
|
||||
if (!dw.srcn || !dw.c || !dw.cn || !dw.ck || !dw.cv ||
|
||||
(c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) ||
|
||||
(c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k ||
|
||||
!dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.dlog ||
|
||||
!dw.best_score || !dw.best_token || !dw.tokens)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", ck_head, dw));
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dspark";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = c.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = c.steps();
|
||||
drf.window = c.window;
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1);
|
||||
if (drf.mask_token < 0)
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1);
|
||||
if (drf.mask_token < 0) {
|
||||
fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled "
|
||||
"block position embeds\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
|
||||
rad_note(b, "DSpark drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured "
|
||||
"history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one "
|
||||
"forward over %lld noise row(s), the anchor included, proposes %lld tokens",
|
||||
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1,
|
||||
(long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim,
|
||||
(long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window,
|
||||
(long long)window, (long long)c.rot, (long long)dg.head_dim, c.act,
|
||||
c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block,
|
||||
(long long)c.steps());
|
||||
rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at "
|
||||
"each draft position; confidence is not applied to logits%s",
|
||||
(long long)c.rank, (long long)dg.n_vocab_all,
|
||||
rad_meta_geti(meta, "draft.has_confidence_head", 0)
|
||||
? " (its reference role is adaptive depth, which this fixed-depth graph does not use)"
|
||||
: "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_DSPARK_BF16_H */
|
||||
@@ -336,12 +336,14 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
|
||||
/* The epilogue's codes for an fp8 or int8 out-projection (int8 when ActFP8::q8_fed; the codes
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent. */
|
||||
* dtype picks the quantiser). A bf16 out-projection reads only `o.x` and these stay absent.
|
||||
* Rotated int8 codes (ActFP8::q8_rot) only the conv fold writes (gdn_conv_recurrent_update_had);
|
||||
* rows this update serves are quantised by q_o. */
|
||||
if (g.plain_norm) {
|
||||
RAD_ARCH_TRY(out.probe(b, nm, g, nm.f("blk.%d.ssm_out", l), { s.out }));
|
||||
o_plain = out.codes_free && out.reads_x;
|
||||
}
|
||||
if (op_recur && w.o.cq() && !o_plain) {
|
||||
if (op_recur && w.o.cq() && !o_plain && !w.o.q8_rot) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
|
||||
}
|
||||
@@ -349,7 +351,7 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* tokens per sequence. Optional (no RAD_ARCH_TRY): without it the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
|
||||
op_cr = rw(b, RAD_OP(b, w.o.q8_rot ? "gdn_conv_recurrent_update_had" : "gdn_conv_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
@@ -530,8 +532,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() && !o_plain ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() && !o_plain ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() && !o_plain && !w.o.q8_rot ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
/* Rotated codes come only from the fold; here the decode rows take the quantiser. */
|
||||
if (w.o.q8_rot && !o_plain) q_o.step(c, T, 0, DT);
|
||||
}
|
||||
|
||||
/* The output a piece at a time where the caller takes the all-reduce that way (ArPieces): the
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/* rad_block_gemma4_unified.h -- the media embedders of Gemma 4 12B ("unified", transformers'
|
||||
* Gemma4UnifiedVisionEmbedder and the audio Gemma4UnifiedMultimodalEmbedder), served by gemma4_bf16.
|
||||
* Neither has an encoder: the language model sees each patch or audio frame after a few norms and
|
||||
* linears.
|
||||
*
|
||||
* image: a patch is 48 x 48 x 3 (3 x 3 of the processor's 16-pixel patches), staged by the core's
|
||||
* Gemma 4 processor as u / 255 in bf16, (y, x, channel); a LayerNorm over the patch, a linear with
|
||||
* a bias, a LayerNorm, plus a learned row for the patch's column and one for its row (the
|
||||
* checkpoint's [npos, 2, width] table, read as its two taps of dimension 1), a LayerNorm, then the
|
||||
* multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. The LayerNorms are
|
||||
* nn.LayerNorm's default eps 1e-5, which no config states. One patch is one row.
|
||||
* audio: a frame is 640 samples at 16 kHz as they are, the last zero-padded, in bf16; an RMS norm
|
||||
* with no gain and a 640 -> n_embd linear. One frame is one row.
|
||||
*
|
||||
* Their rows replace the placeholders' embeddings unscaled, as the vision tower's do. Every rank
|
||||
* runs them whole (RAD_SHARD_NONE). */
|
||||
#ifndef RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
#define RAD_BLOCK_GEMMA4_UNIFIED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Gemma4UnifiedVision {
|
||||
bool on = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = false;
|
||||
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
|
||||
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
|
||||
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
|
||||
rad_op op_ln1 = 0, op_in = 0, op_ln2 = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0;
|
||||
rad_op op_pn = 0, op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_x = 0, b_h = 0, b_px = 0, b_py = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_vision");
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
width = rad_meta_geti(m, "vision_config.mm_embed_dim", 0);
|
||||
npos = rad_meta_geti(m, "vision_config.mm_posemb_size", 0);
|
||||
const int64_t side = rad_meta_geti(m, "vision_config.model_patch_size", 0);
|
||||
const int64_t outd = rad_meta_geti(m, "vision_config.output_proj_dims", width);
|
||||
const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6);
|
||||
if (width <= 0 || npos <= 0 || side <= 0 || outd != width) {
|
||||
fprintf(stderr, "radiance: %s: the container's vision_config is incomplete or not the "
|
||||
"embedder this plugin serves (mm_embed_dim %lld, mm_posemb_size %lld, "
|
||||
"model_patch_size %lld, output_proj_dims %lld)\n", who,
|
||||
(long long)width, (long long)npos, (long long)side, (long long)outd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * side * side;
|
||||
P = ctx->max_enc_patches;
|
||||
const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE;
|
||||
const char* V = "model.vision_embedder";
|
||||
struct { const char* to; const char* from; } cp[] = {
|
||||
{ "v.ln1.weight", "patch_ln1.weight" }, { "v.ln1.bias", "patch_ln1.bias" },
|
||||
{ "v.in.weight", "patch_dense.weight" }, { "v.in.bias", "patch_dense.bias" },
|
||||
{ "v.ln2.weight", "patch_ln2.weight" }, { "v.ln2.bias", "patch_ln2.bias" },
|
||||
{ "v.pn.weight", "pos_norm.weight" }, { "v.pn.bias", "pos_norm.bias" } };
|
||||
for (const auto& e : cp)
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("%s", e.to), nm.ckpt("%s.%s", V, e.from)));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_x.weight"), nm.ckpt("%s.pos_embedding", V), 1, 0));
|
||||
RAD_ARCH_TRY(map_tap(b, nm.f("v.pos_y.weight"), nm.ckpt("%s.pos_embedding", V), 1, 1));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight")));
|
||||
w_ln1 = decl_w(b, nm.f("v.ln1.weight"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_ln1b = decl_w(b, nm.f("v.ln1.bias"), RAD_BF16, {patch_dim}, A, N, grp_model());
|
||||
w_in = decl_w(b, nm.f("v.in.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model());
|
||||
w_inb = decl_w(b, nm.f("v.in.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2 = decl_w(b, nm.f("v.ln2.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_ln2b = decl_w(b, nm.f("v.ln2.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model());
|
||||
w_pn = decl_w(b, nm.f("v.pn.weight"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_pnb = decl_w(b, nm.f("v.pn.bias"), RAD_BF16, {width}, A, N, grp_model());
|
||||
w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model());
|
||||
|
||||
b_n = decl_b(b, nm.f("v.n"), RAD_BF16, {P, patch_dim});
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width});
|
||||
b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width});
|
||||
b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width});
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {P, n_embd});
|
||||
|
||||
auto ln = [&](int64_t n, rad_weight w, rad_weight bias) {
|
||||
return RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto lookup = [&](rad_weight w) {
|
||||
return RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width),
|
||||
RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto add = [&]() {
|
||||
return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
op_ln1 = rw(b, ln(patch_dim, w_ln1, w_ln1b), {}, {b_n});
|
||||
op_in = rw(b, RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width),
|
||||
RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16"),
|
||||
RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(w_in, w_inb)),
|
||||
{b_n}, {b_x});
|
||||
op_ln2 = rw(b, ln(width, w_ln2, w_ln2b), {b_x}, {b_h});
|
||||
op_px = rw(b, lookup(w_px), {}, {b_px});
|
||||
op_py = rw(b, lookup(w_py), {}, {b_py});
|
||||
op_padd = rw(b, add(), {b_px, b_py}, {b_px});
|
||||
op_add = rw(b, add(), {b_h, b_px}, {b_h});
|
||||
op_pn = rw(b, ln(width, w_pn, w_pnb), {b_h}, {b_x});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_x}, {b_h});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", width), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_h}, {b_out});
|
||||
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = 1;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
|
||||
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)side, (long long)side, (long long)patch_dim, (long long)width,
|
||||
(long long)npos, (long long)P, (long long)P, (long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an encoder pass this program's vision embedder cannot serve: none "
|
||||
"declared, or more patches than it was declared for");
|
||||
return;
|
||||
}
|
||||
const int32_t* crd = batch->enc_coord;
|
||||
RAD_ISSUE_N(c, op_ln1, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim), RAD_W(w_ln1),
|
||||
RAD_W(w_ln1b), brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_in, Pn, brows(b_n, Pn), RAD_W(w_in), RAD_W(w_inb), RAD_NONE, brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_ln2, Pn, brows(b_x, Pn), RAD_W(w_ln2), RAD_W(w_ln2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_h, Pn), brows(b_px, Pn), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_pn, Pn, brows(b_h, Pn), RAD_W(w_pn), RAD_W(w_pnb), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_norm, Pn, brows(b_x, Pn), RAD_NONE, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_h, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
struct Gemma4UnifiedAudio {
|
||||
bool on = false;
|
||||
int64_t P = 0, frame = 0, n_embd = 0;
|
||||
rad_weight w_proj = 0;
|
||||
rad_op op_norm = 0, op_out = 0;
|
||||
rad_buf b_n = 0, b_out = 0;
|
||||
|
||||
static bool present(const RadModelMeta* m) {
|
||||
const char* t = rad_meta_gets(m, "audio_config.model_type", "");
|
||||
return t && !std::strcmp(t, "gemma4_unified_audio");
|
||||
}
|
||||
/* Samples a frame: the extractor's audio_samples_per_token, else the embedder's input width. */
|
||||
static int64_t frame_for(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "processor.feature_extractor.audio_samples_per_token",
|
||||
rad_meta_geti(m, "audio_config.audio_embed_dim", 0));
|
||||
}
|
||||
/* The longest clip in frames: processor_config.json's audio_seq_length, else 30 s. */
|
||||
static int64_t frames_for(const RadModelMeta* m) {
|
||||
const int64_t f = frame_for(m);
|
||||
const int64_t rate = rad_meta_geti(m, "processor.feature_extractor.sampling_rate", 16000);
|
||||
if (f <= 0 || rate <= 0) return 0;
|
||||
return rad_meta_geti(m, "processor.audio_seq_length", (30 * rate + f - 1) / f);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, const char* who) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_audio_frames <= 0) return RAD_OK;
|
||||
frame = frame_for(m);
|
||||
const int64_t width = rad_meta_geti(m, "audio_config.audio_embed_dim", 0);
|
||||
const double eps = rad_meta_getf(m, "audio_config.rms_norm_eps", 1e-6);
|
||||
if (frame <= 0 || width != frame) {
|
||||
fprintf(stderr, "radiance: %s: the container's audio frame (%lld samples) is not the "
|
||||
"embedder's input (audio_embed_dim %lld)\n", who, (long long)frame,
|
||||
(long long)width);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
n_embd = model_embd;
|
||||
P = ctx->max_audio_frames;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("a.embed.weight"), nm.ckpt("model.embed_audio.embedding_projection.weight")));
|
||||
w_proj = decl_w(b, nm.f("a.embed.weight"), RAD_BF16, {n_embd, frame}, RAD_ACCESS_PER_REQUEST,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
b_n = decl_b(b, nm.f("a.n"), RAD_BF16, {P, frame});
|
||||
b_out = decl_b(b, nm.f("a.out"), RAD_BF16, {P, n_embd});
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", frame),
|
||||
RAD_F64("eps", eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {b_n});
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", n_embd),
|
||||
RAD_INT("K", frame), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_proj)),
|
||||
{b_n}, {b_out});
|
||||
RadEncoderDecl e{};
|
||||
e.name = "audio";
|
||||
e.modalities = RAD_MM_AUDIO;
|
||||
e.patch_dim = frame;
|
||||
e.merge = 1;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "audio embedder (no encoder): frames of %lld samples -> %lld; %lld frames a pass",
|
||||
(long long)frame, (long long)n_embd, (long long)P);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch;
|
||||
if (!on || Pn <= 0 || Pn > P || batch->enc_n_seg <= 0) {
|
||||
rad_step_fail(c, "an audio pass this program's audio embedder cannot serve: none "
|
||||
"declared, or more frames than it was declared for");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_norm, Pn, praw2(batch->enc_pixels, RAD_BF16, Pn, frame), RAD_NONE,
|
||||
brows(b_n, Pn));
|
||||
RAD_ISSUE_N(c, op_out, Pn, brows(b_n, Pn), RAD_W(w_proj), brows(b_out, Pn));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GEMMA4_UNIFIED_H */
|
||||
@@ -56,6 +56,9 @@ struct Gemma4Vision {
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false, clip = false;
|
||||
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
|
||||
* plugin sets it before declare. */
|
||||
bool bidirectional = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
@@ -321,6 +324,7 @@ struct Gemma4Vision {
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.bidirectional = bidirectional ? 1 : 0;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
|
||||
|
||||
@@ -27,6 +27,9 @@ struct DsaCache {
|
||||
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
|
||||
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
|
||||
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
|
||||
/* A taking-all step's zero scores, [max_tok, topk + 1]: such a step does not split, and
|
||||
* the score plane holds only a run of rows when the step may. */
|
||||
rad_buf unscored = 0;
|
||||
/* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */
|
||||
rad_buf cu_part = 0, sel_part = 0, len_part = 0;
|
||||
};
|
||||
@@ -44,6 +47,7 @@ struct DsaCache {
|
||||
rad_kvgroup index = 0, tail = 0, attention = 0;
|
||||
rad_weight ape = 0;
|
||||
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
|
||||
rad_op op_unscored = 0, op_select_all = 0;
|
||||
rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
@@ -112,6 +116,15 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.kg }, {});
|
||||
/* A step whose every row reaches topk or fewer blocks selects them all (takes_all), and
|
||||
* qsa_select takes any finite scores in block order then: zeros serve as well as the
|
||||
* scorer's. The fill spans topk + 1 columns, at least the live reach of such a step. */
|
||||
op_unscored = rw(b,
|
||||
RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("n", unscored_cols()), RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { w.unscored });
|
||||
op_score = rw(b,
|
||||
RAD_OP(b, "dsa_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
|
||||
@@ -139,6 +152,14 @@ struct DsaCache {
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
|
||||
op_select_all = rw(b,
|
||||
RAD_OP(b, "qsa_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("blocks", unscored_cols()),
|
||||
RAD_INT("topk", 512), RAD_INT("ratio", 4),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.unscored, w.nc }, { w.selected, w.nsel, w.length });
|
||||
if (split) {
|
||||
op_select_part = rw(
|
||||
b,
|
||||
@@ -165,8 +186,12 @@ struct DsaCache {
|
||||
if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL;
|
||||
return op_query && op_work && op_tail && op_unscored && op_score && op_select &&
|
||||
op_select_all
|
||||
? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
int64_t unscored_cols() const { return c.topk + 1 < c.blocks ? c.topk + 1 : c.blocks; }
|
||||
/* The columns a step scores: the live reach the batch bounds on the host. */
|
||||
int64_t live_blocks(const RadBatch* batch) const {
|
||||
const auto* ib = kv_batch(batch, index);
|
||||
@@ -179,13 +204,19 @@ struct DsaCache {
|
||||
}
|
||||
/* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by
|
||||
* the core), so every rank takes the same path and a recorded decode pass changes it only when
|
||||
* that bound moves. */
|
||||
* that bound moves. A step that takes all its blocks never splits: with nothing to score, every
|
||||
* rank selects the whole step itself, and the gathers have nothing to save. */
|
||||
bool splits(const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
return op_score_part && (GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows &&
|
||||
T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
return op_score_part && live_blocks(batch) > c.topk &&
|
||||
(GlmTp::splits(T, g.world) ||
|
||||
(T >= GlmTp::kSplitWorkRows && T * live_blocks(batch) >= GlmTp::kSplitWork));
|
||||
}
|
||||
/* Every row's history fits the selection, so the query side (projection, head gates,
|
||||
* quantiser, scorer) has nothing to decide: the selected table is every live block in order,
|
||||
* bit for bit what scoring would select. Read from the same host bound as splits(), so every
|
||||
* rank agrees. */
|
||||
bool takes_all(const RadBatch* batch) const { return live_blocks(batch) <= c.topk; }
|
||||
/* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of).
|
||||
* A rank whose run lies wholly past a small step runs the step's first R rows instead: no
|
||||
* sequence holds its run, so its scores are -inf, and its answers land past T. The caller's
|
||||
@@ -210,11 +241,13 @@ struct DsaCache {
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t work = (T + 3) / 4 + S,
|
||||
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
|
||||
const bool all = takes_all(batch);
|
||||
int64_t q0 = 0, qn = T;
|
||||
query_rows(batch, &q0, &qn);
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.codes, q0 * 32, qn * 32, 128),
|
||||
brow_slice(w.scales, q0 * 32, qn * 32, 1));
|
||||
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
|
||||
praw2(tb->state_index, RAD_I32, S, pitch),
|
||||
@@ -232,6 +265,16 @@ struct DsaCache {
|
||||
step_split(ctx, batch, live);
|
||||
return;
|
||||
}
|
||||
if (all) {
|
||||
const int64_t U = unscored_cols();
|
||||
RAD_ISSUE_N(ctx, op_unscored, T, brows(w.unscored, T));
|
||||
RAD_ISSUE_N(ctx, op_select_all, T, bcol_at(w.unscored, 0, U, 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));
|
||||
return;
|
||||
}
|
||||
// dsa_score declares ten operands, cu_part the optional tenth; the engine counts them.
|
||||
RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32),
|
||||
brows(w.gate, T), kv_cache(index, layer), RAD_NONE,
|
||||
@@ -348,23 +391,29 @@ struct GlmIndexer {
|
||||
};
|
||||
int64_t r0 = 0, rows = T;
|
||||
cache.query_rows(batch, &r0, &rows);
|
||||
/* The key side runs on every step, since the index cache must stay current; the query
|
||||
* side only where the selection is a choice (DsaCache::takes_all). */
|
||||
const bool all = cache.takes_all(batch);
|
||||
/* Every output row of these ops is independent of the others and of how many there are,
|
||||
* except the bf16 projection's at 64 rows and under, a band whose split count a tuned
|
||||
* configuration may set: it stays on the step's rows unless every run is wider. */
|
||||
const bool runs = cache.splits(batch);
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
if (!all) {
|
||||
if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64)
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows);
|
||||
else
|
||||
query.step(ctx, act(w.q_low), w.q_wide, T);
|
||||
RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096),
|
||||
brow_slice(w.cache.query, r0 * 32, rows * 32, 128));
|
||||
}
|
||||
key_gate.step(ctx, act(w.input), w.kg_raw, T);
|
||||
RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias),
|
||||
bcol(w.cache.kg, 0, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T),
|
||||
bcol(w.cache.kg, 128, 128, T));
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight),
|
||||
brow_slice(w.cache.gate, r0, rows, 32));
|
||||
if (!all)
|
||||
RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096),
|
||||
RAD_W(head_weight), brow_slice(w.cache.gate, r0, rows, 32));
|
||||
cache.step(ctx, batch);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include "rad_glm_tp.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -27,6 +28,25 @@ struct MlaLatent {
|
||||
struct Config {
|
||||
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
|
||||
};
|
||||
/* The attention over the latent cache, `rows` rows of `heads` heads. The cache is Geom::kv_dtype
|
||||
* (bf16, or fp8_e4m3 under --kv-cache-dtype fp8); `kv_dtype` is stated only for a cache that is
|
||||
* not bf16, so a bf16 build declares the op it always did. */
|
||||
static rad_op attn_op(RadBuilder* b, const Geom& g, int64_t rows, int64_t heads,
|
||||
int64_t blocks, double scale) {
|
||||
if (g.kv_dtype && std::strcmp(g.kv_dtype, "bf16"))
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", heads), RAD_INT("blocks", blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", scale),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
}
|
||||
struct Wire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
|
||||
/* qsa_select's entry count (selected_count), one int a row: the streamed resolve's `nsel`.
|
||||
@@ -68,16 +88,10 @@ struct MlaLatent {
|
||||
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 });
|
||||
op_attn = rw(b,
|
||||
attn_op(b, g, g.max_tok, c.heads, c.blocks,
|
||||
1.0 / std::sqrt((double)c.head_dim)),
|
||||
{ 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,
|
||||
@@ -172,12 +186,13 @@ struct GlmMla {
|
||||
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
|
||||
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, w.core.q));
|
||||
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
|
||||
/* Cache stores contiguous halves of the normalized latent, with no duplicated K/V. An E4M3
|
||||
* cache (Geom::kv_dtype) stores at kv_store's default descale of 1, which mla_attn reads. */
|
||||
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_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
if (!op_store) return RAD_E_INVAL;
|
||||
@@ -200,7 +215,7 @@ struct GlmMla {
|
||||
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_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.latent }, {});
|
||||
/* Issued in finish, after this layer's indexer selects and before the attention reads
|
||||
@@ -239,15 +254,8 @@ struct GlmMla {
|
||||
{ in }, { out });
|
||||
};
|
||||
op_rows_absorb = project("absorb", r.q, r.q_latent);
|
||||
op_rows_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_attn = rw(b, MlaLatent::attn_op(b, g, R, 64, core.c.blocks, 1.0 / std::sqrt(256.0)),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
|
||||
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
|
||||
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
|
||||
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
|
||||
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
|
||||
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass.
|
||||
*
|
||||
* The same head serves another DeepSeek-style drafter by its checkpoint layout, set before
|
||||
* declare_inputs: the residual width, the layer's checkpoint prefix and index, and the name of the
|
||||
* head's final norm (Ling-3.0: 2560, `model.layers.42`, 42, `final_layernorm.weight`). */
|
||||
#ifndef RAD_BLOCK_GLM_MTP_H
|
||||
#define RAD_BLOCK_GLM_MTP_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -31,6 +35,10 @@ struct GlmMtp {
|
||||
rad_weight token = 0, head = 0;
|
||||
};
|
||||
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
|
||||
int64_t width = 4096;
|
||||
const char* prefix = "model.language_model.layers.45";
|
||||
int layer = 45;
|
||||
const char* norm_src = "shared_head.norm.weight";
|
||||
Names nm{ "mtp" };
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
@@ -50,47 +58,48 @@ struct GlmMtp {
|
||||
w = wire;
|
||||
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
|
||||
return RAD_E_INVAL;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
|
||||
const char* pre = "model.language_model.layers.45";
|
||||
const int64_t E = width;
|
||||
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, E });
|
||||
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, E }, RAD_BUF_PERSIST);
|
||||
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, E });
|
||||
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 2 * E });
|
||||
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, E });
|
||||
const char* pre = prefix;
|
||||
auto gain = [&](const char* n, const char* src) {
|
||||
const char* name = nm.f("%s", n);
|
||||
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
|
||||
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(45));
|
||||
return decl_w(b, name, RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(layer));
|
||||
};
|
||||
en = gain("enorm.weight", "enorm.weight");
|
||||
hn = gain("hnorm.weight", "hnorm.weight");
|
||||
norm = gain("output_norm.weight", "shared_head.norm.weight");
|
||||
norm = gain("output_norm.weight", norm_src);
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(45));
|
||||
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { E, 2 * E }, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_layer(layer));
|
||||
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
|
||||
return RAD_E_INVAL;
|
||||
op_prev = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.final_hidden }, { hidden });
|
||||
op_embed = rw(b,
|
||||
RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w.token)),
|
||||
{}, { embedding });
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, E, embedding));
|
||||
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
|
||||
op_en = rmsnorm(b, en, embedding, concat);
|
||||
op_hn = rmsnorm(b, hn, hidden, concat);
|
||||
op_eh = rw(b,
|
||||
RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
|
||||
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", E),
|
||||
RAD_INT("K", 2 * E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(eh)),
|
||||
{ concat }, { x });
|
||||
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
|
||||
@@ -102,14 +111,14 @@ struct GlmMtp {
|
||||
int declare_join(RadBuilder* b, rad_buf y) {
|
||||
op_residual = rw(b,
|
||||
RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x, y }, { x });
|
||||
// All history rows fill the draft cache; only proposal rows need its FFN.
|
||||
op_select = rw(b,
|
||||
RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ x }, { hidden });
|
||||
@@ -124,7 +133,7 @@ struct GlmMtp {
|
||||
op_head = rw(b,
|
||||
RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w.head)),
|
||||
{ hidden }, { w.logits });
|
||||
@@ -150,9 +159,9 @@ struct GlmMtp {
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
|
||||
brows(embedding, T));
|
||||
mrows.step(c, batch, embedding, T);
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T));
|
||||
if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * width, brows(embedding, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, width, T));
|
||||
RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, width, width, T));
|
||||
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
|
||||
}
|
||||
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
|
||||
@@ -175,7 +184,7 @@ private:
|
||||
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain)),
|
||||
{ in }, { out });
|
||||
@@ -183,7 +192,7 @@ private:
|
||||
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
|
||||
return rw(b,
|
||||
RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", width),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ in }, { out });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
|
||||
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. With `groups`
|
||||
* above 1 the selection is group-limited (router_sigmoid_group_topk, Ling-3.0's 8 groups, 4 kept). */
|
||||
#ifndef RAD_BLOCK_GLM_ROUTER_H
|
||||
#define RAD_BLOCK_GLM_ROUTER_H
|
||||
#include "rad_glm_tp.h"
|
||||
@@ -9,7 +10,7 @@ namespace rad {
|
||||
namespace arch {
|
||||
struct GlmRouter {
|
||||
struct Config {
|
||||
int64_t experts = 288, top_k = 8, rows = 32;
|
||||
int64_t experts = 288, top_k = 8, rows = 32, groups = 1, topk_groups = 1;
|
||||
int norm = 1;
|
||||
double route_scale = 2.5;
|
||||
};
|
||||
@@ -33,8 +34,9 @@ struct GlmRouter {
|
||||
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)
|
||||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 ||
|
||||
c.groups < 1 || c.experts % c.groups || c.topk_groups < 1 || c.topk_groups > c.groups ||
|
||||
!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));
|
||||
@@ -52,14 +54,25 @@ struct GlmRouter {
|
||||
{ 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 });
|
||||
if (c.groups > 1)
|
||||
op_select =
|
||||
rw(b,
|
||||
RAD_OP(b, "router_sigmoid_group_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("n_group", c.groups),
|
||||
RAD_INT("topk_group", c.topk_groups), 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 });
|
||||
else
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
/* rad_block_lilicorr.h -- LiLiCorr's head: the candidate correlator after a DFlash2 backbone.
|
||||
*
|
||||
* NVIDIA's drafter for Nemotron-3.5-Bolt (vLLM's model_executor/models/lilicorr.py). The backbone is
|
||||
* rad_block_dflash2.h's, with attention sinks (Dflash2::Config::lili). Its final hidden states at
|
||||
* the block's draft rows go here instead of to DFlash2's selector:
|
||||
*
|
||||
* candidates each draft position's top-k from the target's own lm_head (log-softmax values,
|
||||
* vocab-parallel: each rank's shard, all-gathered, merged)
|
||||
* lattice steps x k rows a sequence, row s * k + j:
|
||||
* token_proj(embed(cand)) + pass_hidden_proj(h_s)
|
||||
* + feature_mlp(layernorm(five rank features)) + slot[s] + rank[j]
|
||||
* 2 layers rmsnorm, attention over the lattice with a learned slot bias (lili_attn), the
|
||||
* in/out projections; rmsnorm, silu MLP with biases; residuals
|
||||
* factor x = output_norm(lattice), a = anchor_norm(context_proj(the anchor's context row))
|
||||
* f = silu(W [x | a | x * a] + b), [out | in] = edge heads of f
|
||||
* walk normalised dot products, start from the anchor's own outgoing head, greedy
|
||||
* (lili_walk)
|
||||
*
|
||||
* The anchor's context row is hidden_norm(fc(taps)) at the last committed position, which the
|
||||
* context pass left in Dflash2's `c` (RadBatch::anchor_rows names the row). The head reads the
|
||||
* target's embedding and lm_head, and its own 25 linears are bf16: ModelOpt ships them NVFP4,
|
||||
* which no kernel serves, and the recipe decodes them (`cast dtype=bf16`).
|
||||
*
|
||||
* Every rank computes the whole lattice (vLLM: "candidate IDs and embeddings are replicated across
|
||||
* TP ranks"); only the head's logits and the embedding lookup are per rank, with the merge in
|
||||
* lili_cand and an exact all-reduce after the lookup.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_LILICORR_H
|
||||
#define RAD_BLOCK_LILICORR_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct LiliCorr {
|
||||
enum { MAX_LAYERS = 4 };
|
||||
|
||||
struct Config {
|
||||
int64_t steps = 0; /* draft positions a sequence: the block less the anchor */
|
||||
int64_t k = 8; /* candidates a position (lilicorr_candidate_topk) */
|
||||
int64_t hs = 1024; /* the lattice's width (lilicorr_hidden_size) */
|
||||
int64_t n_head = 8;
|
||||
int64_t mlp = 2048; /* hs * lilicorr_mlp_ratio */
|
||||
int64_t fdim = 1024; /* lilicorr_factor_dim */
|
||||
int64_t n_layer = 2;
|
||||
double eps = 1e-6; /* rms_norm_eps, the lattice's RMS norms */
|
||||
double vec_eps = 1e-4; /* lilicorr_vector_eps, F.normalize's floor */
|
||||
double scale = 8.0; /* lilicorr_logit_scale */
|
||||
};
|
||||
|
||||
/* row_k: the pairs a rank's logprob row carries, k rounded up so 2 + 2 row_k floats are whole
|
||||
* 16-byte words (the all-gather's unit): 9 for k = 8. */
|
||||
static int64_t row_k(int64_t k) { return (k % 2) ? k : k + 1; }
|
||||
|
||||
struct Wire {
|
||||
/* Dflash2's */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the drafter's final hidden states, draft rows */
|
||||
rad_buf c = 0; /* [max_tok, n_embd] hidden_norm(fc(taps)), the context pass's rows */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32, the proposal */
|
||||
/* the head's own */
|
||||
rad_buf logits = 0; /* [srows, n_vocab] f32, this rank's shard */
|
||||
rad_buf stats = 0; /* [srows, 2 + 2 row_k] f32 */
|
||||
rad_buf sgath = 0; /* [srows, world * (2 + 2 row_k)] f32, world > 1 */
|
||||
rad_buf pas = 0; /* [srows, hs] */
|
||||
rad_buf cand = 0; /* [srows * k] i32 */
|
||||
rad_buf feat = 0; /* [lrows, hs] */
|
||||
rad_buf hh = 0; /* [lrows, hs] the lattice's residual stream; starts as lili_cand's base */
|
||||
rad_buf emb = 0; /* [lrows, n_embd] the candidates' embeddings */
|
||||
rad_buf y = 0; /* [lrows, hs] */
|
||||
rad_buf qkv = 0; /* [lrows, 3 hs] */
|
||||
rad_buf att = 0; /* [lrows, hs] */
|
||||
rad_buf up = 0; /* [lrows, mlp] */
|
||||
rad_buf ups = 0; /* [lrows, mlp] */
|
||||
rad_buf cat = 0; /* [lrows, 3 hs] */
|
||||
rad_buf fh = 0; /* [lrows, hs] */
|
||||
rad_buf fhs = 0; /* [lrows, hs] */
|
||||
rad_buf edges = 0; /* [lrows, 2 fdim] */
|
||||
rad_buf anc = 0; /* [max_seqs, n_embd] */
|
||||
rad_buf ast = 0; /* [max_seqs, hs] */
|
||||
rad_buf an = 0; /* [max_seqs, hs] */
|
||||
rad_buf aout = 0; /* [max_seqs, fdim] */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int64_t srows = 0, lrows = 0, rk = 0;
|
||||
|
||||
rad_weight w_lm = 0, w_tok = 0; /* the target's */
|
||||
rad_weight w_tokp = 0, b_tokp = 0, w_pass = 0, b_pass = 0, w_ctx = 0, b_ctx = 0;
|
||||
rad_weight w_fdn = 0, b_fdn = 0, ln_w = 0, ln_b = 0, up_w = 0, up_b = 0, w_slot = 0, w_rank = 0;
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_in[MAX_LAYERS] = {}, b_in[MAX_LAYERS] = {};
|
||||
rad_weight w_out[MAX_LAYERS] = {}, b_out[MAX_LAYERS] = {}, w_mnorm[MAX_LAYERS] = {};
|
||||
rad_weight w_up[MAX_LAYERS] = {}, b_up[MAX_LAYERS] = {}, w_dn[MAX_LAYERS] = {};
|
||||
rad_weight b_dn[MAX_LAYERS] = {};
|
||||
rad_weight w_rel = 0, w_same = 0, w_onorm = 0, w_annorm = 0;
|
||||
rad_weight w_fac = 0, b_fac = 0, w_edge = 0, b_edge = 0, w_aout = 0, b_aout = 0;
|
||||
|
||||
rad_op op_logits = 0, op_stats = 0, op_sgath = 0, op_pas = 0, op_cand = 0;
|
||||
rad_op op_emb = 0, op_emb_ar = 0, op_tokp = 0, op_fdn = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_in[MAX_LAYERS] = {}, op_attn = 0;
|
||||
rad_op op_out[MAX_LAYERS] = {}, op_mnorm[MAX_LAYERS] = {}, op_up[MAX_LAYERS] = {};
|
||||
rad_op op_dn[MAX_LAYERS] = {}, op_silu_up = 0;
|
||||
rad_op op_onorm = 0, op_anc = 0, op_ctx = 0, op_annorm = 0, op_factor = 0, op_fac = 0;
|
||||
rad_op op_silu_f = 0, op_edge = 0, op_aout = 0, op_walk = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, rad_weight lm_head,
|
||||
rad_weight tok_embd, const char* ck, const Wire& wire);
|
||||
/* After Dflash2::step, on the same query batch: `sel_h` holds the draft rows. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int LiliCorr::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
rad_weight lm_head, rad_weight tok_embd, const char* ck,
|
||||
const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; w_lm = lm_head; w_tok = tok_embd;
|
||||
if (!w_lm || !w_tok || !ck || cfg.steps < 1 || cfg.k < 2 || cfg.n_layer < 1 ||
|
||||
cfg.n_layer > MAX_LAYERS || cfg.hs % cfg.n_head)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t K = cfg.k, S = cfg.steps, hs = cfg.hs, fd = cfg.fdim, E = g.n_embd;
|
||||
srows = g.max_seqs * S;
|
||||
lrows = srows * K;
|
||||
rk = row_k(K);
|
||||
const int ACC = RAD_ACCESS_PER_TOKEN;
|
||||
const RadWeightGroup grp = grp_model();
|
||||
|
||||
/* The head's weights, all replicated. Linears and tables bf16, biases, norms and the
|
||||
* feature layer f32. */
|
||||
auto wt = [&](const char* dn, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shp) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, grp);
|
||||
};
|
||||
const char* L = nm.ckpt("%s.lilicorr", ck);
|
||||
auto src = [&](const char* tail) { return nm.ckpt("%s.%s", L, tail); };
|
||||
w_tokp = wt(nm.f("dflash.lili.token_proj.weight"), src("token_proj.weight"), RAD_BF16, { hs, E });
|
||||
b_tokp = wt(nm.f("dflash.lili.token_proj.bias"), src("token_proj.bias"), RAD_F32, { hs });
|
||||
w_pass = wt(nm.f("dflash.lili.pass_proj.weight"), src("pass_hidden_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_pass = wt(nm.f("dflash.lili.pass_proj.bias"), src("pass_hidden_proj.bias"), RAD_F32, { hs });
|
||||
w_ctx = wt(nm.f("dflash.lili.context_proj.weight"), src("context_proj.weight"), RAD_BF16,
|
||||
{ hs, E });
|
||||
b_ctx = wt(nm.f("dflash.lili.context_proj.bias"), src("context_proj.bias"), RAD_F32, { hs });
|
||||
ln_w = wt(nm.f("dflash.lili.feature_norm.weight"), src("feature_norm.weight"), RAD_F32, { 5 });
|
||||
ln_b = wt(nm.f("dflash.lili.feature_norm.bias"), src("feature_norm.bias"), RAD_F32, { 5 });
|
||||
up_w = wt(nm.f("dflash.lili.feature_up.weight"), src("feature_mlp.up_proj.weight"), RAD_F32,
|
||||
{ hs, 5 });
|
||||
up_b = wt(nm.f("dflash.lili.feature_up.bias"), src("feature_mlp.up_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
w_fdn = wt(nm.f("dflash.lili.feature_down.weight"), src("feature_mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_fdn = wt(nm.f("dflash.lili.feature_down.bias"), src("feature_mlp.down_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [1, 1, steps, 1, hs] and [1, 1, 1, k, hs], read as tables (a reshape of one whole plane). */
|
||||
w_slot = wt(nm.f("dflash.lili.slot_embedding"), src("slot_embedding"), RAD_BF16, { S, hs });
|
||||
w_rank = wt(nm.f("dflash.lili.rank_embedding"), src("rank_embedding"), RAD_BF16, { K, hs });
|
||||
w_rel = wt(nm.f("dflash.lili.relative_slot_bias"), src("relative_slot_bias"), RAD_F32,
|
||||
{ cfg.n_head, 2 * (S + 1) - 1 });
|
||||
w_same = wt(nm.f("dflash.lili.same_slot_bias"), src("same_slot_bias"), RAD_F32, { cfg.n_head });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
auto ls = [&](const char* tail) { return nm.ckpt("%s.layers.%d.%s", L, i, tail); };
|
||||
w_anorm[i] = wt(nm.f("dflash.lili.blk.%d.attn_norm.weight", i), ls("attn_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.weight", i), ls("attn.in_proj_weight"),
|
||||
RAD_BF16, { 3 * hs, hs });
|
||||
b_in[i] = wt(nm.f("dflash.lili.blk.%d.attn_in.bias", i), ls("attn.in_proj_bias"), RAD_F32,
|
||||
{ 3 * hs });
|
||||
w_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.weight", i), ls("attn.out_proj.weight"),
|
||||
RAD_BF16, { hs, hs });
|
||||
b_out[i] = wt(nm.f("dflash.lili.blk.%d.attn_out.bias", i), ls("attn.out_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
w_mnorm[i] = wt(nm.f("dflash.lili.blk.%d.mlp_norm.weight", i), ls("mlp_norm.weight"),
|
||||
RAD_F32, { hs });
|
||||
w_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.weight", i), ls("mlp.up_proj.weight"),
|
||||
RAD_BF16, { cfg.mlp, hs });
|
||||
b_up[i] = wt(nm.f("dflash.lili.blk.%d.mlp_up.bias", i), ls("mlp.up_proj.bias"), RAD_F32,
|
||||
{ cfg.mlp });
|
||||
w_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.weight", i), ls("mlp.down_proj.weight"),
|
||||
RAD_BF16, { hs, cfg.mlp });
|
||||
b_dn[i] = wt(nm.f("dflash.lili.blk.%d.mlp_down.bias", i), ls("mlp.down_proj.bias"),
|
||||
RAD_F32, { hs });
|
||||
if (!w_anorm[i] || !w_in[i] || !b_in[i] || !w_out[i] || !b_out[i] || !w_mnorm[i] ||
|
||||
!w_up[i] || !b_up[i] || !w_dn[i] || !b_dn[i])
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
w_onorm = wt(nm.f("dflash.lili.output_norm.weight"), src("output_norm.weight"), RAD_F32, { hs });
|
||||
w_annorm = wt(nm.f("dflash.lili.anchor_norm.weight"), src("anchor_norm.weight"), RAD_F32, { hs });
|
||||
w_fac = wt(nm.f("dflash.lili.factor_proj.weight"), src("factor_input_proj.weight"), RAD_BF16,
|
||||
{ hs, 3 * hs });
|
||||
b_fac = wt(nm.f("dflash.lili.factor_proj.bias"), src("factor_input_proj.bias"), RAD_F32,
|
||||
{ hs });
|
||||
/* [out_head | in_head] as one linear, as vLLM fuses them (`_fused_edge_weight`). */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.weight"),
|
||||
{ src("out_head.weight"), src("in_head.weight") }, 0));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("dflash.lili.edge.bias"),
|
||||
{ src("out_head.bias"), src("in_head.bias") }, 0));
|
||||
w_edge = decl_w(b, nm.f("dflash.lili.edge.weight"), RAD_BF16, { 2 * fd, hs }, ACC,
|
||||
RAD_SHARD_NONE, grp);
|
||||
b_edge = decl_w(b, nm.f("dflash.lili.edge.bias"), RAD_F32, { 2 * fd }, ACC, RAD_SHARD_NONE,
|
||||
grp);
|
||||
w_aout = wt(nm.f("dflash.lili.anchor_out.weight"), src("anchor_out_head.weight"), RAD_BF16,
|
||||
{ fd, hs });
|
||||
b_aout = wt(nm.f("dflash.lili.anchor_out.bias"), src("anchor_out_head.bias"), RAD_F32, { fd });
|
||||
if (!w_tokp || !b_tokp || !w_pass || !b_pass || !w_ctx || !b_ctx || !ln_w || !ln_b || !up_w ||
|
||||
!up_b || !w_fdn || !b_fdn || !w_slot || !w_rank || !w_rel || !w_same || !w_onorm ||
|
||||
!w_annorm || !w_fac || !b_fac || !w_edge || !b_edge || !w_aout || !b_aout)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- ops */
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t Kd, rad_weight wgt, rad_weight bias)
|
||||
-> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", Kd),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", "none")),
|
||||
RAD_WEIGHTS(wgt, bias));
|
||||
};
|
||||
auto rms = [&](int64_t rows, int64_t n, rad_weight gain) -> rad_op {
|
||||
return RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", cfg.eps),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(gain));
|
||||
};
|
||||
auto silu = [&](int64_t rows, int64_t n) -> rad_op {
|
||||
return RAD_OP(b, "silu",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS);
|
||||
};
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
/* The candidates: this rank's shard of the target's logits, its logprob row, the exchange. */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{ w.sel_h }, { w.logits });
|
||||
/* Replicated, `vocab_off` is omitted: an optional parameter present at 0 is a different
|
||||
* declaration from an absent one. */
|
||||
op_stats = g.world > 1
|
||||
? rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk), RAD_INT("vocab_off", g.vocab_off)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats })
|
||||
: rw(b, RAD_OP(b, "sample_logprobs",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("k", rk)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.logits }, { w.stats });
|
||||
if (g.world > 1)
|
||||
op_sgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * sw), RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", sw)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.stats }, { w.sgath });
|
||||
op_pas = rw(b, gemm_b(srows, hs, E, w_pass, b_pass), { w.sel_h }, { w.pas });
|
||||
op_cand = rw(b, RAD_OP(b, "lili_cand",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("k", K),
|
||||
RAD_INT("world", g.world), RAD_INT("steps", S),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", 1e-5), RAD_INT("row_k", rk)),
|
||||
RAD_WEIGHTS(ln_w, ln_b, up_w, up_b, w_slot, w_rank)),
|
||||
{ g.world > 1 ? w.sgath : w.stats, w.pas }, { w.cand, w.feat, w.hh });
|
||||
/* The lattice: candidates' embeddings (the trunk's vocab-sharded table, exact reduce), the
|
||||
* token and feature projections added onto lili_cand's base in their GEMMs' residual. */
|
||||
op_emb = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("n_embd", E),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{ w.cand }, { w.emb });
|
||||
if (g.world > 1)
|
||||
op_emb_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", E, lrows * E),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.emb }, { w.emb });
|
||||
op_tokp = rw(b, gemm_b(lrows, hs, E, w_tokp, b_tokp), { w.emb, w.hh }, { w.hh });
|
||||
op_fdn = rw(b, gemm_b(lrows, hs, hs, w_fdn, b_fdn), { w.feat, w.hh }, { w.hh });
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, rms(lrows, hs, w_anorm[i]), { w.hh }, { w.y });
|
||||
op_in[i] = rw(b, gemm_b(lrows, 3 * hs, hs, w_in[i], b_in[i]), { w.y }, { w.qkv });
|
||||
op_out[i] = rw(b, gemm_b(lrows, hs, hs, w_out[i], b_out[i]), { w.att, w.hh }, { w.hh });
|
||||
op_mnorm[i] = rw(b, rms(lrows, hs, w_mnorm[i]), { w.hh }, { w.y });
|
||||
op_up[i] = rw(b, gemm_b(lrows, cfg.mlp, hs, w_up[i], b_up[i]), { w.y }, { w.up });
|
||||
op_dn[i] = rw(b, gemm_b(lrows, hs, cfg.mlp, w_dn[i], b_dn[i]), { w.ups, w.hh }, { w.hh });
|
||||
}
|
||||
op_attn = rw(b, RAD_OP(b, "lili_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("steps", S), RAD_INT("k", K),
|
||||
RAD_INT("n_head", cfg.n_head),
|
||||
RAD_INT("head_dim", hs / cfg.n_head),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_rel, w_same)),
|
||||
{ w.qkv }, { w.att });
|
||||
op_silu_up = rw(b, silu(lrows, cfg.mlp), { w.up }, { w.ups });
|
||||
op_onorm = rw(b, rms(lrows, hs, w_onorm), { w.hh }, { w.y });
|
||||
/* The anchor: the context pass's row at each drafting sequence's last committed position. */
|
||||
op_anc = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.c }, { w.anc });
|
||||
op_ctx = rw(b, gemm_b(g.max_seqs, hs, E, w_ctx, b_ctx), { w.anc }, { w.ast });
|
||||
op_annorm = rw(b, rms(g.max_seqs, hs, w_annorm), { w.ast }, { w.an });
|
||||
op_factor = rw(b, RAD_OP(b, "lili_factor",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, lrows), RAD_INT("L", S * K),
|
||||
RAD_INT("n", hs), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.y, w.an }, { w.cat });
|
||||
op_fac = rw(b, gemm_b(lrows, hs, 3 * hs, w_fac, b_fac), { w.cat }, { w.fh });
|
||||
op_silu_f = rw(b, silu(lrows, hs), { w.fh }, { w.fhs });
|
||||
op_edge = rw(b, gemm_b(lrows, 2 * fd, hs, w_edge, b_edge), { w.fhs }, { w.edges });
|
||||
op_aout = rw(b, gemm_b(g.max_seqs, fd, hs, w_aout, b_aout), { w.an }, { w.aout });
|
||||
op_walk = rw(b, RAD_OP(b, "lili_walk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", S),
|
||||
RAD_INT("k", K), RAD_INT("n", fd), RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("eps", cfg.vec_eps), RAD_F64("scale", cfg.scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.edges, w.aout, w.cand }, { w.tokens });
|
||||
if (!op_logits || !op_stats || (g.world > 1 && (!op_sgath || !op_emb_ar)) || !op_pas ||
|
||||
!op_cand || !op_emb || !op_tokp || !op_fdn || !op_attn || !op_silu_up || !op_onorm ||
|
||||
!op_anc || !op_ctx || !op_annorm || !op_factor || !op_fac || !op_silu_f || !op_edge ||
|
||||
!op_aout || !op_walk)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void LiliCorr::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t n = batch->n_seq, S = n * cfg.steps, Lr = S * cfg.k;
|
||||
if (n <= 0) return;
|
||||
if (!batch->anchor_rows) {
|
||||
rad_step_fail(c, "lilicorr: the query pass carries no anchor rows (RadBatch::anchor_rows): "
|
||||
"this engine does not position a block drafter's anchor");
|
||||
return;
|
||||
}
|
||||
const int64_t E = g.n_embd, hs = cfg.hs, fd = cfg.fdim;
|
||||
const int64_t sw = 2 + 2 * rk;
|
||||
|
||||
RAD_ISSUE_N(c, op_logits, S, brows(w.sel_h, S), RAD_W(w_lm), brows(w.logits, S));
|
||||
RAD_ISSUE_N(c, op_stats, S, brows(w.logits, S), RAD_NONE, brows(w.stats, S));
|
||||
if (op_sgath) RAD_ISSUE(c, op_sgath, brows(w.stats, S), brows(w.sgath, S));
|
||||
RAD_ISSUE_N(c, op_pas, S, brows(w.sel_h, S), RAD_W(w_pass), RAD_W(b_pass), RAD_NONE,
|
||||
brows(w.pas, S));
|
||||
RAD_ISSUE_N(c, op_cand, S, op_sgath ? brows(w.sgath, S) : brows(w.stats, S), brows(w.pas, S),
|
||||
RAD_W(ln_w), RAD_W(ln_b), RAD_W(up_w), RAD_W(up_b), RAD_W(w_slot), RAD_W(w_rank),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.feat, Lr), brows(w.hh, Lr));
|
||||
(void)sw;
|
||||
|
||||
RAD_ISSUE_N(c, op_emb, Lr, brow_slice(w.cand, 0, Lr, 1), RAD_W(w_tok), brows(w.emb, Lr));
|
||||
if (op_emb_ar) RAD_ISSUE_N(c, op_emb_ar, Lr * E, brows(w.emb, Lr), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_tokp, Lr, brows(w.emb, Lr), RAD_W(w_tokp), RAD_W(b_tokp), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_fdn, Lr, brows(w.feat, Lr), RAD_W(w_fdn), RAD_W(b_fdn), brows(w.hh, Lr),
|
||||
brows(w.hh, Lr));
|
||||
for (int64_t l = 0; l < cfg.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_anorm[i], Lr, brows(w.hh, Lr), RAD_W(w_anorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_in[i], Lr, brows(w.y, Lr), RAD_W(w_in[i]), RAD_W(b_in[i]), RAD_NONE,
|
||||
brows(w.qkv, Lr));
|
||||
RAD_ISSUE_N(c, op_attn, Lr, brows(w.qkv, Lr), RAD_W(w_rel), RAD_W(w_same), brows(w.att, Lr));
|
||||
RAD_ISSUE_N(c, op_out[i], Lr, brows(w.att, Lr), RAD_W(w_out[i]), RAD_W(b_out[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
RAD_ISSUE_N(c, op_mnorm[i], Lr, brows(w.hh, Lr), RAD_W(w_mnorm[i]), brows(w.y, Lr));
|
||||
RAD_ISSUE_N(c, op_up[i], Lr, brows(w.y, Lr), RAD_W(w_up[i]), RAD_W(b_up[i]), RAD_NONE,
|
||||
brows(w.up, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_up, Lr, brows(w.up, Lr), brows(w.ups, Lr));
|
||||
RAD_ISSUE_N(c, op_dn[i], Lr, brows(w.ups, Lr), RAD_W(w_dn[i]), RAD_W(b_dn[i]),
|
||||
brows(w.hh, Lr), brows(w.hh, Lr));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_onorm, Lr, brows(w.hh, Lr), RAD_W(w_onorm), brows(w.y, Lr));
|
||||
|
||||
RAD_ISSUE_N(c, op_anc, n, RAD_B(w.c), praw(batch->anchor_rows, RAD_I32, n), brows(w.anc, n));
|
||||
RAD_ISSUE_N(c, op_ctx, n, brows(w.anc, n), RAD_W(w_ctx), RAD_W(b_ctx), RAD_NONE, brows(w.ast, n));
|
||||
RAD_ISSUE_N(c, op_annorm, n, brows(w.ast, n), RAD_W(w_annorm), brows(w.an, n));
|
||||
RAD_ISSUE_N(c, op_factor, Lr, brows(w.y, Lr), brows(w.an, n), brows(w.cat, Lr));
|
||||
RAD_ISSUE_N(c, op_fac, Lr, brows(w.cat, Lr), RAD_W(w_fac), RAD_W(b_fac), RAD_NONE,
|
||||
brows(w.fh, Lr));
|
||||
RAD_ISSUE_N(c, op_silu_f, Lr, brows(w.fh, Lr), brows(w.fhs, Lr));
|
||||
RAD_ISSUE_N(c, op_edge, Lr, brows(w.fhs, Lr), RAD_W(w_edge), RAD_W(b_edge), RAD_NONE,
|
||||
brows(w.edges, Lr));
|
||||
RAD_ISSUE_N(c, op_aout, n, brows(w.an, n), RAD_W(w_aout), RAD_W(b_aout), RAD_NONE,
|
||||
brows(w.aout, n));
|
||||
RAD_ISSUE_N(c, op_walk, n, brows(w.edges, Lr), brows(w.aout, n),
|
||||
brow_slice(w.cand, 0, Lr, 1), brows(w.tokens, n), RAD_NONE);
|
||||
(void)E; (void)hs; (void)fd;
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_LILICORR_H */
|
||||
@@ -132,9 +132,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
swiglu_limit));
|
||||
|
||||
/* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain
|
||||
* MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included),
|
||||
* and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would
|
||||
* take it, which would pin the layer's weights to the host. */
|
||||
* MXFP4 at one to 16 rows (eight where K is short), decl_gated_fold_iqr for an IQR weight
|
||||
* whose input and output are the rotated int8 trunk's fed pairs, to 16 rows. Other gate_up
|
||||
* encodings (M2XFP4 included), and a clamped (swiglu_limit) product, take the pair. */
|
||||
const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale;
|
||||
if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 &&
|
||||
!gate_up.i8)
|
||||
@@ -144,6 +144,14 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s },
|
||||
&gated_rows, wide_fold);
|
||||
else if (fold_ok && gate_up.iqr && w.h.q8_fed && w.h.q8_rot && w.ffn.q8_fed && w.ffn.q8_rot)
|
||||
op_gated = decl_gated_fold_iqr(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
{ w.h.q8, w.h.s8 },
|
||||
gq_ffn.want_x
|
||||
? std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8,
|
||||
w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q8, w.ffn.s8 },
|
||||
&gated_rows);
|
||||
else if (fold_ok && gate_up.mx && !gate_up.paro)
|
||||
op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
|
||||
gate_up.wref, { w.h.q, w.h.s },
|
||||
@@ -207,10 +215,11 @@ inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
/* The fp8a8 fold's E4M3 pairs, or the IQR fold's int8 ones (cq / cs: the fed pair). */
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.cq(), r0, rows, g.n_embd),
|
||||
brow_slice(w.h.cs(), r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.cq(), r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.cs(), r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else {
|
||||
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
|
||||
|
||||
@@ -182,8 +182,19 @@ struct MoeFP8 {
|
||||
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
|
||||
int expert_f32_scale = 0;
|
||||
double route_scale = 1.0;
|
||||
/* With `sigmoid_router`: group-limited selection over `n_group` groups, `topk_group` kept
|
||||
* (router_sigmoid_group_topk; Ling-3.0). 1 is GLM's single group. The fused selection and
|
||||
* sort is single-group, so a grouped router runs the separate pair. */
|
||||
int64_t n_group = 1, topk_group = 1;
|
||||
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
|
||||
double swiglu_limit = 0.0;
|
||||
/* The shared arm's clamp where it differs from the routed one (Ling-3.0 clamps its shared
|
||||
* expert at 5 or 7 and its routed ones at 4, in different layers); negative: the routed
|
||||
* arm's. */
|
||||
double shared_swiglu_limit = -1.0;
|
||||
/* Clip after the SiLU (`swiglu_step`) rather than before it (`swiglu_clamped`), for both
|
||||
* arms. */
|
||||
int swiglu_step = 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;
|
||||
@@ -196,6 +207,19 @@ struct MoeFP8 {
|
||||
* At TP1 the ungated gather preserves both roundings; TP>1 reduces each arm separately
|
||||
* before combining, so its gather cannot fold the shared output. */
|
||||
int shared_fp32_combine = 0;
|
||||
/* Experts without a gate (Nemotron-H): one projection up (`up_proj`), relu(x)^2, and down,
|
||||
* so the first GEMM is n_ff_exp wide rather than 2 * n_ff_exp and the quantiser between
|
||||
* the GEMMs squares rather than gates (GateQuantFP8's "relu2"). The routed arm only: such a
|
||||
* family's shared expert is the caller's. */
|
||||
int ungated = 0;
|
||||
/* The router's input width when it is not the experts' (Nemotron-H's latent experts: the
|
||||
* router scores the full hidden state, the experts read a narrower projection of it, and
|
||||
* this block's Geom is the experts'). 0 means n_embd. With it the router reads
|
||||
* Wire::route. The sigmoid router only. */
|
||||
int64_t router_k = 0;
|
||||
/* The caller reduces the block's delta across ranks, because it applies more linear work
|
||||
* to it first (Nemotron-H's latent up-projection); no all-reduce is declared. */
|
||||
int no_reduce = 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
|
||||
@@ -267,6 +291,8 @@ struct MoeFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the block's delta */
|
||||
/* The router's input when Config::router_k is set; `h` otherwise. */
|
||||
rad_buf route = 0; /* [max_tok, router_k] bf16 */
|
||||
/* Rotated codes of the same input (only `q` and `s`; `x` is `h`'s). Declared only with
|
||||
* `expert_rot`: the routed gate_up reads them, the shared expert reads `h`'s. */
|
||||
ActFP8 hr{}; /* [max_tok, n_embd] q + scale only */
|
||||
@@ -547,17 +573,19 @@ inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const c
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_gate_up(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
long long ge) {
|
||||
long long ge, bool ungated = false) {
|
||||
if (src.experts_gate_up) return map_slice(b, guw, src.experts_gate_up, (int)ge);
|
||||
if (src.experts_gate && src.experts_up)
|
||||
return map_slice_concat(b, guw, {src.experts_gate, src.experts_up}, (int)ge);
|
||||
/* Ungated experts (Nemotron-H) have no gate_proj: the first GEMM is up_proj alone. */
|
||||
if (ungated) return map_copy(b, guw, nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge));
|
||||
return map_concat(b, guw, {nm.ckpt("%s.%lld.gate_proj.weight", src.experts, ge),
|
||||
nm.ckpt("%s.%lld.up_proj.weight", src.experts, ge)});
|
||||
}
|
||||
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
const char* dnw, long long ge, bool gate_up) {
|
||||
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
if (gate_up) RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, src.cfg.ungated));
|
||||
if (src.experts_gate_up || src.experts_gate)
|
||||
return map_slice(b, dnw, src.experts_down, (int)ge);
|
||||
return map_copy(b, dnw, nm.ckpt("%s.%lld.down_proj.weight", src.experts, ge));
|
||||
@@ -584,7 +612,7 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
|
||||
int f = 0;
|
||||
for (long long ge = g0; ge < gn && ge <= g0 + kMaxProtected; ++ge) {
|
||||
const char* guw = nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, ge);
|
||||
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge));
|
||||
RAD_ARCH_TRY(moe_map_gate_up(b, nm, src, guw, ge, cfg->ungated));
|
||||
cfg->probed_count = ge - g0 + 1;
|
||||
RadEncoding e{};
|
||||
f = 0;
|
||||
@@ -618,6 +646,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
int ar_in, bool ar_out_) {
|
||||
g = geom; c = src.cfg; w = wire; layer = l;
|
||||
ar_out = ar_out_;
|
||||
if (c.n_group > 1) c.router_fuse = 0;
|
||||
const double sh_limit = c.shared_swiglu_limit < 0 ? c.swiglu_limit : c.shared_swiglu_limit;
|
||||
/* 0 means not expert-parallel: this rank owns every expert. */
|
||||
if (c.n_expert_all <= 0) c.n_expert_all = c.n_expert;
|
||||
if (c.n_expert <= 0 || c.top_k <= 0 || c.top_k > c.n_expert_all || c.n_ff_exp <= 0)
|
||||
@@ -639,6 +669,21 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
"BF16 shared arm and routed output\n", l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The first GEMM's rows per intermediate column (gate and up, or up alone) and the activation
|
||||
* between the GEMMs. */
|
||||
const int64_t gu = c.ungated ? 1 : 2;
|
||||
const char* const gact = c.ungated ? "relu2" : "silu";
|
||||
if (c.ungated && (shared || src.experts_gate_up || src.experts_gate ||
|
||||
c.swiglu_limit > 0)) {
|
||||
fprintf(stderr, "radiance: ungated experts are served one by one (`up_proj`), unclamped and "
|
||||
"without a shared arm in this block\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.router_k && (!c.sigmoid_router || !w.route)) {
|
||||
fprintf(stderr, "radiance: a router over another input than the experts' is the sigmoid "
|
||||
"router reading Wire::route\n");
|
||||
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;
|
||||
@@ -764,9 +809,13 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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 };
|
||||
rc.groups = c.n_group;
|
||||
rc.topk_groups = c.topk_group;
|
||||
const GlmRouter::Wire wire{ c.router_k ? w.route : 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));
|
||||
Geom rg = g;
|
||||
if (c.router_k) rg.n_embd = c.router_k;
|
||||
RAD_ARCH_TRY(glm_router.declare(b, nm, rg, 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;
|
||||
@@ -931,7 +980,7 @@ 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;
|
||||
const int n_parts = ep ? 0 : (int)gu;
|
||||
/* 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. */
|
||||
@@ -969,10 +1018,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp };
|
||||
const int64_t parts[2] = { c.n_ff_exp, c.n_ff_exp }; /* gate, up (up alone: one) */
|
||||
w_gu[(size_t)e] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
RAD_BF16, {2 * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
|
||||
RAD_BF16, {gu * c.n_ff_exp, g.n_embd}, RAD_ACCESS_CONDITIONAL,
|
||||
sh_row, grp_expert_slot(l, (int)e, 0), 0, parts, n_parts);
|
||||
if (!w_gu[(size_t)e]) return RAD_E_INVAL;
|
||||
}
|
||||
@@ -986,7 +1035,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* Row orders as for the quantised GEMMs (see `a_order` below): gate_up gathers token rows,
|
||||
* down reads sorted rows. */
|
||||
op_gu = rw(b, rad_decl_op(b, "moe_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * c.n_ff_exp),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * c.n_ff_exp),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", ne),
|
||||
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -996,8 +1045,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* (rad_fp8.h: GateQuantFP8). */
|
||||
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, c.swiglu_limit));
|
||||
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
|
||||
true, false, c.swiglu_limit, c.swiglu_step != 0));
|
||||
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),
|
||||
@@ -1015,7 +1064,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_weight& h = w_gu[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + e)),
|
||||
nullptr, ecodes, edt[0], {2 * wq[q], g.n_embd},
|
||||
nullptr, ecodes, edt[0], {gu * wq[q], g.n_embd},
|
||||
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
|
||||
parts, n_parts);
|
||||
if (!h) return RAD_E_INVAL;
|
||||
@@ -1031,7 +1080,7 @@ 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 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
|
||||
{(c.expert_w4 || c.expert_mx) ? gu * wq[q] : fp8_blocks(gu * 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);
|
||||
@@ -1107,22 +1156,22 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", 2 * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", 2)),
|
||||
RAD_INT("N_1", gu * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", gu * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", gu * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_odd", 2 * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", 2)),
|
||||
RAD_INT("N_odd", gu * wq[1]), RAD_INT("K_odd", g.n_embd),
|
||||
RAD_INT("parts", gu)),
|
||||
tab.data(), (int)tab.size());
|
||||
op_gu = rw(b, h, {rot ? w.hr.q : w.h.q, rot ? w.hr.s : w.h.s, w.sorted, w.eoff}, {w.egu});
|
||||
}
|
||||
@@ -1130,8 +1179,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* 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, c.swiglu_limit));
|
||||
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, gact, c.rows * c.top_k,
|
||||
false, rot, c.swiglu_limit, c.swiglu_step != 0));
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
|
||||
rad_op h = ncls == 4
|
||||
@@ -1184,7 +1233,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* the plain even split with no span. */
|
||||
psh_row = RAD_SHARD_ROW;
|
||||
psh_col = RAD_SHARD_COL;
|
||||
pparts = 2;
|
||||
pparts = (int)gu;
|
||||
if (full % g.world == 0 && (full / g.world) % 64 == 0) {
|
||||
wp = full / g.world;
|
||||
} else if (full % 64 || full / 64 < g.world) {
|
||||
@@ -1206,7 +1255,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t parts[2] = { wp, wp };
|
||||
w_pgu[(size_t)j] = decl_w_n(b, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
|
||||
(long long)(c.expert_base + prot[(size_t)j])),
|
||||
RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_BF16, {gu * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
|
||||
psh_row, grp_layer(l), 0, parts, pparts);
|
||||
if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
|
||||
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi));
|
||||
@@ -1221,11 +1270,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
/* The gate_up and gate outputs, bf16, one sorted row each; regular experts' rows are
|
||||
* unused. */
|
||||
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, 2 * wp});
|
||||
b_pgu = decl_b(b, nm.f("blk.%d.moe_prot_gu", l), RAD_BF16, {c.rows * c.top_k, gu * wp});
|
||||
pff.x = decl_b(b, nm.f("blk.%d.moe_prot_ff", l), RAD_BF16, {c.rows * c.top_k, wp});
|
||||
if (!b_pgu || !pff.x) return RAD_E_INVAL;
|
||||
op_pgu = rw(b, rad_decl_op(b, "moe_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wp),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", gu * wp),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", np),
|
||||
RAD_INT("top_k", c.top_k), RAD_STR("a_order", "token"),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -1233,8 +1282,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.h.x, w.sorted, w.eoff}, {b_pgu});
|
||||
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, c.swiglu_limit));
|
||||
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, gact, c.rows * c.top_k, true,
|
||||
false, c.swiglu_limit, c.swiglu_step != 0));
|
||||
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),
|
||||
@@ -1374,7 +1423,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 || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
|
||||
if (!w.sff.q || sh_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));
|
||||
@@ -1391,7 +1440,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
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), false,
|
||||
c.swiglu_limit));
|
||||
sh_limit, c.swiglu_step != 0));
|
||||
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
|
||||
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
|
||||
{ shared_down },
|
||||
@@ -1515,7 +1564,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
}
|
||||
|
||||
if (g.world > 1) {
|
||||
if (g.world > 1 && !c.no_reduce) {
|
||||
const auto all_reduce = [&](const char* dtype, rad_buf buffer) {
|
||||
return rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -1536,7 +1585,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
}
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar, a pipelined
|
||||
* prefill): at `overlap` 1 it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
if (g.world > 1 && !c.no_reduce && ar_overlap > 0)
|
||||
op_ar_ov = 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),
|
||||
@@ -1784,6 +1833,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
|
||||
(!calib_dne_failed &&
|
||||
calib_dne.write(gram_dn_stem, c.expert_base, gram_domain,
|
||||
rad_rank(c_)));
|
||||
/* Written: the host sums are done with (a layer's can be gigabytes). */
|
||||
calib_dne.acc = {};
|
||||
calib_dne.rows = {};
|
||||
calib_done = true;
|
||||
if (layer == 0)
|
||||
std::fprintf(stderr, "radiance: calibration wrote layer Hessians after %lld "
|
||||
|
||||
@@ -25,7 +25,13 @@
|
||||
* safetensors file per input, <dir>/<stem>.safetensors, holding `hessian_upper`, f32
|
||||
* [k * (k + 1) / 2], row i's entries k2 = i .. k-1 after row i-1's, and metadata naming `k`, the
|
||||
* rows summed and the checkpoint linears that read the input. H is the raw sum; divide by `rows`
|
||||
* for the mean second moment. */
|
||||
* for the mean second moment.
|
||||
*
|
||||
* An int8 trunk (site_i8, one rank only) is recorded from the codes and scales its GEMMs actually
|
||||
* read, so H includes what the model's own quantisation did to the input -- the input a quantised
|
||||
* model feeds each layer, for GPTQ against the error it inherits. Codes a rotating producer wrote
|
||||
* are in the rotated domain; the file's metadata then names it (`domain`: the Hadamard width), as
|
||||
* RADGRAM2's header does, and the reader converts. */
|
||||
#pragma once
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
@@ -52,6 +58,8 @@ struct CalibFull {
|
||||
rad_op op_gather = 0; /* the columns of every rank into `gathered`; 0 when replicated */
|
||||
rad_op op_gram = 0; /* declared on the owner only */
|
||||
bool owner = false;
|
||||
rad_buf q8 = 0, s8 = 0; /* site_i8: the int8 codes and their f32 (row, 128) scales */
|
||||
uint32_t domain = 0; /* site_i8: the codes' rotation width, 0 for none */
|
||||
std::vector<float> tri; /* the owner's accumulator, upper triangle packed */
|
||||
};
|
||||
|
||||
@@ -156,6 +164,32 @@ struct CalibFull {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One input of layer `layer` from an int8 trunk's codes `q8` and scales `s8` (see the file
|
||||
* comment): the whole input on one rank, `domain` the Hadamard width the codes were rotated by
|
||||
* (0 for none). */
|
||||
int site_i8(RadBuilder* b, const Geom& g, int64_t layer, std::string stem, std::string linears,
|
||||
rad_buf q8, rad_buf s8, int64_t K, uint32_t domain) {
|
||||
if (world > 1 || !q8 || !s8 || K > kmax) return RAD_E_INVAL;
|
||||
Site s;
|
||||
s.stem = std::move(stem);
|
||||
s.linears = std::move(linears);
|
||||
s.K = s.k_local = K;
|
||||
s.owner = true;
|
||||
s.q8 = q8;
|
||||
s.s8 = s8;
|
||||
s.domain = domain;
|
||||
(void)layer;
|
||||
s.op_gram = rw(b, RAD_OP(b, "gram_accum",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", 128), RAD_STR("dtype", "i8a8"),
|
||||
RAD_INT("upper", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ q8, s8, scratch }, { scratch });
|
||||
if (!s.op_gram) return RAD_E_INVAL;
|
||||
sites.push_back(std::move(s));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Site `i` over a step's T rows: gather (every rank), then on the owner the Gram into the
|
||||
* scratch, copied to a free square, the scratch zeroed, and the square handed to the worker. */
|
||||
void tap(RadCtx* c, size_t i, int64_t T) {
|
||||
@@ -186,7 +220,10 @@ struct CalibFull {
|
||||
}
|
||||
}
|
||||
const int64_t K = s.K;
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
if (s.q8)
|
||||
RAD_ISSUE_N(c, s.op_gram, T, brows(s.q8, T), brows(s.s8, T), praw2(dev, RAD_F32, K, K));
|
||||
else
|
||||
RAD_ISSUE_N(c, s.op_gram, T, a, RAD_NONE, praw2(dev, RAD_F32, K, K));
|
||||
/* `upper` 1 writes no entry below the diagonal, so only the upper triangle comes back:
|
||||
* band by band of kBand rows, each from its first row's diagonal on, about half the
|
||||
* square's bytes. The link is what a step's taps wait on, 25 GB a step on each rank of
|
||||
@@ -317,7 +354,9 @@ private:
|
||||
const uint64_t bytes = (uint64_t)s.tri.size() * 4;
|
||||
std::string hdr = "{\"__metadata__\":{\"k\":\"" + std::to_string(s.K) + "\",\"rows\":\"" +
|
||||
std::to_string(seen) + "\",\"layout\":\"upper triangle, row-major, packed\","
|
||||
"\"linears\":\"" + s.linears + "\"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"linears\":\"" + s.linears + "\"" +
|
||||
(s.domain ? ",\"domain\":\"" + std::to_string(s.domain) + "\"" : std::string()) +
|
||||
"},\"hessian_upper\":{\"dtype\":\"F32\","
|
||||
"\"shape\":[" + std::to_string(s.tri.size()) + "],\"data_offsets\":[0," +
|
||||
std::to_string(bytes) + "]}}";
|
||||
while (hdr.size() % 8) hdr += ' ';
|
||||
|
||||
+92
-6
@@ -141,8 +141,9 @@ inline int QuantFP8::declare(RadBuilder* b, const Geom& g, const ActFP8& act, in
|
||||
if (g.w_bf16) { op = 0; return a.x ? RAD_OK : RAD_E_INVAL; }
|
||||
if (!a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
|
||||
/* `dtype` is the input's (bf16); the op name gives the output format. An input fed at int8
|
||||
* codes is quantised by quant_act_i8g into its int8 pair. */
|
||||
op = rw(b, RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
|
||||
* codes is quantised by quant_act_i8g into its int8 pair, or by had_quant_act_i8g where they
|
||||
* are rotated (ActFP8::q8_rot). */
|
||||
op = rw(b, RAD_OP(b, a.q8_fed ? (a.q8_rot ? "had_quant_act_i8g" : "quant_act_i8g") : "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -580,14 +581,20 @@ struct GateQuantFP8 {
|
||||
* not resolve: `silu_mul` into the bf16 plane (`op`), then `had_quant_act_fp8` over it into the
|
||||
* codes (`op_q`). */
|
||||
rad_op op_q = 0;
|
||||
/* act "relu2" (Nemotron-H's ungated experts): `gate_up` is one part, n wide, and `op` is
|
||||
* act_mul's relu over it twice, relu(x)^2 into the bf16 plane, which `op_q` quantises (rotated
|
||||
* for a rotated weight). No fused form yet: the plane is written either way. */
|
||||
bool ungated = false;
|
||||
|
||||
/* Set before declare: the product in bf16 alone, as for bf16 linears, for a consumer that
|
||||
* quantises its input itself (an int8 linear's op_q). */
|
||||
bool silu_only = false;
|
||||
|
||||
/* `step`: with `limit`, clip after the SiLU (`swiglu_step`, Ling-3.0) rather than before it
|
||||
* (`swiglu_clamped`, GLM-5.3). It has no fused quantiser, so the pair runs. */
|
||||
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, double limit = 0);
|
||||
bool rot = false, double limit = 0, bool step = false);
|
||||
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
|
||||
};
|
||||
|
||||
@@ -596,7 +603,7 @@ 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, double limit) {
|
||||
bool bf16_out, bool rot, double limit, bool step) {
|
||||
a = act;
|
||||
want_x = bf16_out;
|
||||
op_quant = 0;
|
||||
@@ -607,6 +614,28 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
clipped = limit > 0;
|
||||
clamped_fused = false;
|
||||
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
|
||||
ungated = std::strcmp(act_name, "relu2") == 0;
|
||||
if (ungated) {
|
||||
if (!gate_up || !a.x || n <= 0 || clipped || (!bf16 && (!a.cq() || !a.cs())) ||
|
||||
(rot && a.q8_fed))
|
||||
return RAD_E_INVAL;
|
||||
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
|
||||
want_x = true;
|
||||
op = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("act", "relu"),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ gate_up }, { a.x });
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (bf16) return RAD_OK;
|
||||
const char* qn = rot ? "had_quant_act_fp8" : a.q8_fed ? "quant_act_i8g" : "quant_act_fp8";
|
||||
op_q = rw(b, RAD_OP(b, qn,
|
||||
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() });
|
||||
return op_q ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (clipped) {
|
||||
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated; and no clamp
|
||||
* with `silu_only`. */
|
||||
@@ -614,7 +643,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
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() &&
|
||||
if (fuse_clamped && !step && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
|
||||
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
|
||||
op =
|
||||
RAD_OP(b, "swiglu_clamped_quant_fp8",
|
||||
@@ -631,7 +660,7 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
|
||||
}
|
||||
want_x = true;
|
||||
op = rw(b,
|
||||
RAD_OP(b, "swiglu_clamped",
|
||||
RAD_OP(b, step ? "swiglu_step" : "swiglu_clamped",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -701,6 +730,15 @@ 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 (ungated) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, n), brow_slice(gate_up, r0, rows, n),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
if (op_q)
|
||||
RAD_ISSUE_N(c, op_q, 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 (clamped_fused) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
|
||||
brow_slice(a.cq(), r0, rows, n),
|
||||
@@ -779,6 +817,13 @@ struct LinearFP8 {
|
||||
* writes E4M3. Read from the weight's encoding. */
|
||||
bool i8 = false;
|
||||
rad_op op_q = 0;
|
||||
/* An int8 weight stored rotated (i8a8h, or a rotated four- or five-bit one): its activation
|
||||
* codes are in the 128-wide Hadamard domain, whoever wrote them (had_quant_act_i8g or a
|
||||
* rotating producer). */
|
||||
bool i8_rot = false;
|
||||
/* With i8_rot: an IQR weight (libr4d's r4d_iqr.h), whose codes decode where they are read: a
|
||||
* u6 code under a zero, a table, a grid or a trellis. Read from the weight's encoding. */
|
||||
bool iqr = false;
|
||||
/* OCP-MXFP4 weight read by `gemm_nt_q` at dtype mxfp4a8 against the usual E4M3 activation pair:
|
||||
* e2m1 codes with one E8M0 exponent per 32 of K (libquant `codes=fp4_e2m1 group=32
|
||||
* scale=e8m0`). libr4d folds each block's exponent into the e4m3 operand against a per-row
|
||||
@@ -1310,6 +1355,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const bool asym = known && linear_is_wnh(enc);
|
||||
const bool rot8 = known && (linear_is_w8h(enc) || asym);
|
||||
i8 = known && (linear_is_w8(enc) || rot8);
|
||||
i8_rot = i8 && rot8;
|
||||
if (i8) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
@@ -1340,6 +1386,8 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
/* A narrower i8a8h weight's codes view takes the plane that decodes it too. */
|
||||
const W8hForm form = linear_w8h_form(enc);
|
||||
iqr = rot8 && !asym && (form == W8hForm::Zero || form == W8hForm::Table ||
|
||||
form == W8hForm::Grid || form == W8hForm::Trellis);
|
||||
const RadEncPlane* tpl = rad_enc_plane(&enc, "trellis");
|
||||
const bool trb = form == W8hForm::Trellis && tpl && tpl->block[1] > 1;
|
||||
const char* cv = form == W8hForm::Zero ? "codes,zero"
|
||||
@@ -1829,6 +1877,23 @@ struct DenseFP8 {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
|
||||
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
|
||||
}
|
||||
/* This rank's rows [lo, hi) of a RAD_SHARD_ROW weight where the even shard is the wrong cut: a
|
||||
* KV head replicated over ranks (Geom::kv_off), the same rows on every rank that shares it.
|
||||
* Call after declare(), whose N is already hi - lo. The fp8 scale plane takes the span in its
|
||||
* 128-row blocks; the MXFP4 and M2XFP4 planes are one row a weight row, as in LinearFP8. */
|
||||
int span(RadBuilder* b, int64_t lo, int64_t hi) const {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
|
||||
if (mx || m2x) {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, s, lo, hi));
|
||||
return rad_weight_shard_span(b, ref, lo, hi);
|
||||
}
|
||||
if (lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: a row span [%lld, %lld) is not whole %d-row scale blocks\n",
|
||||
(long long)lo, (long long)hi, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
|
||||
}
|
||||
/* `gemm_nt_q` over this weight, `fp8a8`, `mxfp4a8` or `m2xfp4` as it was declared, ranged
|
||||
* M 1..hi. `split_n`, when set, is the stored width a row slice takes its K split from
|
||||
* (docs/OPS.md). */
|
||||
@@ -1968,6 +2033,27 @@ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The same fold over an IQR [2n, K] gate_up weight under the rotated int8 trunk (`gemm_nt_q_gated`
|
||||
* at i8a8h: the codes and scale views gemm_nt_q reads, the input's and the output's int8 pairs, both
|
||||
* in the Hadamard domain), declared for M up to min(rows, 16): libr4d's gemm_iqr_gated serves its
|
||||
* GEMV and 16-token tile, each byte-identical to the GEMM row of its band followed by
|
||||
* gated_had_quant_i8g. Optional like decl_gated_fold, and asked for only when a loaded library
|
||||
* declares the op at that dtype: a CPU-only engine takes the pair. */
|
||||
inline rad_op decl_gated_fold_iqr(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w,
|
||||
rad_weight ws, std::initializer_list<rad_buf> reads,
|
||||
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
|
||||
if (rows <= 0 || N % 256 || K % 256) return 0;
|
||||
const int64_t hi = rows < 16 ? rows : 16;
|
||||
const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8h"),
|
||||
RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
reads, writes);
|
||||
if (op) *gated_rows = hi;
|
||||
return op;
|
||||
}
|
||||
|
||||
/* ================================================== a calibration tap */
|
||||
/* One tap of the GPTQ calibration (calib_dir): the Gram of a linear's bf16 input, summed over the
|
||||
* corpus in a PERSIST [K, K] f32 buffer that calib_write() saves. */
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (rad_block_gemma4_vision.h) and,
|
||||
* for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h).
|
||||
* for E2B/E4B, its audio encoder (rad_block_gemma4_audio.h); for the 12B ("unified"), its image and
|
||||
* audio embedders in their place (rad_block_gemma4_unified.h).
|
||||
*
|
||||
* Two attention classes over one residual stream, alternating by layer. A "sliding" layer is
|
||||
* sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global"
|
||||
@@ -17,6 +18,7 @@
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_audio.h>
|
||||
#include <arch/rad_block_gemma4_unified.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
#include <arch/rad_gemma4_dflash.h>
|
||||
@@ -454,6 +456,16 @@ struct Gemma4Attn {
|
||||
* no library serves it, which the model reads as "no trees". */
|
||||
bool tree = false;
|
||||
rad_op op_attn_tree = 0, op_tree_lift = 0;
|
||||
/* Pictures read both ways (Model::bidi, set before declare; sliding layers only): attention
|
||||
* again over a run's keys without the causal bound (RadBatch::n_bidi), reading q in the row
|
||||
* (op_bidi_row) where the step's attention does, else in its own rows (op_bidi); 0 where no
|
||||
* kernel serves it. */
|
||||
bool want_bidi = false;
|
||||
rad_op op_bidi = 0, op_bidi_row = 0;
|
||||
/* The same where the window bounds the keys behind a row only: a run longer than the window
|
||||
* (op_ahead_row where q is read in the row); 0 where no kernel serves it. */
|
||||
rad_op op_ahead = 0, op_ahead_row = 0;
|
||||
bool bidi_ok() const { return op_bidi || op_bidi_row; }
|
||||
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
|
||||
* "Prefetch beside the reductions") */
|
||||
rad_op op_pf = 0;
|
||||
@@ -492,6 +504,9 @@ struct Gemma4Attn {
|
||||
bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); }
|
||||
void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
|
||||
RadOperand used) const;
|
||||
/* The rows of each run read both ways, attended again (see op_bidi); `q_dense`: the step's
|
||||
* attention left q in its own rows. */
|
||||
void attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const;
|
||||
};
|
||||
|
||||
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
@@ -644,11 +659,12 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
/* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
|
||||
* use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
|
||||
* so 1.0 is passed explicitly. */
|
||||
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0) {
|
||||
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0,
|
||||
int causal = 1) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok),
|
||||
RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", causal),
|
||||
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
@@ -729,6 +745,15 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
op_attn = attn("attn_paged", {w.q, w.qkv});
|
||||
}
|
||||
}
|
||||
if (want_bidi) {
|
||||
if (op_attn_row) {
|
||||
op_bidi_row = attn("attn_paged_qrow", {w.qkv}, 0, 0);
|
||||
op_ahead_row = attn("attn_paged_qrow_ahead", {w.qkv}, 0, 0);
|
||||
} else {
|
||||
op_bidi = attn("attn_paged", {w.q}, 0, 0);
|
||||
op_ahead = attn("attn_paged_ahead", {w.q}, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
|
||||
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
|
||||
@@ -855,6 +880,23 @@ int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
if (want_bidi) {
|
||||
auto bidi = [&](const char* op) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 0),
|
||||
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
};
|
||||
op_bidi = bidi("attn_paged");
|
||||
op_ahead = bidi("attn_paged_ahead");
|
||||
}
|
||||
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),
|
||||
@@ -963,6 +1005,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
attend_bidi(c, batch, true);
|
||||
return;
|
||||
}
|
||||
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
|
||||
@@ -1001,6 +1044,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
* which come first (spec §8). */
|
||||
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
|
||||
batch->n_seq_decode > 0;
|
||||
bool q_dense = true;
|
||||
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
|
||||
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
|
||||
rad_op a_op = op_attn;
|
||||
@@ -1011,8 +1055,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
|
||||
a_op = op_attn_dec;
|
||||
a_q = Q;
|
||||
q_dense = false;
|
||||
} else if (row) {
|
||||
if (T == 1) a_q = Q;
|
||||
if (T == 1) { a_q = Q; q_dense = false; }
|
||||
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, a_op, batch->max_q_len,
|
||||
@@ -1039,6 +1084,44 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
brows(w.attn, Td),
|
||||
praw(batch->spec_parent, RAD_I32, Td));
|
||||
}
|
||||
attend_bidi(c, batch, q_dense);
|
||||
}
|
||||
|
||||
/* A run's rows (RadBatch::n_bidi) see every key of their run, later ones included: attention over
|
||||
* their sequence's cache up to the run's end without the causal bound, written over what the
|
||||
* causal pass left in their rows, on a sliding layer. Its window stays: (causal or the run) and
|
||||
* the window, as transformers' mask has it. The window bounds the keys behind a row; within it a
|
||||
* run's far end is in reach of every row up to the window's length, and a longer run is read with
|
||||
* attn_paged_ahead, whose window bounds the keys behind only. The keys are all in the cache: the
|
||||
* step stored its own, and a run's earlier rows are this step's or a prefix hit's. */
|
||||
void Gemma4Attn::attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const {
|
||||
if (batch->n_bidi <= 0 || !bidi_ok()) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
|
||||
for (int64_t i = 0; i < batch->n_bidi; ++i) {
|
||||
const int64_t r0 = batch->bidi_row[i], n = batch->bidi_n[i], s = batch->bidi_seq[i];
|
||||
const RadOperand tb = praw2(table ? table + s * pitch : nullptr, RAD_I32, 1, pitch);
|
||||
const RadOperand used = praw(batch->bidi_used + i, RAD_I32, 1);
|
||||
const RadOperand out = brow_slice(w.attn, r0, n, qd);
|
||||
/* A run longer than the window has rows that miss its far end under a two-sided window;
|
||||
* transformers' mask bounds only the keys behind. */
|
||||
const bool ahead = n > cls.window;
|
||||
const rad_op bidi_row = ahead && op_ahead_row ? op_ahead_row : op_bidi_row;
|
||||
const rad_op bidi = ahead && op_ahead ? op_ahead : op_bidi;
|
||||
if (op_bidi_row) {
|
||||
RAD_ISSUE_N(c, bidi_row, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
|
||||
kv_cache(kv, kv_layer), tb, used, RAD_NONE, RAD_NONE, RAD_NONE, out);
|
||||
continue;
|
||||
}
|
||||
if (!q_dense)
|
||||
RAD_ISSUE_N(c, op_lift_q, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
|
||||
brow_slice(w.q, r0, n, qd));
|
||||
RAD_ISSUE_N(c, bidi, n, brow_slice(w.q, r0, n, qd), kv_cache(kv, kv_layer), tb, used,
|
||||
RAD_NONE, RAD_NONE, RAD_NONE, out);
|
||||
}
|
||||
}
|
||||
|
||||
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
|
||||
@@ -1414,10 +1497,11 @@ struct Gemma4Head {
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
/* Does the container carry an assistant head at all? */
|
||||
/* Does the container carry an assistant head at all? The 12B's is the same head under another
|
||||
* name (Gemma4UnifiedAssistantForCausalLM). */
|
||||
static bool has_assistant(const RadModelMeta* m) {
|
||||
const char* a = rad_meta_gets(m, "draft.architectures", "");
|
||||
return a && std::strstr(a, "Gemma4Assistant") != nullptr;
|
||||
return a && (std::strstr(a, "Gemma4Assistant") || std::strstr(a, "Gemma4UnifiedAssistant"));
|
||||
}
|
||||
|
||||
int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk,
|
||||
@@ -1459,16 +1543,17 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
|
||||
}
|
||||
/* The head reads the trunk's cache, so everything the cache's shape depends on must agree:
|
||||
* the two head widths, the two kv head counts and the window. A head that disagrees was trained
|
||||
* with another trunk. */
|
||||
* with another trunk. The counts are the model's, not a rank's: a replicated kv head (fewer
|
||||
* than ranks) is one head on every rank. */
|
||||
if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim ||
|
||||
head_g != cg.head_dim || n_kv != cs.n_head_kv * trunk.world ||
|
||||
n_kv_g != cg.n_head_kv * trunk.world || win != cs.window) {
|
||||
head_g != cg.head_dim || n_kv != cs.n_head_kv_all || n_kv_g != cg.n_head_kv_all ||
|
||||
win != cs.window) {
|
||||
fprintf(stderr, "radiance: gemma4 assistant: this head was not made for this trunk -- it "
|
||||
"states width %lld, vocabulary %lld, heads %lld/%lld x %lld/%lld kv over a "
|
||||
"window of %lld; the trunk's cache is %lld/%lld kv heads of %lld/%lld over "
|
||||
"%lld, at width %lld and vocabulary %lld\n",
|
||||
(long long)n_trunk, vocab, n_kv, n_kv_g, head_s, head_g, win,
|
||||
(long long)(cs.n_head_kv * trunk.world), (long long)(cg.n_head_kv * trunk.world),
|
||||
(long long)cs.n_head_kv_all, (long long)cg.n_head_kv_all,
|
||||
(long long)cs.head_dim, (long long)cg.head_dim, (long long)cs.window,
|
||||
(long long)trunk.n_embd, (long long)trunk.n_vocab_all);
|
||||
return RAD_E_INVAL;
|
||||
@@ -1888,7 +1973,13 @@ struct Model {
|
||||
* embeddings. */
|
||||
Gemma4Vision vis{};
|
||||
Gemma4Audio aud{};
|
||||
Gemma4UnifiedVision uvis{}; /* the 12B's embedders, in place of the tower and encoder */
|
||||
Gemma4UnifiedAudio uaud{};
|
||||
rad_op op_mm = 0;
|
||||
/* A picture's or video frame's placeholders attend to each other both ways
|
||||
* (use_bidirectional_attention "vision"): every sliding layer attends a run's rows again
|
||||
* (Gemma4Attn::op_bidi), and the encoder says so (RadEncoderDecl::bidirectional). */
|
||||
bool bidi = false;
|
||||
|
||||
G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */
|
||||
bool fuse = false;
|
||||
@@ -2404,8 +2495,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the lookup and before its all-reduce (RadBatch::mm_embd: rank 0 holds the rows, every other
|
||||
* rank zeros). The reference scales token embeddings by sqrt(n_embd) and scatters the media
|
||||
* features in unscaled. */
|
||||
if ((Gemma4Vision::present(meta) && ctx->max_enc_patches > 0) ||
|
||||
(Gemma4Audio::present(meta) && ctx->max_audio_frames > 0))
|
||||
if (((Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta)) &&
|
||||
ctx->max_enc_patches > 0) ||
|
||||
((Gemma4Audio::present(meta) || Gemma4UnifiedAudio::present(meta)) &&
|
||||
ctx->max_audio_frames > 0))
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
@@ -2508,10 +2601,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
kv_shared == 0 && ctx->draft_tree != 0;
|
||||
bool tree_all = tree_want;
|
||||
|
||||
/* Pictures read both ways where the model was trained so, on the sliding layers alone: the
|
||||
* global layers stay causal (transformers' create_masks_for_vision_model, "Gemma 4 explicitly
|
||||
* disables bidirectional attention on global attention layers"; KerasHub's Gemma 4 decoder
|
||||
* block and vLLM agree). */
|
||||
const char* bidi_cfg = meta_text_gets(meta, "use_bidirectional_attention", "");
|
||||
const bool want_bidi = bidi_cfg && !std::strcmp(bidi_cfg, "vision") && ctx->max_enc_patches > 0 &&
|
||||
(Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta));
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.global = (is_global[(size_t)l] == 1);
|
||||
lay.attn.want_bidi = want_bidi && !lay.global;
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
|
||||
@@ -2818,11 +2919,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta));
|
||||
head_groups = rad_meta_geti(meta, k, 0);
|
||||
}
|
||||
m.bidi = want_bidi;
|
||||
for (const Layer& lay : m.layers) m.bidi = m.bidi && (lay.global || lay.attn.bidi_ok());
|
||||
if (want_bidi && !m.bidi)
|
||||
rad_note(b, "pictures are read causally: no kernel attends a run's rows without the "
|
||||
"causal bound");
|
||||
m.vis.bidirectional = m.uvis.bidirectional = m.bidi;
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
|
||||
"model.", "gemma4_bf16"));
|
||||
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd,
|
||||
(int)(m.n_main + head_groups) + (int)m.vis.L.size(), "model.",
|
||||
"gemma4_bf16"));
|
||||
RAD_ARCH_TRY(m.uvis.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
|
||||
RAD_ARCH_TRY(m.uaud.declare(b, meta, ctx, nm, g.n_embd, "gemma4_bf16"));
|
||||
}
|
||||
|
||||
rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, "
|
||||
@@ -2954,7 +3063,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
|
||||
|
||||
m.j0.step(c, T);
|
||||
const size_t L = m.layers.size();
|
||||
if (m.slice_attn && batch->n_seq == 1) {
|
||||
if (m.slice_attn && batch->n_seq == 1 && batch->n_bidi == 0) {
|
||||
/* Attention per slice (see Model::slice_attn): slice A's context end first, then each
|
||||
* layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward
|
||||
* beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each
|
||||
@@ -3050,8 +3159,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
|
||||
/* An encoder pass runs only its encoder. */
|
||||
if (batch->enc) {
|
||||
if (batch->enc == RAD_MM_AUDIO) m.aud.step(c, batch);
|
||||
else m.vis.step(c, batch);
|
||||
if (batch->enc == RAD_MM_AUDIO) {
|
||||
if (m.uaud.on) m.uaud.step(c, batch);
|
||||
else m.aud.step(c, batch);
|
||||
} else if (m.uvis.on) {
|
||||
m.uvis.step(c, batch);
|
||||
} else {
|
||||
m.vis.step(c, batch);
|
||||
}
|
||||
return;
|
||||
}
|
||||
/* A draft pass runs only the draft model. The trunk already left its final-normed hidden state
|
||||
@@ -3192,12 +3307,15 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
if (Gemma4Audio::present(meta)) out->audio_frames = Gemma4Audio::frames_for(meta);
|
||||
/* The 12B's embedders: a patch and an audio frame are a row each. */
|
||||
if (Gemma4UnifiedVision::present(meta)) out->enc_merge = 1;
|
||||
if (Gemma4UnifiedAudio::present(meta)) out->audio_frames = Gemma4UnifiedAudio::frames_for(meta);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"Gemma 4 dense (text, images and E2B/E4B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"Gemma 4 dense (text, images, E2B/E4B/12B audio), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"release: sliding-window and proportional-RoPE global attention over a plain "
|
||||
"RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped "
|
||||
"logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter")
|
||||
|
||||
+65
-24
@@ -50,6 +50,12 @@ struct Model {
|
||||
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
|
||||
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
|
||||
GlmMla::Form form = GlmMla::Form::heads;
|
||||
/* Routed experts whole on their rank (288/world of them) instead of split by width across
|
||||
* every rank. Whole experts can be read from the drive, which two cards need; at four and
|
||||
* eight the width split is the shape the MXFP4 kernels are tuned for (prefill runs about three
|
||||
* times faster), so all-MXFP4 experts take it unless --weights-disk-tier asks for the drive.
|
||||
* Anything else stays whole: a plain bf16 expert cannot be sliced at all. */
|
||||
bool whole_experts = false;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
@@ -76,6 +82,23 @@ struct Model {
|
||||
static std::unique_ptr<Model> models[MAX_RANKS];
|
||||
static thread_local std::unique_ptr<Model> probe_model;
|
||||
|
||||
/* Whether every routed expert is MXFP4, asked before any buffer is sized and of the same experts on
|
||||
* every rank, so all ranks reach the same layout. It reads the container's entries and declares no
|
||||
* name map, so it leaves the graph as it was. One expert in another format settles it: a protected
|
||||
* bf16 expert is served only whole. No answer means no container entry, and what is not known to
|
||||
* be MXFP4 stays whole. */
|
||||
static bool experts_are_mxfp4(RadBuilder* b, Names& nm) {
|
||||
for (int l = 3; l < 45; ++l)
|
||||
for (int ge = 0; ge < 288; ++ge)
|
||||
for (const char* fmt : { "blk.%d.ffn_gate_up_exps.%d.weight",
|
||||
"blk.%d.ffn_down_exps.%d.weight" }) {
|
||||
RadEncoding e{};
|
||||
if (!weight_enc(b, nm.f(fmt, l, ge), &e) || MoeFP8::format_of(e) != 8)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
|
||||
char nested[160];
|
||||
std::snprintf(nested, sizeof nested, "text_config.%s", key);
|
||||
@@ -211,6 +234,7 @@ static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
* at 64k of context the whole step's plane would be 256 MiB. */
|
||||
const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T;
|
||||
c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks });
|
||||
c.unscored = decl_b(b, nm.f("index_unscored"), RAD_F32, { T, std::min<int64_t>(513, blocks) });
|
||||
c.selected = m.aw.core.selected;
|
||||
c.length = m.aw.core.length;
|
||||
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
|
||||
@@ -243,13 +267,18 @@ static int ffn_buffers(RadBuilder* b, Model& m) {
|
||||
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
|
||||
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
|
||||
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
|
||||
/* PERSIST, as every other MoE here declares it: the router writes the counts and no declared
|
||||
* op reads them (rad_route_report is a handoff), so as a transient a later buffer could share
|
||||
* their bytes and an arena level would move them, while the core copies them at the block's
|
||||
* end and the file stager reads them, through the address the last pass reported, at the
|
||||
* layer's first expert op. */
|
||||
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }, RAD_BUF_PERSIST);
|
||||
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
|
||||
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
|
||||
// FE: the routed experts' WHOLE intermediate (2048). Under expert parallelism a rank owns
|
||||
// whole experts, so the routed arm's buffers are full-width at every world size; the SHARED
|
||||
// expert stays width-sharded (F). The two coincide at world 1.
|
||||
const int64_t FE = 2048;
|
||||
// FE: the routed experts' intermediate. Under expert parallelism a rank owns whole experts,
|
||||
// so the routed arm's buffers are full-width (2048); split by width they are F. The SHARED
|
||||
// expert stays width-sharded (F) either way. The two coincide at world 1.
|
||||
const int64_t FE = m.whole_experts ? 2048 : F;
|
||||
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * FE });
|
||||
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, FE });
|
||||
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", FE, T * 8));
|
||||
@@ -266,7 +295,8 @@ static int kv_groups(RadBuilder* b, Model& m) {
|
||||
auto& nm = m.nm;
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
// bf16, or E4M3 under --kv-cache-dtype fp8 (geometry); the other groups keep their own.
|
||||
d.dtype = rad_dtype_parse(g.kv_dtype);
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = 256;
|
||||
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
|
||||
@@ -373,14 +403,19 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
// degenerates to the old whole-model declaration (n_expert == n_expert_all, no spans).
|
||||
s.cfg.n_expert_all = 288;
|
||||
s.cfg.top_k = 8;
|
||||
s.cfg.n_expert = 288 / g.world;
|
||||
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
|
||||
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
s.cfg.expert_base = ep_rank * (288 / g.world);
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
s.cfg.n_ff_shared = 2048 / g.world;
|
||||
s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
|
||||
if (m.whole_experts) {
|
||||
s.cfg.n_expert = 288 / g.world;
|
||||
// A shape probe may pass rank >= world (arch_test's parallel declares reuse i % 4);
|
||||
// old code tolerated that because expert_base stayed 0, so clamp to rank 0's window.
|
||||
const int ep_rank = g.rank < g.world ? g.rank : 0;
|
||||
s.cfg.expert_base = ep_rank * (288 / g.world);
|
||||
s.cfg.probed_expert = s.cfg.expert_base; // probe this rank's first owned expert
|
||||
s.cfg.n_ff_exp = 2048; // whole: whole experts' intermediate
|
||||
} else {
|
||||
s.cfg.n_expert = 288;
|
||||
s.cfg.n_ff_exp = GlmTp::expert_width(g.world);
|
||||
}
|
||||
s.cfg.rows = g.max_tok;
|
||||
s.cfg.sigmoid_router = 1;
|
||||
s.cfg.route_scale = 2.5;
|
||||
@@ -389,12 +424,12 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
s.cfg.router_fuse = 1;
|
||||
s.cfg.swiglu_quant = 1;
|
||||
// At world 1 the width-slice declaration IS the whole model: keep the spans so the
|
||||
// graph stays the pinned one. At world > 1 expert parallelism is in force and whole
|
||||
// experts need no width spans (split && ep is refused by the helper).
|
||||
if (g.world == 1) {
|
||||
// graph stays the pinned one. Whole experts need no width spans (split && ep is refused
|
||||
// by the helper).
|
||||
if (!m.whole_experts) {
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
s.cfg.ff_lo[q] = g.rank * (2048 / g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world);
|
||||
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
|
||||
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
|
||||
@@ -430,6 +465,9 @@ static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, i
|
||||
g.max_logit_rows = std::min<int64_t>(g.max_tok, g.max_seqs * (g.max_spec + 1));
|
||||
if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows;
|
||||
g.eps = meta->rms_eps;
|
||||
/* --kv-cache-dtype names the latent cache's dtype only (kv_groups); declare refuses all but
|
||||
* bf16 and fp8. */
|
||||
g.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16));
|
||||
g.wire_exact = !ctx->tp_wire_lossy;
|
||||
g.wire_min_bytes = ctx->tp_wire_min_bytes;
|
||||
return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK;
|
||||
@@ -468,11 +506,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent "
|
||||
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so "
|
||||
"run it with --kv-cache-dtype bf16\n",
|
||||
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype));
|
||||
/* fp8 narrows the latent attention cache to E4M3 at a descale of 1 (kv_groups); the index
|
||||
* tail, the DSA index and the KDA caches keep their dtypes. */
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_F8E4M3) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin serves its latent "
|
||||
"attention cache in bf16 or fp8 only\n",
|
||||
rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
@@ -483,6 +522,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
m.whole_experts = world == 2 || (world > 2 && (ctx->expert_file_tier ||
|
||||
!experts_are_mxfp4(b, nm)));
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
RAD_ARCH_TRY(mla_buffers(b, m));
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/hunyuan3d2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(hunyuan3d2 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(hunyuan3d2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/hunyuan3d2.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(nemotronh LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
rad_add_plugin(nemotronh architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/nemotronh.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,348 @@
|
||||
/* radio.h -- Nemotron-H Omni's vision encoder: C-RADIO (v4-H) and the projector after it (mlp1).
|
||||
*
|
||||
* Per encoder pass (RadBatch::enc). The processor (core/mm, Family::Radio) gives every segment
|
||||
* `n_prefix` zero rows ahead of its patches, with coordinate (-1, k):
|
||||
*
|
||||
* x = rows @ W^T one GEMM for both projections: a row is a
|
||||
* tubelet's frames then a picture's patch, the part
|
||||
* not in use zero, and W = [video_embedder |
|
||||
* embedder] concatenated at convert; no bias
|
||||
* x += CPE(table, row, col), or prefix[k] grid_embed_cpe: the 128 x 128 table resampled
|
||||
* half-pixel bilinear onto a square of the grid's
|
||||
* longer side and cropped to it; a prefix row takes
|
||||
* the k-th class or register token
|
||||
* depth times (pre-norm, LayerScale 1):
|
||||
* x += proj(attn(qkv(LN1(x)))) full attention within a segment, no rotary
|
||||
* x += fc2(gelu(fc1(LN2(x)))) exact GELU
|
||||
* y = each segment's patch rows gather_rows: the prefix rows dropped
|
||||
* out = l2(relu(l1(rms(y viewed [P/4, 4 * width])))^2)
|
||||
*
|
||||
* which is transformers' RadioModel (make_preprocessor_external) then NemotronH_Omni's vision
|
||||
* projector with vision_final_layernorm off. The pixel shuffle (ps v2) is the view: the processor
|
||||
* keeps a 2 x 2 block's patches consecutive, (dy, dx), the order the shuffle concatenates them;
|
||||
* the tower is order-independent within a segment (attention is permutation-equivariant, every
|
||||
* other layer is per row, the position term is sampled at each row's own coordinate).
|
||||
*
|
||||
* A pass is one grid (RadEncoderDecl::one_grid), so its segments are equally long and each
|
||||
* segment's patch rows sit at a fixed offset, which `step` gathers with slices of one identity
|
||||
* index. Replicated, per-request weights and pass-sized activations, as in
|
||||
* arch/common/rad_block_vit.h's tower.
|
||||
*/
|
||||
#ifndef NEMOTRONH_RADIO_H
|
||||
#define NEMOTRONH_RADIO_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace nemotronh {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Radio {
|
||||
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0, npre = 0;
|
||||
int64_t tubelet = 0, head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0, R = 0;
|
||||
float eps = 1e-6f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
|
||||
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, w_pos = 0, w_pre = 0, mn_w = 0, m1_w = 0, m2_w = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_seq = 0, op_gather = 0, op_mln = 0, op_m1 = 0;
|
||||
rad_op op_act = 0, op_m2 = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_seq = 0, b_g = 0, b_mn = 0;
|
||||
rad_buf b_mf = 0, b_ma = 0, b_out = 0;
|
||||
|
||||
/* A tower to declare: the container is a Nemotron-H Omni one, whose vision_config is RADIO's. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "radio") &&
|
||||
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int Radio::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group) {
|
||||
on = false;
|
||||
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
|
||||
|
||||
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
|
||||
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
|
||||
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
|
||||
ff = (int64_t)std::llround(rad_meta_getf(m, "vision_config.mlp_ratio", 0.0) * (double)width);
|
||||
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
|
||||
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
|
||||
side = rad_meta_geti(m, "vision_config.max_img_size", 0) / (patch > 0 ? patch : 1);
|
||||
npre = rad_meta_geti(m, "vision_config.num_cls_tokens", 0) +
|
||||
rad_meta_geti(m, "vision_config.num_registers", 0);
|
||||
tubelet = rad_meta_geti(m, "vision_config.video_temporal_patch_size",
|
||||
rad_meta_geti(m, "video_temporal_patch_size", 0));
|
||||
const double ratio = rad_meta_getf(m, "downsample_ratio", 0.0);
|
||||
merge = ratio > 0.0 ? (int64_t)std::llround(1.0 / ratio) : 0;
|
||||
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
|
||||
n_embd = model_embd;
|
||||
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
|
||||
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || side <= 0 ||
|
||||
npre <= 0 || tubelet <= 0 || merge <= 0 || proj_hidden <= 0 || width % heads ||
|
||||
chans != 3) {
|
||||
fprintf(stderr, "radiance: nemotronh: the container's RADIO vision_config is incomplete or "
|
||||
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
|
||||
"table %lld, prefix %lld, tubelet %lld, merge %lld, projector %lld)\n",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)ff,
|
||||
(long long)patch, (long long)side, (long long)npre, (long long)tubelet,
|
||||
(long long)merge, (long long)proj_hidden);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* What this tower serves of RADIO's options: the plain GELU MLP, LayerScale 1 (no stored
|
||||
* scales), q/k/v with biases, and no final layer norm before the projector. */
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu");
|
||||
const bool swiglu = rad_meta_geti(m, "vision_config.use_swiglu_ffn", 0) != 0 ||
|
||||
!std::strcmp(rad_meta_gets(m, "vision_config.use_swiglu_ffn", ""), "true");
|
||||
const bool final_ln = rad_meta_geti(m, "vision_final_layernorm", 0) != 0 ||
|
||||
!std::strcmp(rad_meta_gets(m, "vision_final_layernorm", ""), "true");
|
||||
if (std::strcmp(act, "gelu") || swiglu || final_ln ||
|
||||
rad_meta_getf(m, "vision_config.layerscale_value", 1.0) != 1.0) {
|
||||
fprintf(stderr, "radiance: nemotronh: this RADIO tower (activation '%s'%s%s, layer scale "
|
||||
"%g) is not the one served: GELU MLP, layer scale 1, no final layer norm\n",
|
||||
act, swiglu ? ", SwiGLU" : "", final_ln ? ", final layer norm" : "",
|
||||
rad_meta_getf(m, "vision_config.layerscale_value", 1.0));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
head_dim = width / heads;
|
||||
const int64_t pp = chans * patch * patch;
|
||||
patch_dim = pp * (1 + tubelet);
|
||||
const int64_t mm = merge * merge, mw = mm * width;
|
||||
|
||||
/* A pass's rows, prefix rows included; the output rows are at most a quarter of them. */
|
||||
P = ctx->max_enc_patches;
|
||||
const int64_t max_seg = P;
|
||||
if (ctx->shape_probe) {
|
||||
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
|
||||
P = std::max<int64_t>(mm, r / mm * mm);
|
||||
}
|
||||
R = P / mm;
|
||||
if (R <= 0) return RAD_E_SHAPE;
|
||||
const int ACC = RAD_ACCESS_PER_REQUEST;
|
||||
|
||||
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
const char* pg = "vision_model.radio_model.model.patch_generator.";
|
||||
/* [video_embedder | embedder] along K: one GEMM for a row of either kind. */
|
||||
if (map_concat(b, nm.f("v.patch.weight"),
|
||||
{ nm.ckpt("%svideo_embedder.weight", pg), nm.ckpt("%sembedder.weight", pg) },
|
||||
1) < 0)
|
||||
return RAD_E_INVAL;
|
||||
/* Whether the tower is here at all: its stem's encoding, which convert answers from the
|
||||
* checkpoint and load from the container alike. A text-only cut (a few blocks for a host
|
||||
* reference) or a container converted without it serves text; the map left behind is inert. */
|
||||
{
|
||||
RadEncoding enc;
|
||||
if (rad_weight_encoding(b, nm.f("v.patch.weight"), &enc, nullptr, nullptr) != RAD_OK) {
|
||||
rad_note(b, "nemotronh: vision_config names a RADIO tower its weights are not here "
|
||||
"for; serving text");
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
w_patch = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, { width, patch_dim }, ACC,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
/* The checkpoint's [1, side * side, width] read as the [side * side, width] table. */
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%spos_embed", pg), { side * side, width }, grp_model());
|
||||
w_pre = bw(nm.f("v.prefix.weight"), nm.ckpt("%scls_token.token", pg), { npre, width },
|
||||
grp_model());
|
||||
L.assign((size_t)depth, Layer{});
|
||||
for (int64_t i = 0; i < depth; ++i) {
|
||||
Layer& l = L[(size_t)i];
|
||||
const RadWeightGroup g = grp_layer(first_group + (int)i);
|
||||
const int li = (int)i;
|
||||
const char* e = "vision_model.radio_model.model.blocks.%d.%s";
|
||||
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, li, "norm1.weight"), { width }, g);
|
||||
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, li, "norm1.bias"), { width }, g);
|
||||
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt(e, li, "attn.qkv.weight"), { 3 * width, width }, g);
|
||||
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt(e, li, "attn.qkv.bias"), { 3 * width }, g);
|
||||
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, li, "attn.proj.weight"), { width, width }, g);
|
||||
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, li, "attn.proj.bias"), { width }, g);
|
||||
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, li, "norm2.weight"), { width }, g);
|
||||
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, li, "norm2.bias"), { width }, g);
|
||||
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, li, "mlp.fc1.weight"), { ff, width }, g);
|
||||
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, li, "mlp.fc1.bias"), { ff }, g);
|
||||
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, li, "mlp.fc2.weight"), { width, ff }, g);
|
||||
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, li, "mlp.fc2.bias"), { width }, g);
|
||||
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
|
||||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("mlp1.0.weight"), { mw }, grp_model());
|
||||
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("mlp1.1.weight"), { proj_hidden, mw }, grp_model());
|
||||
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("mlp1.3.weight"), { n_embd, proj_hidden }, grp_model());
|
||||
if (!w_patch || !w_pos || !w_pre || !mn_w || !m1_w || !m2_w) return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `g` holds the gathered patch rows at `width` and is read by the norm as
|
||||
* R rows of mm * width (the pixel shuffle's view, no copy). */
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
|
||||
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
|
||||
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
|
||||
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
|
||||
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_seq = decl_b(b, nm.f("v.seq"), RAD_I32, { P });
|
||||
b_g = decl_b(b, nm.f("v.g"), RAD_BF16, { R, mw });
|
||||
b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
|
||||
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
|
||||
b_ma = decl_b(b, nm.f("v.ma"), RAD_BF16, { R, proj_hidden });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_seq || !b_g || !b_mn || !b_mf || !b_ma ||
|
||||
!b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
|
||||
op_patch = rw(b, gemm(P, width, patch_dim, w_patch), {}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed_cpe",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_INT("n_prefix", npre),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos, w_pre)),
|
||||
{ b_x }, { b_x });
|
||||
op_seq = rw(b, RAD_OP(b, "iota",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("start", 0), RAD_INT("step", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, { b_seq });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h });
|
||||
l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
l.attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
|
||||
RAD_INT("max_seqlen", max_seg)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv }, { b_att });
|
||||
l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
|
||||
l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h });
|
||||
l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
|
||||
}
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_x, b_seq }, { b_g });
|
||||
op_mln = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", mw), RAD_F64("eps", 1e-5),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(mn_w)),
|
||||
{ b_g }, { b_mn });
|
||||
op_m1 = rw(b, gemm(R, proj_hidden, mw, m1_w), { b_mn }, { b_mf });
|
||||
/* relu(x)^2: act_mul's "relu" with the one tensor in both operands. */
|
||||
op_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_hidden),
|
||||
RAD_STR("act", "relu"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_mf }, { b_ma });
|
||||
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, m2_w), { b_ma }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
e.one_grid = 1;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "RADIO tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld "
|
||||
"(tubelet %lld), %lld x %lld position table, %lld prefix rows; projector %lld "
|
||||
"-> %lld -> %lld; %lld rows a pass",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
|
||||
(long long)ff, (long long)patch, (long long)tubelet, (long long)side,
|
||||
(long long)side, (long long)npre, (long long)mw, (long long)proj_hidden,
|
||||
(long long)n_embd, (long long)P);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void Radio::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
|
||||
const int64_t mm = merge * merge;
|
||||
const int64_t gh = S > 0 && batch->enc_seg_h ? batch->enc_seg_h[0] : 0;
|
||||
const int64_t gw = S > 0 && batch->enc_seg_w ? batch->enc_seg_w[0] : 0;
|
||||
const int64_t seg = npre + gh * gw, Rn = S * gh * gw / (mm > 0 ? mm : 1);
|
||||
if (!on || Pn <= 0 || Pn > P || S <= 0 || gh <= 0 || gw <= 0 || (gh * gw) % mm ||
|
||||
S * seg != Pn || Rn > R) {
|
||||
rad_step_fail(c, "nemotronh: an encoder pass this program's RADIO tower cannot serve: no "
|
||||
"tower, more rows than it was declared for, or segments that are not one "
|
||||
"grid of whole merged rows behind their prefix rows");
|
||||
return;
|
||||
}
|
||||
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
|
||||
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd, RAD_W(w_pre));
|
||||
RAD_ISSUE_N(c, op_seq, Pn, brows(b_seq, Pn));
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.attn, Pn,
|
||||
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_x, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_x, Pn), brows(b_x, Pn));
|
||||
}
|
||||
/* Each segment's patch rows, behind its prefix rows, into `g` at width: segment s's are rows
|
||||
* [s * seg + npre, (s + 1) * seg) of x, which the identity index names by a slice. */
|
||||
const int64_t hw = gh * gw;
|
||||
for (int64_t s = 0; s < S; ++s)
|
||||
RAD_ISSUE_N(c, op_gather, hw, brows(b_x, Pn), brow_slice(b_seq, s * seg + npre, hw, 1),
|
||||
brow_slice(b_g, s * hw / mm, hw / mm, mm * width));
|
||||
RAD_ISSUE_N(c, op_mln, Rn, brows(b_g, Rn), RAD_W(mn_w), brows(b_mn, Rn));
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mn, Rn), RAD_W(m1_w), brows(b_mf, Rn));
|
||||
RAD_ISSUE_N(c, op_act, Rn, brows(b_mf, Rn), brows(b_mf, Rn), brows(b_ma, Rn));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_ma, Rn), RAD_W(m2_w), brows(b_out, Rn));
|
||||
}
|
||||
|
||||
} /* namespace nemotronh */
|
||||
|
||||
#endif /* NEMOTRONH_RADIO_H */
|
||||
+137
-17
@@ -80,6 +80,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_attn_gated_fp8.h>
|
||||
#include <arch/rad_block_gdn_fp8.h>
|
||||
#include <arch/rad_calib_full.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#if QWEN35_MOE
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
@@ -134,6 +135,9 @@ struct Layer {
|
||||
* beside the feed-forward's; 0 where none is declared. */
|
||||
rad_op op_pf_gu = 0, op_pf_next = 0;
|
||||
rad_weight pf_gu_w = 0, pf_next_w = 0;
|
||||
/* The layer's calibration inputs (rad_calib_full.h, site_i8), -1 where this run does not record
|
||||
* it: the mixer's input and its output projection's, the feed-forward's and its down's. */
|
||||
int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -208,6 +212,12 @@ struct Model {
|
||||
rad_op op_tap = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
/* A vocabulary-weighted head (logits_gemm_vocab): its width classes' codes, scales and rows'
|
||||
* vocabulary ids, and this rank's rows of each. */
|
||||
enum { MAX_VCLS = 4 };
|
||||
int n_vcls = 0;
|
||||
rad_weight w_vw[MAX_VCLS] = {}, w_vs[MAX_VCLS] = {}, w_vi[MAX_VCLS] = {}, w_vrow = 0;
|
||||
int64_t vcls_rows[MAX_VCLS] = {};
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0;
|
||||
/* Set by a plugin built over this one whose head answers a request from its words
|
||||
* (RadBatch::plugin_words): a `fill` of the logits rows that plugin declared. A step every
|
||||
@@ -224,6 +234,7 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
CalibFull calib; /* --calib-dir over an int8 trunk (rad_calib_full.h) */
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
|
||||
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
|
||||
@@ -871,6 +882,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")))
|
||||
m.a_h.q8_fed = m.a_h.q8_rot = true;
|
||||
if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true;
|
||||
/* The delta net's output likewise, from the decode conv fold's epilogue
|
||||
* (gdn_conv_recurrent_update_had) and had_quant_act_i8g on the other rows (GdnFP8::q_o). */
|
||||
if (rad_op_declared(b, "gdn_conv_recurrent_update_had") && rad_op_declared(b, "had_quant_act_i8g"))
|
||||
m.a_go.q8_fed = m.a_go.q8_rot = true;
|
||||
/* And the gated attention's output, from its gate (gate_had_quant_i8g). */
|
||||
if (rad_op_declared(b, "gate_had_quant_i8g") && rad_op_declared(b, "had_quant_act_i8g"))
|
||||
m.a_attn.q8_fed = m.a_attn.q8_rot = true;
|
||||
#endif
|
||||
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
@@ -929,10 +947,45 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
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());
|
||||
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
|
||||
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());
|
||||
/* A vocabulary-weighted head, where the model holds one in place of output.weight: the rows
|
||||
* sorted by their token's probability into classes of one computed-trellis width each,
|
||||
* `output.k<B>.weight`, with `output.k<B>.ids` [rows, 1] each row's vocabulary id, and
|
||||
* `output.vrow` [n_vocab, 1] the inverse (each id's class width and row). Each class is
|
||||
* row-sharded like any lm_head, the converter keeping an id's row among its rank's rows
|
||||
* (libr4d's logits_gemm_vocab). */
|
||||
for (int B = 7; B >= 2; --B) {
|
||||
const char* wn = nm.f("output.k%d.weight", B);
|
||||
RAD_ARCH_TRY(map_copy(b, wn, nm.ckpt("lm_head.k%d.weight", B)));
|
||||
RadEncoding e{};
|
||||
int64_t shp[RAD_MAX_RANK] = {};
|
||||
if (rad_weight_encoding(b, wn, &e, shp, nullptr) != RAD_OK) continue;
|
||||
if (m.n_vcls == Model::MAX_VCLS || shp[0] % (256 * g.world) || shp[1] != g.n_embd) {
|
||||
fprintf(stderr, "radiance: '%s' is not a head class this build reads (at most %d "
|
||||
"classes, rows a multiple of 256 a rank)\n", wn, (int)Model::MAX_VCLS);
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
const int64_t n = shp[0] / g.world;
|
||||
const int k = m.n_vcls++;
|
||||
m.w_vw[k] = decl_view(b, wn, nullptr, "codes,trellis,trellis.mad", e.plane[0].dtype,
|
||||
{n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_vs[k] = decl_view(b, nm.f("output.k%d.scale", B), wn,
|
||||
rad_enc_plane(&e, "scale.col") ? "scale,scale.col" : "scale",
|
||||
RAD_F32, {n, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
const char* in = nm.f("output.k%d.ids", B);
|
||||
RAD_ARCH_TRY(map_copy(b, in, nm.ckpt("lm_head.k%d.ids", B)));
|
||||
m.w_vi[k] = decl_w(b, in, RAD_I32, {n, 1}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.vcls_rows[k] = n;
|
||||
}
|
||||
if (m.n_vcls) {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output.vrow"), nm.ckpt("lm_head.vrow")));
|
||||
m.w_vrow = decl_w(b, nm.f("output.vrow"), RAD_I32, {g.n_vocab, 1}, RAD_ACCESS_VOCAB,
|
||||
RAD_SHARD_ROW, grp_model());
|
||||
} else {
|
||||
/* Row-sharded with the vocabulary: g.n_vocab is this rank's share (rad_arch.h). */
|
||||
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),
|
||||
@@ -1028,6 +1081,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* unfolded: it is a separate chain over its own residual buffer and saves only two launches a
|
||||
* step. */
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
#if !QWEN35_MOE
|
||||
/* GPTQ calibration over the trunk's own int8 codes (rad_calib_full.h, site_i8): one rank, the
|
||||
* serial step. The scratch is the widest input's square, the feed-forward's. */
|
||||
if (ctx->calib_dir && *ctx->calib_dir && g.world > 1) {
|
||||
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk at --tp 1 only\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, m.n_main, 0, std::max<int64_t>(g.n_ff, g.n_embd)));
|
||||
#endif
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
@@ -1093,6 +1155,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
#endif
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add,
|
||||
f.mlp_ar_in, f.mlp_ar_out));
|
||||
#if !QWEN35_MOE
|
||||
if (m.calib.records(l)) {
|
||||
/* The codes each int8 GEMM reads, in the domain its weight is stored in (i8_rot). */
|
||||
const ActFP8& ao = lay.full ? m.a_attn : m.a_go;
|
||||
const LinearFP8& li = lay.full ? lay.attn.qg : lay.gdn.in;
|
||||
const LinearFP8& lo = lay.full ? lay.attn.o : lay.gdn.out;
|
||||
if (!m.a_h.q8 || !ao.q8 || !m.a_ffn.q8 || !lay.mlp.gate_up.i8 || !lo.i8) {
|
||||
fprintf(stderr, "radiance: qwen35: --calib-dir records an int8 trunk; layer %lld "
|
||||
"is not one\n", (long long)l);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto dom = [](const LinearFP8& w) { return w.i8_rot ? (uint32_t)RAD_FP8_BLOCK : 0u; };
|
||||
const std::string L = "model.language_model.layers." + std::to_string(l);
|
||||
const std::string mix = L + (lay.full ? ".self_attn" : ".linear_attn");
|
||||
const std::string op = lay.full ? ".o_proj" : ".out_proj";
|
||||
lay.cs_in = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".input", mix, m.a_h.q8, m.a_h.s8, g.n_embd,
|
||||
dom(li)));
|
||||
lay.cs_o = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, mix + op + ".input", mix + op, ao.q8, ao.s8, lo.K,
|
||||
dom(lo)));
|
||||
lay.cs_mlp = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".post_attention.input",
|
||||
L + ".mlp.gate_proj," + L + ".mlp.up_proj", m.a_h.q8,
|
||||
m.a_h.s8, g.n_embd, dom(lay.mlp.gate_up)));
|
||||
lay.cs_down = (int)m.calib.sites.size();
|
||||
RAD_ARCH_TRY(m.calib.site_i8(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj",
|
||||
m.a_ffn.q8, m.a_ffn.s8, g.n_ff, dom(lay.mlp.down)));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#if QWEN35_MOE
|
||||
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
|
||||
@@ -1136,12 +1228,22 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.a_h.x}, {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});
|
||||
m.op_logits = m.n_vcls
|
||||
? rw(b, RAD_OP(b, "logits_gemm_vocab",
|
||||
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_INT("vocab_offset", g.vocab_off),
|
||||
RAD_INT("rows0", m.vcls_rows[0]), RAD_INT("rows1", m.vcls_rows[1]),
|
||||
RAD_INT("rows2", m.vcls_rows[2]), RAD_INT("rows3", m.vcls_rows[3])),
|
||||
RAD_WEIGHTS(m.w_vw[0], m.w_vs[0], m.w_vi[0], m.w_vw[1], m.w_vs[1], m.w_vi[1],
|
||||
m.w_vw[2], m.w_vs[2], m.w_vi[2], m.w_vw[3], m.w_vs[3], m.w_vi[3],
|
||||
m.w_vrow)),
|
||||
{m.b_hout}, {m.b_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});
|
||||
|
||||
/* ---- the multi-token-prediction head (rad_block_mtp_fp8.h).
|
||||
*
|
||||
@@ -1151,7 +1253,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
*
|
||||
* Also only when there is no DFlash2 drafter (`n_taps` == 0): a deployment drafts with one,
|
||||
* and DFlash2 (one forward per block rather than one per token) is the better one here. */
|
||||
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0) {
|
||||
/* (A vocabulary-weighted head has no output.weight for the draft head to read.) */
|
||||
if (nextn > 0 && g.max_spec > 0 && m.n_taps == 0 && !m.n_vcls) {
|
||||
/* Sized at max_tok, not max_logit_rows: a draft round is one row per sequence, but the
|
||||
* history pass that fills the head's own K and V is one row per token over a whole prefill
|
||||
* chunk (26 MiB at a 512-token chunk, beside 477 MiB of head weights). */
|
||||
@@ -1321,6 +1424,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The lm_head over the gathered rows: the one weight, or a vocabulary-weighted head's classes. */
|
||||
static void issue_logits(RadCtx* c, const Model& m, int n) {
|
||||
if (!m.n_vcls) {
|
||||
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, n));
|
||||
return;
|
||||
}
|
||||
auto w = [](rad_weight h) { return h ? RAD_W(h) : RAD_NONE; };
|
||||
RAD_ISSUE_N(c, m.op_logits, n, brows(m.b_hout, n), w(m.w_vw[0]), w(m.w_vs[0]), w(m.w_vi[0]),
|
||||
w(m.w_vw[1]), w(m.w_vs[1]), w(m.w_vi[1]), w(m.w_vw[2]), w(m.w_vs[2]), w(m.w_vi[2]),
|
||||
w(m.w_vw[3]), w(m.w_vs[3]), w(m.w_vi[3]), RAD_W(m.w_vrow), brows(m.b_logits, n));
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
@@ -1547,9 +1663,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.a_h.x, T), 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));
|
||||
issue_logits(c, m, batch->n_out);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1628,9 +1742,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
if (l.full) l.attn.step(c, batch);
|
||||
else l.gdn.step(c, batch);
|
||||
/* The calibration taps read the codes the block's GEMMs just read, before the next block's
|
||||
* norm rewrites the shared input planes. */
|
||||
if (l.cs_in >= 0) m.calib.tap(c, (size_t)l.cs_in, batch->n_tok);
|
||||
if (l.cs_o >= 0) m.calib.tap(c, (size_t)l.cs_o, batch->n_tok);
|
||||
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
|
||||
dbg_resid(c, (int)li, "mix", m.g.n_embd, m.b_x, m.a_h.x);
|
||||
l.mlp.step(c, batch);
|
||||
if (l.cs_mlp >= 0) m.calib.tap(c, (size_t)l.cs_mlp, batch->n_tok);
|
||||
if (l.cs_down >= 0) m.calib.tap(c, (size_t)l.cs_down, batch->n_tok);
|
||||
prefetch_beside(c, l.op_pf_next, l.pf_next_w, pf_h);
|
||||
dbg_resid(c, (int)li, "ffn", m.g.n_embd, m.b_x, m.a_h.x);
|
||||
|
||||
@@ -1643,6 +1763,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
}
|
||||
}
|
||||
|
||||
m.calib.after_step(c, batch->n_tok);
|
||||
|
||||
RAD_ISSUE(c, m.op_final_norm,
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.a_h.x, batch->n_tok));
|
||||
|
||||
@@ -1655,9 +1777,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
brows(m.a_h.x, 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));
|
||||
issue_logits(c, m, batch->n_out);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <rad_prefill_split.h>
|
||||
#include <arch/rad_block_attn_gated_fp8.h>
|
||||
#include <arch/rad_block_gdn_fp8.h>
|
||||
#include <arch/rad_block_hc.h>
|
||||
@@ -1696,6 +1697,72 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
* acceptance stays high at every depth, but each extra verify row costs real time because the
|
||||
* weights do not fit device memory (more experts streamed, more n-gram rows faulted from the
|
||||
* mapped table). */
|
||||
uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
if (batch->enc) return 1;
|
||||
/* Mixed batches split the query rows into decode and prefill subsets before attention; the
|
||||
* whole-batch host summary cannot key those subset geometries exactly. */
|
||||
if (batch->phase == RAD_PHASE_MIXED) return 0;
|
||||
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
/* Decode, verify and draft passes (the MTP head attends over the same KV group): every
|
||||
* attention launch covers all the pass's sequences, and the shape fields the core keys (n_tok,
|
||||
* n_seq, max_q_len, n_spec, draft_pass) fix each launch's q_len band and units. The live KV
|
||||
* length enters a split launcher's count only through the cap of eight 48-key tiles a split
|
||||
* (rad_prefill_splits_law; every head_dim 256 launcher has P_TILE 48), and from 64 splits up
|
||||
* the cap no longer binds. Keying that cap level lets these passes be recorded while each launch
|
||||
* still splits by its exact live length: answering 0 left them unrecorded (issue #402), and the
|
||||
* core's keyed bound for a plugin without the callback rounds the length up a bucket, which split
|
||||
* a short single-stream verify into several partials with a merge (x1 203 against 219 tok/s). */
|
||||
if (batch->phase != RAD_PHASE_PREFILL || batch->draft_pass != 0 || batch->n_spec > 0) {
|
||||
if (!m.kv_full || !used_max_h || !batch->kv) return 0;
|
||||
int group = -1;
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv_full) { group = i; break; }
|
||||
if (group < 0) return 2; // no full-attention KV in this pass: nothing splits by length
|
||||
const int used = used_max_h[group];
|
||||
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
|
||||
constexpr int tile = 48;
|
||||
const int ctx = (m.g.max_ctx > 0 && used >= m.g.max_ctx) ? (int)m.g.max_ctx : used;
|
||||
const int cap = std::min(((ctx + tile - 1) / tile) / 8, 64);
|
||||
return 3 + (uint64_t)cap;
|
||||
}
|
||||
|
||||
bool has_full_attention = false;
|
||||
for (const Layer& layer : m.layers) {
|
||||
if (!layer.full) continue;
|
||||
if (layer.attn.kv_block != 4) return 0;
|
||||
has_full_attention = true;
|
||||
}
|
||||
if (!has_full_attention) return 1;
|
||||
if (m.g.head_dim != 256 || (m.g.gqa() != 6 && m.g.gqa() != 12) || !m.kv_full ||
|
||||
!used_max_h || !batch->kv || batch->n_kv_groups <= 0)
|
||||
return 0;
|
||||
|
||||
int group = -1;
|
||||
for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv_full) { group = i; break; }
|
||||
if (group < 0) return 0;
|
||||
|
||||
/* Qwen always passes cu_seqlens, so fill_paged takes q_len = min(band, total_q). That equals
|
||||
* n_tok only for one sequence; a ragged or multi-sequence launch's band is not the host group
|
||||
* max, and mixed decode-prefix / prefill-suffix launches use the suffix's own KV lengths. */
|
||||
if (batch->n_seq != 1 || batch->n_tok <= 0 || m.g.max_ctx <= 0) return 0;
|
||||
const int q_len = (int)batch->n_tok;
|
||||
const int total_q = (int)batch->n_tok;
|
||||
const int num_seqs = 1;
|
||||
const int kv_heads = (int)m.g.n_head_kv;
|
||||
const int used = used_max_h[group];
|
||||
if (used <= 0) return 0; // Missing host summary is not the same as an empty KV cache.
|
||||
const int wgps = rad_ctx_wgp_count(c);
|
||||
if (wgps <= 0) return 0;
|
||||
constexpr int tile = 48, nwarps = 24;
|
||||
const int bq = nwarps * 16 / m.g.gqa();
|
||||
const int splits = rad_prefill_splits_for_live(bq, tile, q_len, total_q, num_seqs,
|
||||
kv_heads, m.g.max_ctx, used, wgps);
|
||||
return rad_prefill_grid_key(q_len, bq, splits, kv_heads, num_seqs, nwarps * 32);
|
||||
}
|
||||
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
/* The gated attention block declares the streamed store and the resolve
|
||||
@@ -1717,6 +1784,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
}
|
||||
/* The gated residual applies a control vector after every block's write (HcProject). */
|
||||
out->control_vector_ok = 1;
|
||||
/* Chained launches pay with the MTP drafter: the speculative step's small kernels wait on the
|
||||
* previous one on the card instead of behind a queue barrier (libr4d/r4d_chain.h). On 2x R9700,
|
||||
* sampled at temperature 1 with a 25k prompt, MTP depth 3, with the chained hc_read forms:
|
||||
* 1/2/4/8/16 streams 174/291/458/657/851 -> 207/339/493/647/843 tok/s. */
|
||||
out->chain_pays = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1728,4 +1800,8 @@ RAD_ARCH_PLUGIN(qwen4exp_fp8, "qwen4exp", "", "0.1.0",
|
||||
"Qwen4-Exp (Qwen3.8-Flash-Next): hybrid Gated DeltaNet / gated attention, a gated "
|
||||
"residual four streams wide and 512 routed experts, from a dense bf16 checkpoint "
|
||||
"quantised ahead of time by a recipe")
|
||||
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
|
||||
const int32_t* used_max_h) {
|
||||
return qwen4exp_fp8::pass_key(c, batch, used_max_h);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in tree or against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(spark25_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(spark25_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spark25_bf16.cpp)
|
||||
@@ -0,0 +1,35 @@
|
||||
/* Spark's reply format: the checkpoint's template writes these tags around each call. */
|
||||
#pragma once
|
||||
#include "rad_builder.h"
|
||||
|
||||
namespace spark25_bf16 {
|
||||
|
||||
inline const RadChatFormat* spark_chat_format() {
|
||||
static const char* const breaks[] = {"<tool_call>"};
|
||||
static const char* const triggers[] = {"<tool_call>"};
|
||||
static const RadChatFormat f = [] {
|
||||
RadChatFormat x{};
|
||||
x.struct_size = sizeof(x);
|
||||
x.name = "plugin:spark25";
|
||||
x.reasoning_open = "<think>";
|
||||
x.reasoning_close = "</think>";
|
||||
x.reasoning_breaks = breaks;
|
||||
x.n_reasoning_breaks = 1;
|
||||
x.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT;
|
||||
/* There is no delimiter between the call opener and the function name. */
|
||||
x.name_prefix = "<tool_call>";
|
||||
x.call_end = "</tool_call>";
|
||||
x.arg_prefix = "<arg_key>";
|
||||
x.arg_name_suffix = "</arg_key>";
|
||||
x.arg_value_prefix = "<arg_value>";
|
||||
x.arg_value_suffix = "</arg_value>";
|
||||
x.string_value = RAD_CHAT_VALUE_RAW;
|
||||
x.other_value = RAD_CHAT_VALUE_JSON;
|
||||
x.triggers = triggers;
|
||||
x.n_triggers = 1;
|
||||
return x;
|
||||
}();
|
||||
return &f;
|
||||
}
|
||||
|
||||
} /* namespace spark25_bf16 */
|
||||
@@ -0,0 +1,626 @@
|
||||
/* Spark X2.6 (Spark2_5ForCausalLM), BF16 weights and activations.
|
||||
*
|
||||
* The checkpoint has one [q | k | v] projection per layer. Conversion splits its rows into
|
||||
* contiguous matrices because paged attention needs a contiguous query. The MLP's two matrices
|
||||
* are concatenated as [gate | up]; act_mul with exact erf GELU matches the reference, unlike
|
||||
* gelu_mul (which is the tanh approximation). The attention gate is one sigmoid per head, not
|
||||
* per channel. Local and full layers have different NeoX rotary dimensions and theta values.
|
||||
*
|
||||
* Tensor parallelism splits attention by whole KV groups, replicating KV heads when ranks
|
||||
* outnumber them. As in the HF reference, residuals accumulate in f32; rmsnorm reads that stream
|
||||
* and writes bf16 for the linear projections.
|
||||
*
|
||||
* A container built with `--draft-model` also carries a DSpark drafter, which reads the residual
|
||||
* stream after the trunk layers its config names and denoises a block of masked positions in one
|
||||
* pass. The trunk's part of that is the taps and the drafter pass dispatch (see
|
||||
* arch/rad_block_dspark_bf16.h for the drafter itself).
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dspark_bf16.h>
|
||||
#include "chat.h"
|
||||
#include "spark25_prefill_pass_key.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace spark25_bf16 {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
rad_kvgroup kv = 0;
|
||||
rad_weight an = 0, q = 0, k = 0, v = 0, gate = 0, o = 0, fn = 0, gu = 0, down = 0;
|
||||
rad_op anorm = 0, qp = 0, kp = 0, vp = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
|
||||
rad_op sigmoid = 0, gate_heads = 0, op = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
|
||||
rad_op fnorm = 0, gup = 0, act = 0, dp = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
|
||||
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
rad_kvgroup kv = 0;
|
||||
rad_buf x = 0, delta = 0, h = 0, q = 0, k = 0, v = 0, gate = 0, attn = 0, gu = 0, ff = 0;
|
||||
rad_buf hout = 0, logits = 0;
|
||||
rad_weight tok = 0, norm = 0, head = 0;
|
||||
rad_op embed = 0, widen = 0, reduce_embed = 0, final_norm = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
bool tap_live = false;
|
||||
long long calib_rows = 0;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
/* The drafter, declared only when the container carries one and this serve speculates. Its own
|
||||
* KV group holds the context it derived from the trunk's taps. */
|
||||
DsparkBF16 ds{};
|
||||
DsparkBF16::Wire dsw{};
|
||||
DsparkTaps taps{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
* than left unused: the container would serve at the speed of a model with no drafter, and the
|
||||
* user would have no way to find out that the flag they passed did nothing. */
|
||||
static int drafter_kind(const RadModelMeta* meta, bool* present) {
|
||||
*present = false;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (!da || !*da) {
|
||||
/* A drafter's config.json flattened, or a GGUF import, either of which names it. */
|
||||
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) <= 0) return RAD_OK;
|
||||
da = rad_meta_gets(meta, "draft.model_type", "");
|
||||
}
|
||||
if (std::strstr(da, "DSpark") || std::strcmp(da, "dspark") == 0) {
|
||||
*present = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
*present = true;
|
||||
fprintf(stderr, "radiance: spark25: this container carries a '%s' drafter. Spark's drafts are "
|
||||
"DSpark, with a rank-N Markov head over the target's own table; this "
|
||||
"architecture implements that and nothing else\n", da);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The HF config names every layer. Do not infer a periodic schedule: it changes the mask and
|
||||
* rotary of a layer and would silently produce a different model. */
|
||||
static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& local) {
|
||||
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
|
||||
if (!s) {
|
||||
fprintf(stderr, "radiance: spark25: layer_types is required\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::istringstream in(s);
|
||||
std::string word;
|
||||
while (in >> word) {
|
||||
if (word != "sliding_attention" && word != "full_attention") {
|
||||
fprintf(stderr, "radiance: spark25: unknown layer type '%s'\n", word.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
local.push_back(word == "sliding_attention");
|
||||
}
|
||||
if ((int64_t)local.size() != n) {
|
||||
fprintf(stderr, "radiance: spark25: layer_types has %zu entries for %lld layers\n",
|
||||
local.size(), (long long)n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
struct Span {
|
||||
int64_t first = 0, count = 0;
|
||||
};
|
||||
|
||||
/* Remainder-first contiguous slices, in whole units. */
|
||||
static Span split(int64_t n, int parts, int rank) {
|
||||
const int64_t base = n / parts, rem = n % parts;
|
||||
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
|
||||
}
|
||||
|
||||
struct Shards {
|
||||
Span q, kv, ff; /* q and kv in heads; ff in channels */
|
||||
};
|
||||
|
||||
/* A rank's attention heads must describe whole GQA groups, or a slice of a single group with
|
||||
* that group's KV head replicated. This also covers non-divisible worlds such as 3 ranks over
|
||||
* the checkpoint's 4 KV heads. Projection and FFN spans below give the loader those exact cuts. */
|
||||
static int shard_geometry(Geom& g, const RadBuildCtx* ctx, Shards& s) {
|
||||
g.world = ctx->world_size > 0 ? ctx->world_size : 1;
|
||||
g.rank = ctx->rank;
|
||||
if (g.rank >= g.world || g.world > g.n_head_all || g.n_head_kv_all <= 0 ||
|
||||
g.n_head_all % g.n_head_kv_all || g.world > g.n_ff_all) {
|
||||
fprintf(stderr, "radiance: spark25: cannot shard %lld query heads, %lld KV heads and "
|
||||
"%lld FFN channels over %d ranks\n", (long long)g.n_head_all,
|
||||
(long long)g.n_head_kv_all, (long long)g.n_ff_all, g.world);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t group = g.n_head_all / g.n_head_kv_all;
|
||||
if (g.world <= g.n_head_kv_all) {
|
||||
s.kv = split(g.n_head_kv_all, g.world, g.rank);
|
||||
s.q = {s.kv.first * group, s.kv.count * group};
|
||||
} else {
|
||||
int first_rank = 0;
|
||||
for (int64_t k = 0; k < g.n_head_kv_all; ++k) {
|
||||
const int n = (int)split(g.world, (int)g.n_head_kv_all, (int)k).count;
|
||||
if (g.rank < first_rank + n) {
|
||||
const Span q = split(group, n, g.rank - first_rank);
|
||||
s.kv = {k, 1};
|
||||
s.q = {k * group + q.first, q.count};
|
||||
break;
|
||||
}
|
||||
first_rank += n;
|
||||
}
|
||||
}
|
||||
/* Prefer whole 128-channel blocks for a ragged split, keeping device GEMMs aligned. */
|
||||
const int64_t unit = g.n_ff_all % 128 == 0 && g.n_ff_all / 128 >= g.world ? 128 : 1;
|
||||
s.ff = split(g.n_ff_all / unit, g.world, g.rank);
|
||||
s.ff.first *= unit;
|
||||
s.ff.count *= unit;
|
||||
g.n_head = s.q.count;
|
||||
g.n_head_kv = s.kv.count;
|
||||
g.n_ff = s.ff.count;
|
||||
g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank);
|
||||
g.vocab_off = shard_begin(g.n_vocab_all, g.world, g.rank);
|
||||
return g.n_head > 0 && g.n_head_kv > 0 && g.n_ff > 0 && g.n_vocab > 0 ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
static bool needs_span(const Span& s, int64_t total, const Geom& g) {
|
||||
return total % g.world != 0 || s.first != g.rank * (total / g.world) ||
|
||||
s.count != total / g.world;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
Model& m = models[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
* then give each rank a group-preserving shard and state its spans on the weights. */
|
||||
RadBuildCtx whole = *ctx;
|
||||
whole.rank = 0;
|
||||
whole.world_size = 1;
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, &whole, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Shards shards;
|
||||
RAD_ARCH_TRY(shard_geometry(g, ctx, shards));
|
||||
Names& nm = m.nm;
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2 || meta->n_expert ||
|
||||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "mlp_bias", 0) ||
|
||||
!rad_meta_geti(meta, "tie_word_embeddings", 0) ||
|
||||
!rad_meta_geti(meta, "headwise_attn_output_gate", 0) ||
|
||||
std::strcmp(rad_meta_gets(meta, "gate_attn_act_mode", "sigmoid"), "sigmoid") ||
|
||||
std::strcmp(rad_meta_gets(meta, "hidden_act", "gelu"), "gelu")) {
|
||||
fprintf(stderr, "radiance: spark25: requires a dense, bias-free, tied model with headwise "
|
||||
"sigmoid gates, exact GELU and divisible attention heads\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A single global override cannot describe this model's two rotary ladders. */
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
|
||||
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f || g.rope_mc) {
|
||||
fprintf(stderr, "radiance: spark25: rotary scaling overrides are not supported\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::vector<bool> local;
|
||||
RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
|
||||
if (calib_dir()) {
|
||||
if (g.world != 1) {
|
||||
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
|
||||
"Grams retain their cross terms\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
|
||||
&m.calib_lo, &m.calib_hi));
|
||||
m.tap_live = true;
|
||||
}
|
||||
const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
|
||||
if (window <= 0) {
|
||||
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
double theta[2]{};
|
||||
int64_t rot[2]{};
|
||||
const char* kinds[] = {"full_attention", "sliding_attention"};
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
theta[j] = rad_meta_getf(meta, nm.f("rope_parameters.%s.rope_theta", kinds[j]), 10000.0);
|
||||
const double factor = rad_meta_getf(meta,
|
||||
nm.f("rope_parameters.%s.partial_rotary_factor", kinds[j]), 1.0);
|
||||
const char* type = rad_meta_gets(meta, nm.f("rope_parameters.%s.rope_type", kinds[j]), "default");
|
||||
if (std::strcmp(type, "default")) {
|
||||
fprintf(stderr, "radiance: spark25: %s rotary type '%s' is not supported\n", kinds[j], type);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double r = g.head_dim * factor;
|
||||
if (!std::isfinite(theta[j]) || !(theta[j] > 0) || !(factor > 0 && factor <= 1) || !std::isfinite(r) ||
|
||||
std::floor(r) != r || (int64_t)r % 2) {
|
||||
fprintf(stderr, "radiance: spark25: invalid %s rotary theta %g or factor %g\n",
|
||||
kinds[j], theta[j], factor);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
rot[j] = (int64_t)r;
|
||||
}
|
||||
|
||||
/* A full cache for both kinds keeps prefix caching valid. The local attention op enforces
|
||||
* its own window (q - k < window); the full layers read all past positions. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
|
||||
if (!m.kv) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
|
||||
m.x = decl_b(b, nm.f("x"), RAD_F32, {T, E});
|
||||
m.delta = decl_b(b, nm.f("delta"), RAD_F32, {T, E});
|
||||
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.q = decl_b(b, nm.f("q"), RAD_BF16, {T, Q});
|
||||
m.k = decl_b(b, nm.f("k"), RAD_BF16, {T, K});
|
||||
m.v = decl_b(b, nm.f("v"), RAD_BF16, {T, K});
|
||||
m.gate = decl_b(b, nm.f("gate"), RAD_BF16, {T, g.n_head});
|
||||
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
|
||||
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
|
||||
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
|
||||
m.hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
if (!m.x || !m.delta || !m.h || !m.q || !m.k || !m.v || !m.gate || !m.attn || !m.gu || !m.ff ||
|
||||
!m.hout || !m.logits) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
/* ---- the drafter's taps, when the container carries a drafter and this serve speculates.
|
||||
* Declared before the layer loop because the stream outlives it: the drafter's context pass
|
||||
* runs after the trunk's, on the residual streams the trunk saved here. */
|
||||
bool drafter = false;
|
||||
RAD_ARCH_TRY(drafter_kind(meta, &drafter));
|
||||
if (drafter && ctx->max_spec > 0) {
|
||||
m.taps.read(meta, g.n_layer);
|
||||
if (m.taps.n <= 0) {
|
||||
fprintf(stderr, "radiance: spark25: the drafter names no trunk layer to read, or names "
|
||||
"only layers past this target's last (`draft.target_layer_ids`)\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.x));
|
||||
}
|
||||
|
||||
auto weight = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, RadWeightGroup group,
|
||||
int access = RAD_ACCESS_PER_TOKEN, int shard = RAD_SHARD_NONE) {
|
||||
if (map_copy(b, name, src) != RAD_OK) return (rad_weight)0;
|
||||
return decl_w(b, name, dt, shape, access, shard, group);
|
||||
};
|
||||
m.tok = weight(nm.f("token_embd.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
|
||||
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
|
||||
m.head = weight(nm.f("output.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
|
||||
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
|
||||
m.norm = weight(nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32,
|
||||
{E}, grp_model());
|
||||
if (!m.tok || !m.head || !m.norm) return RAD_E_INVAL;
|
||||
if (g.world > 1 && g.n_vocab_all % g.world) {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.tok, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.head, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
}
|
||||
|
||||
auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)), {x}, {y});
|
||||
};
|
||||
auto gemm = [&](int64_t n, int64_t k, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)), {x}, {y});
|
||||
};
|
||||
auto add = [&]() {
|
||||
return rw(b, RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.x, m.delta}, {m.x});
|
||||
};
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n_embd", E), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.tok)), {}, {m.h});
|
||||
auto widen = [&](rad_buf output) {
|
||||
return rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.h}, {output});
|
||||
};
|
||||
m.widen = widen(m.x);
|
||||
/* Embedding shards contribute disjoint rows, so their widened sum is exact. Projection
|
||||
* shards must instead reduce in bf16, rounding the merged output before it is widened and
|
||||
* added to the f32 residual, as in the reference's BF16 linear layers. */
|
||||
auto reduce = [&](rad_buf x, const char* dtype) {
|
||||
if (g.world <= 1) return (rad_op)0;
|
||||
return rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", E, T * E), RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS), {x}, {x});
|
||||
};
|
||||
m.reduce_embed = reduce(m.x, "fp32");
|
||||
if (g.world > 1 && !m.reduce_embed) {
|
||||
fprintf(stderr, "radiance: spark25 requires an exact fp32 all-reduce for TP=%d\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int l = 0; l < g.n_layer; ++l) {
|
||||
Layer& a = m.layers[(size_t)l];
|
||||
auto src = [&](const char* suffix) { return nm.ckpt("model.layers.%d.%s", l, suffix); };
|
||||
auto w = [&](const char* suffix, const char* s, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, int shard = RAD_SHARD_NONE) {
|
||||
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l),
|
||||
RAD_ACCESS_PER_TOKEN, shard);
|
||||
};
|
||||
a.an = w("attn_norm.weight", "input_layernorm.weight", RAD_F32, {E});
|
||||
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
|
||||
a.o = w("attn_output.weight", "self_attn.out_proj.weight", RAD_BF16, {E, Q}, RAD_SHARD_COL);
|
||||
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
|
||||
a.down = w("ffn_down.weight", "mlp.down_proj.weight", RAD_BF16, {E, F}, RAD_SHARD_COL);
|
||||
const char* qkv = src("self_attn.q_k_v_proj.weight");
|
||||
auto part = [&](const char* name, int first, int64_t all_rows, int64_t rows) {
|
||||
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
|
||||
if (map_rows(b, target, {{qkv, first, all_rows}}) != RAD_OK) return (rad_weight)0;
|
||||
return decl_w(b, target, RAD_BF16, {rows, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
|
||||
grp_layer(l));
|
||||
};
|
||||
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
|
||||
a.q = part("q", 0, qall, Q);
|
||||
a.k = part("k", (int)qall, kall, K);
|
||||
a.v = part("v", (int)(qall + kall), kall, K);
|
||||
const char* gu = nm.f("blk.%d.ffn_gate_up.weight", l);
|
||||
RAD_ARCH_TRY(map_concat(b, gu, {src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")}));
|
||||
a.gu = decl_w(b, gu, RAD_BF16, {2 * F, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
|
||||
grp_layer(l), 0, {F, F});
|
||||
if (!a.an || !a.q || !a.k || !a.v || !a.gate || !a.o || !a.fn || !a.gu || !a.down)
|
||||
return RAD_E_INVAL;
|
||||
if (g.world > 1 && needs_span(shards.q, g.n_head_all, g)) {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, a.q, shards.q.first * g.head_dim,
|
||||
(shards.q.first + shards.q.count) * g.head_dim));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
|
||||
shards.q.first + shards.q.count));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, a.o, shards.q.first * g.head_dim,
|
||||
(shards.q.first + shards.q.count) * g.head_dim));
|
||||
}
|
||||
if (g.world > 1 && needs_span(shards.kv, g.n_head_kv_all, g)) {
|
||||
for (rad_weight h : {a.k, a.v})
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.kv.first * g.head_dim,
|
||||
(shards.kv.first + shards.kv.count) * g.head_dim));
|
||||
}
|
||||
if (g.world > 1 && needs_span(shards.ff, g.n_ff_all, g)) {
|
||||
for (rad_weight h : {a.gu, a.down})
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.ff.first,
|
||||
shards.ff.first + shards.ff.count));
|
||||
}
|
||||
a.kv = m.kv;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, a.kv));
|
||||
a.anorm = norm(a.an, m.x, m.h);
|
||||
a.qp = gemm(Q, E, a.q, m.h, m.q);
|
||||
a.kp = gemm(K, E, a.k, m.h, m.k);
|
||||
a.vp = gemm(K, E, a.v, m.h, m.v);
|
||||
a.gp = gemm(g.n_head, E, a.gate, m.h, m.gate);
|
||||
Geom rope = g;
|
||||
const int kind = local[(size_t)l] ? 1 : 0;
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? 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", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS),
|
||||
{m.q}, {m.attn});
|
||||
a.store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
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, a.kv)), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS), {m.k, m.v}, {});
|
||||
a.sigmoid = rw(b, RAD_OP(b, "sigmoid", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n", g.n_head), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gate}, {m.gate});
|
||||
/* View dense [tokens, heads * dim] and [tokens, heads] as one row per head. */
|
||||
a.gate_heads = rw(b, RAD_OP(b, "scale_rows", RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("act", "none"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
|
||||
a.op = gemm(E, Q, a.o, m.attn, m.h);
|
||||
a.reduce_attn = reduce(m.h, "bf16");
|
||||
a.widen_attn = widen(m.delta);
|
||||
a.add_attn = add();
|
||||
a.fnorm = norm(a.fn, m.x, m.h);
|
||||
a.gup = gemm(2 * F, E, a.gu, m.h, m.gu);
|
||||
a.act = rw(b, RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
|
||||
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
|
||||
a.dp = gemm(E, F, a.down, m.ff, m.h);
|
||||
a.reduce_ffn = reduce(m.h, "bf16");
|
||||
if (g.world > 1 && (!a.reduce_attn || !a.reduce_ffn)) {
|
||||
fprintf(stderr, "radiance: spark25 requires exact bf16 all-reduces for TP=%d\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
a.widen_ffn = widen(m.delta);
|
||||
a.add_ffn = add();
|
||||
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
|
||||
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
|
||||
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
|
||||
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
|
||||
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
|
||||
}
|
||||
}
|
||||
m.final_norm = norm(m.norm, m.x, m.h);
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.hout});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)), {m.hout}, {m.logits});
|
||||
char ids[128] = "";
|
||||
/* The drafter is declared last, after the head. The buffer planner takes lifetimes in
|
||||
* declaration order, and a drafter's passes run after the whole trunk's, so declaring it in the
|
||||
* middle would let a trunk temporary be planned onto bytes the drafter is still reading. */
|
||||
if (m.taps.n > 0) {
|
||||
RAD_ARCH_TRY(declare_dspark(&m.ds, &m.dsw, &m.kv_draft, b, nm, meta, ctx, g, m.taps,
|
||||
(int)g.n_layer, m.tok, nm.ckpt("model.embedding.weight")));
|
||||
m.have_ds = true;
|
||||
for (int t = 0, off = 0; t < m.taps.n && off < (int)sizeof(ids) - 8; ++t)
|
||||
off += std::snprintf(ids + off, sizeof ids - off, "%s%d", t ? ", " : "",
|
||||
m.taps.layer[t]);
|
||||
rad_note(b, "the drafter reads the residual stream after layer(s) %s", ids);
|
||||
}
|
||||
|
||||
rad_note(b, "spark25 rank %d/%d: %lld layers, %lld query / %lld KV heads x %lld, "
|
||||
"FFN %lld, vocab [%lld, %lld), local window %lld", g.rank, g.world,
|
||||
(long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.vocab_off,
|
||||
(long long)(g.vocab_off + g.n_vocab), (long long)window);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
* just committed into the drafter's own K and V. Zero is a trunk step. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_ds) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
"container carries no `draft.` block, or declare ran at max_spec 0");
|
||||
return;
|
||||
}
|
||||
if (batch->draft_pass > 0) m.ds.step(c, batch);
|
||||
else m.ds.context(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.widen, brows(m.h, T), brows(m.x, T));
|
||||
if (m.reduce_embed) RAD_ISSUE_N(c, m.reduce_embed, T * g.n_embd, brows(m.x, T), RAD_NONE);
|
||||
for (size_t i = 0; i < m.layers.size(); ++i) {
|
||||
const Layer& a = m.layers[i];
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, a.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;
|
||||
RAD_ISSUE(c, a.anorm, brows(m.x, T), RAD_W(a.an), brows(m.h, T));
|
||||
RAD_ISSUE(c, a.qp, brows(m.h, T), RAD_W(a.q), brows(m.q, T));
|
||||
RAD_ISSUE(c, a.kp, brows(m.h, T), RAD_W(a.k), brows(m.k, T));
|
||||
RAD_ISSUE(c, a.vp, brows(m.h, T), RAD_W(a.v), brows(m.v, T));
|
||||
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
|
||||
a.tap_in.step(c, m.h, T, m.tap_live);
|
||||
RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
|
||||
RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
|
||||
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(a.kv, (int)i));
|
||||
RAD_ISSUE_N(c, a.attn, batch->max_q_len, brows(m.q, T), kv_cache(a.kv, (int)i),
|
||||
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(m.attn, T));
|
||||
RAD_ISSUE(c, a.sigmoid, brows(m.gate, T), brows(m.gate, T));
|
||||
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
|
||||
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
|
||||
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
|
||||
a.tap_o.step(c, m.attn, T, m.tap_live);
|
||||
RAD_ISSUE(c, a.op, brows(m.attn, T), RAD_W(a.o), brows(m.h, T));
|
||||
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
|
||||
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
|
||||
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
|
||||
RAD_ISSUE(c, a.gup, brows(m.h, T), RAD_W(a.gu), brows(m.gu, T));
|
||||
a.tap_gu.step(c, m.h, T, m.tap_live);
|
||||
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
|
||||
a.tap_down.step(c, m.ff, T, m.tap_live);
|
||||
RAD_ISSUE(c, a.dp, brows(m.ff, T), RAD_W(a.down), brows(m.h, T));
|
||||
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
|
||||
RAD_ISSUE(c, a.add_ffn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
|
||||
/* The tap after this layer, on prefill and decode alike: the drafter conditions on every
|
||||
* committed token's residual stream, not only on prefill's. */
|
||||
m.taps.step(c, m.x, T, (int64_t)i, g.n_embd);
|
||||
}
|
||||
RAD_ISSUE(c, m.final_norm, brows(m.x, T), RAD_W(m.norm), brows(m.h, T));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
if (m.tap_live) {
|
||||
m.calib_rows += T;
|
||||
if (m.calib_rows >= calib_target()) {
|
||||
bool ok = true;
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
const Layer& a = m.layers[(size_t)l];
|
||||
char stem[96];
|
||||
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
|
||||
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
|
||||
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
|
||||
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
|
||||
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
m.tap_live = false;
|
||||
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
|
||||
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
|
||||
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
|
||||
ok ? "" : ", with errors");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
spark25_prefill_key::Request r;
|
||||
r.phase = batch->phase;
|
||||
r.n_tok = batch->n_tok;
|
||||
r.n_seq = batch->n_seq;
|
||||
r.max_q_len = batch->max_q_len;
|
||||
r.max_ctx = m.g.max_ctx;
|
||||
r.n_spec = batch->n_spec;
|
||||
r.draft_pass = batch->draft_pass;
|
||||
r.enc = batch->enc != 0;
|
||||
r.head_dim = m.g.head_dim;
|
||||
r.gqa = m.g.gqa();
|
||||
r.kv_heads = m.g.n_head_kv;
|
||||
r.kv_group_found = group >= 0;
|
||||
r.used = used_max_h && group >= 0 ? used_max_h[group] : 0;
|
||||
r.wgps = rad_ctx_wgp_count(c);
|
||||
return spark25_prefill_key::pass_key(r);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The speculation depth this container supports: zero without a drafter, or the block length a
|
||||
* DSpark drafter was trained at. `draft_depth_fixed` because a block-diffusion drafter denoises
|
||||
* exactly that many mask positions, and `declare` refuses to run it at any other depth. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
out->draft_depth_fixed = 0;
|
||||
bool present = false;
|
||||
if (drafter_kind(meta, &present) != RAD_OK) return RAD_E_UNSUPPORTED;
|
||||
if (!present) return RAD_OK;
|
||||
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (bs < 2) {
|
||||
fprintf(stderr, "radiance: spark25: the container carries a drafter with no "
|
||||
"draft.block_size\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
out->draft_depth = (int)bs;
|
||||
out->draft_depth_fixed = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static const RadChatFormat* chat_format(const RadModelMeta*) { return spark_chat_format(); }
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_bf16)
|
||||
RAD_ARCH_PLUGIN(spark25_bf16, "spark25", "", "0.1.0", "Spark X2.6 BF16")
|
||||
RAD_ARCH_CHAT_FORMAT(spark25_bf16)
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
|
||||
const int32_t* used_max_h) {
|
||||
return spark25_bf16::pass_key(c, batch, used_max_h);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,67 @@
|
||||
/* Spark's prefill pass-key geometry. Keep this host-pure and mirror the h256/GQA4
|
||||
* R4D launcher exactly; unsupported batches fail closed. */
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#if defined(__has_include)
|
||||
# if __has_include(<rad_prefill_split.h>)
|
||||
# include <rad_prefill_split.h>
|
||||
# define SPARK25_HAVE_PREFILL_SPLIT 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
namespace spark25_prefill_key {
|
||||
|
||||
constexpr int kNwarps = 24;
|
||||
constexpr int kTile = 48;
|
||||
constexpr int kGqa = 4;
|
||||
constexpr int kHeadDim = 256;
|
||||
constexpr int kBq = kNwarps * 16 / kGqa;
|
||||
constexpr int kThreads = kNwarps * 32;
|
||||
constexpr int kDecodeRowCap = 64;
|
||||
constexpr int kPhasePrefill = 0;
|
||||
constexpr int kPhaseDecode = 1;
|
||||
constexpr int kPhaseMixed = 2;
|
||||
|
||||
static_assert(kBq == 96, "Spark GQA4 prefill BQ must match the R4D launcher");
|
||||
static_assert(kThreads == 768, "Spark prefill launcher uses 768 threads");
|
||||
|
||||
struct Request {
|
||||
int phase = kPhasePrefill;
|
||||
int64_t n_tok = 0, n_seq = 0, max_q_len = 0, max_ctx = 0;
|
||||
int64_t n_spec = 0, draft_pass = 0;
|
||||
int enc = 0;
|
||||
int64_t head_dim = 0, gqa = 0, kv_heads = 0;
|
||||
int kv_group_found = 0, used = 0, wgps = 0;
|
||||
};
|
||||
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
inline uint64_t pass_key(const Request& r) {
|
||||
if (r.enc) return 1;
|
||||
if (r.draft_pass != 0) return 0;
|
||||
/* Mixed and speculative passes can launch attention on sub-batches whose exact geometry
|
||||
* is not represented by the whole-batch summary. */
|
||||
if (r.phase == kPhaseMixed || r.n_spec > 0) return 0;
|
||||
if (r.phase != kPhasePrefill) return 1;
|
||||
if (r.head_dim != kHeadDim || r.gqa != kGqa || r.kv_heads <= 0 || !r.kv_group_found)
|
||||
return 0;
|
||||
/* For a singleton, these equalities prove the R4D q_len band and total_q used by its launch.
|
||||
* Do not infer geometry for multi-sequence/ragged batches. */
|
||||
if (r.n_seq != 1 || r.n_tok <= 0 || r.max_q_len != r.n_tok || r.max_ctx <= 0 ||
|
||||
r.used <= 0 || r.wgps <= 0)
|
||||
return 0;
|
||||
/* The short-query path resolves to the decode launcher, with a different split law. */
|
||||
if (r.max_q_len * r.gqa <= kDecodeRowCap) return 0;
|
||||
|
||||
const int q_len = (int)r.max_q_len;
|
||||
const int splits = rad_prefill_splits_for_live(kBq, kTile, q_len, (int)r.n_tok, 1,
|
||||
(int)r.kv_heads, (int)r.max_ctx, r.used,
|
||||
r.wgps);
|
||||
return rad_prefill_grid_key(q_len, kBq, splits, (int)r.kv_heads, 1, kThreads);
|
||||
}
|
||||
#else
|
||||
inline uint64_t pass_key(const Request&) { return 0; }
|
||||
#endif
|
||||
|
||||
} // namespace spark25_prefill_key
|
||||
@@ -0,0 +1,9 @@
|
||||
# Built in tree or against an installed radiance.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(spark25_w8a8 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(spark25_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spark25_w8a8.cpp)
|
||||
@@ -0,0 +1,682 @@
|
||||
/* Spark X2.6 (Spark2_5ForCausalLM), rotated int8 weights and activations.
|
||||
*
|
||||
* The checkpoint has one [q | k | v] projection per layer. Conversion splits its rows into
|
||||
* contiguous matrices because paged attention needs a contiguous query. The MLP's two matrices
|
||||
* are concatenated as [gate | up]; act_mul with exact erf GELU matches the reference, unlike
|
||||
* gelu_mul (which is the tanh approximation). The attention gate is one sigmoid per head, not
|
||||
* per channel. Local and full layers have different NeoX rotary dimensions and theta values.
|
||||
*
|
||||
* Tensor parallelism splits attention by whole KV groups, replicating KV heads when ranks
|
||||
* outnumber them. As in the HF reference, residuals accumulate in f32; rmsnorm reads that stream
|
||||
* and writes bf16 for the linear projections.
|
||||
*
|
||||
* A container built with `--draft-model` also carries a DSpark drafter, which reads the residual
|
||||
* stream after the trunk layers its config names and denoises a block of masked positions in one
|
||||
* pass. The drafter itself is bf16 whatever the trunk's quantisation (arch/rad_block_dspark_bf16.h
|
||||
* says why); the trunk's part is the taps and the drafter pass dispatch below.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dspark_bf16.h>
|
||||
#include "../spark25_bf16/chat.h"
|
||||
#include "../spark25_bf16/spark25_prefill_pass_key.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace spark25_w8a8 {
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
rad_kvgroup kv = 0;
|
||||
rad_weight an = 0, gate = 0, fn = 0;
|
||||
LinearFP8 q{}, k{}, v{}, o{}, gu{}, down{};
|
||||
rad_op anorm = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
|
||||
rad_op sigmoid = 0, gate_heads = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
|
||||
rad_op fnorm = 0, act = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
|
||||
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
rad_kvgroup kv = 0;
|
||||
rad_buf x = 0, delta = 0, h = 0, q = 0, k = 0, v = 0, gate = 0, attn = 0, gu = 0, ff = 0;
|
||||
rad_buf hout = 0, logits = 0;
|
||||
ActFP8 a_h{}, a_attn{}, a_ff{};
|
||||
rad_weight tok = 0, norm = 0, head = 0;
|
||||
rad_op embed = 0, widen = 0, reduce_embed = 0, had = 0, final_norm = 0, gather = 0, logits_op = 0;
|
||||
std::vector<Layer> layers;
|
||||
bool tap_live = false;
|
||||
long long calib_rows = 0;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
/* The drafter, declared only when the container carries one and this serve speculates. Its own
|
||||
* KV group holds the context it derived from the trunk's taps. */
|
||||
DsparkBF16 ds{};
|
||||
DsparkBF16::Wire dsw{};
|
||||
DsparkTaps taps{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_ds = false;
|
||||
};
|
||||
static Model models[MAX_RANKS];
|
||||
|
||||
/* Whether the container carries a drafter at all (`--draft-model` merged one under `draft.`), and
|
||||
* whether this file implements it. A drafter this plugin cannot run is refused at declare rather
|
||||
* than left unused: the container would serve at the speed of a model with no drafter, and the
|
||||
* user would have no way to find out that the flag they passed did nothing. */
|
||||
static int drafter_kind(const RadModelMeta* meta, bool* present) {
|
||||
*present = false;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (!da || !*da) {
|
||||
/* A drafter's config.json flattened, or a GGUF import, either of which names it. */
|
||||
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) <= 0) return RAD_OK;
|
||||
da = rad_meta_gets(meta, "draft.model_type", "");
|
||||
}
|
||||
if (std::strstr(da, "DSpark") || std::strcmp(da, "dspark") == 0) {
|
||||
*present = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
*present = true;
|
||||
fprintf(stderr, "radiance: spark25: this container carries a '%s' drafter. Spark's drafts are "
|
||||
"DSpark, with a rank-N Markov head over the target's own table; this "
|
||||
"architecture implements that and nothing else\n", da);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The HF config names every layer. Do not infer a periodic schedule: it changes the mask and
|
||||
* rotary of a layer and would silently produce a different model. */
|
||||
static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& local) {
|
||||
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
|
||||
if (!s) {
|
||||
fprintf(stderr, "radiance: spark25: layer_types is required\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::istringstream in(s);
|
||||
std::string word;
|
||||
while (in >> word) {
|
||||
if (word != "sliding_attention" && word != "full_attention") {
|
||||
fprintf(stderr, "radiance: spark25: unknown layer type '%s'\n", word.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
local.push_back(word == "sliding_attention");
|
||||
}
|
||||
if ((int64_t)local.size() != n) {
|
||||
fprintf(stderr, "radiance: spark25: layer_types has %zu entries for %lld layers\n",
|
||||
local.size(), (long long)n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
struct Span {
|
||||
int64_t first = 0, count = 0;
|
||||
};
|
||||
|
||||
/* Remainder-first contiguous slices, in whole units. */
|
||||
static Span split(int64_t n, int parts, int rank) {
|
||||
const int64_t base = n / parts, rem = n % parts;
|
||||
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
|
||||
}
|
||||
|
||||
struct Shards {
|
||||
Span q, kv, ff; /* q and kv in heads; ff in channels */
|
||||
};
|
||||
|
||||
/* A rank's attention heads must describe whole GQA groups, or a slice of a single group with
|
||||
* that group's KV head replicated. This also covers non-divisible worlds such as 3 ranks over
|
||||
* the checkpoint's 4 KV heads. Projection and FFN spans below give the loader those exact cuts. */
|
||||
static int shard_geometry(Geom& g, const RadBuildCtx* ctx, Shards& s) {
|
||||
g.world = ctx->world_size > 0 ? ctx->world_size : 1;
|
||||
g.rank = ctx->rank;
|
||||
if (g.rank >= g.world || g.world > g.n_head_all || g.n_head_kv_all <= 0 ||
|
||||
g.n_head_all % g.n_head_kv_all || g.world > g.n_ff_all) {
|
||||
fprintf(stderr, "radiance: spark25: cannot shard %lld query heads, %lld KV heads and "
|
||||
"%lld FFN channels over %d ranks\n", (long long)g.n_head_all,
|
||||
(long long)g.n_head_kv_all, (long long)g.n_ff_all, g.world);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t group = g.n_head_all / g.n_head_kv_all;
|
||||
if (g.world <= g.n_head_kv_all) {
|
||||
s.kv = split(g.n_head_kv_all, g.world, g.rank);
|
||||
s.q = {s.kv.first * group, s.kv.count * group};
|
||||
} else {
|
||||
int first_rank = 0;
|
||||
for (int64_t k = 0; k < g.n_head_kv_all; ++k) {
|
||||
const int n = (int)split(g.world, (int)g.n_head_kv_all, (int)k).count;
|
||||
if (g.rank < first_rank + n) {
|
||||
const Span q = split(group, n, g.rank - first_rank);
|
||||
s.kv = {k, 1};
|
||||
s.q = {k * group + q.first, q.count};
|
||||
break;
|
||||
}
|
||||
first_rank += n;
|
||||
}
|
||||
}
|
||||
/* Prefer whole 128-channel blocks for a ragged split, keeping device GEMMs aligned. */
|
||||
const int64_t unit = g.n_ff_all % 128 == 0 && g.n_ff_all / 128 >= g.world ? 128 : 1;
|
||||
s.ff = split(g.n_ff_all / unit, g.world, g.rank);
|
||||
s.ff.first *= unit;
|
||||
s.ff.count *= unit;
|
||||
g.n_head = s.q.count;
|
||||
g.n_head_kv = s.kv.count;
|
||||
g.n_ff = s.ff.count;
|
||||
g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank);
|
||||
g.vocab_off = shard_begin(g.n_vocab_all, g.world, g.rank);
|
||||
return g.n_head > 0 && g.n_head_kv > 0 && g.n_ff > 0 && g.n_vocab > 0 ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
static bool needs_span(const Span& s, int64_t total, const Geom& g) {
|
||||
return total % g.world != 0 || s.first != g.rank * (total / g.world) ||
|
||||
s.count != total / g.world;
|
||||
}
|
||||
|
||||
static int check_format(const RadModelMeta* meta) {
|
||||
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
|
||||
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
|
||||
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
|
||||
fprintf(stderr, "radiance: spark25_w8a8 serves a rotated int8 trunk (quant_method "
|
||||
"'w8a8', fmt 'fwht128'); this container says '%s' / '%s'\n",
|
||||
method ? method : "(none)", fmt ? fmt : "(none)");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
Model& m = models[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
|
||||
* then give each rank a group-preserving shard and state its spans on the weights. */
|
||||
RadBuildCtx whole = *ctx;
|
||||
whole.rank = 0;
|
||||
whole.world_size = 1;
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, &whole, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Shards shards;
|
||||
RAD_ARCH_TRY(shard_geometry(g, ctx, shards));
|
||||
/* A column-sharded int8 linear slices its input's scale groups, so every rank's
|
||||
* feed-forward span must be whole 128-column groups. shard_geometry prefers whole blocks
|
||||
* even for ragged worlds such as TP=3; refuse a geometry that cannot be split that way. */
|
||||
if (g.world > 1 && shards.ff.count % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: spark25_w8a8 cannot shard %lld FFN channels over %d ranks: a "
|
||||
"rank's %lld are not whole %d-column scale groups. An int8 down projection "
|
||||
"sliced inside a group would read its scale plane at the wrong width\n",
|
||||
(long long)g.n_ff_all, g.world, (long long)shards.ff.count, RAD_FP8_BLOCK);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
Names& nm = m.nm;
|
||||
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2 || meta->n_expert ||
|
||||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "mlp_bias", 0) ||
|
||||
!rad_meta_geti(meta, "tie_word_embeddings", 0) ||
|
||||
!rad_meta_geti(meta, "headwise_attn_output_gate", 0) ||
|
||||
std::strcmp(rad_meta_gets(meta, "gate_attn_act_mode", "sigmoid"), "sigmoid") ||
|
||||
std::strcmp(rad_meta_gets(meta, "hidden_act", "gelu"), "gelu")) {
|
||||
fprintf(stderr, "radiance: spark25: requires a dense, bias-free, tied model with headwise "
|
||||
"sigmoid gates, exact GELU and divisible attention heads\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A single global override cannot describe this model's two rotary ladders. */
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
|
||||
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f || g.rope_mc) {
|
||||
fprintf(stderr, "radiance: spark25: rotary scaling overrides are not supported\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::vector<bool> local;
|
||||
RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
|
||||
if (calib_dir()) {
|
||||
if (g.world != 1) {
|
||||
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
|
||||
"Grams retain their cross terms\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
|
||||
&m.calib_lo, &m.calib_hi));
|
||||
m.tap_live = true;
|
||||
}
|
||||
const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
|
||||
if (window <= 0) {
|
||||
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
double theta[2]{};
|
||||
int64_t rot[2]{};
|
||||
const char* kinds[] = {"full_attention", "sliding_attention"};
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
theta[j] = rad_meta_getf(meta, nm.f("rope_parameters.%s.rope_theta", kinds[j]), 10000.0);
|
||||
const double factor = rad_meta_getf(meta,
|
||||
nm.f("rope_parameters.%s.partial_rotary_factor", kinds[j]), 1.0);
|
||||
const char* type = rad_meta_gets(meta, nm.f("rope_parameters.%s.rope_type", kinds[j]), "default");
|
||||
if (std::strcmp(type, "default")) {
|
||||
fprintf(stderr, "radiance: spark25: %s rotary type '%s' is not supported\n", kinds[j], type);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double r = g.head_dim * factor;
|
||||
if (!std::isfinite(theta[j]) || !(theta[j] > 0) || !(factor > 0 && factor <= 1) || !std::isfinite(r) ||
|
||||
std::floor(r) != r || (int64_t)r % 2) {
|
||||
fprintf(stderr, "radiance: spark25: invalid %s rotary theta %g or factor %g\n",
|
||||
kinds[j], theta[j], factor);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
rot[j] = (int64_t)r;
|
||||
}
|
||||
|
||||
/* A full cache for both kinds keeps prefix caching valid. The local attention op enforces
|
||||
* its own window (q - k < window); the full layers read all past positions. */
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
kd.n_head_kv = g.n_head_kv;
|
||||
kd.head_dim = g.head_dim;
|
||||
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
|
||||
if (!m.kv) return RAD_E_INVAL;
|
||||
g.kv_dtype = rad_dtype_name(kd.dtype);
|
||||
|
||||
const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
|
||||
m.x = decl_b(b, nm.f("x"), RAD_F32, {T, E});
|
||||
m.delta = decl_b(b, nm.f("delta"), RAD_F32, {T, E});
|
||||
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
|
||||
m.q = decl_b(b, nm.f("q"), RAD_BF16, {T, Q});
|
||||
m.k = decl_b(b, nm.f("k"), RAD_BF16, {T, K});
|
||||
m.v = decl_b(b, nm.f("v"), RAD_BF16, {T, K});
|
||||
m.gate = decl_b(b, nm.f("gate"), RAD_BF16, {T, g.n_head});
|
||||
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
|
||||
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
|
||||
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
|
||||
m.hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
|
||||
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
if (!m.x || !m.delta || !m.h || !m.q || !m.k || !m.v || !m.gate || !m.attn || !m.gu || !m.ff ||
|
||||
!m.hout || !m.logits) return RAD_E_INVAL;
|
||||
m.a_h.x = m.h;
|
||||
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", E, 0, true, false));
|
||||
m.a_h.q8_fed = true;
|
||||
m.a_h.q8_rot = true;
|
||||
m.a_attn.x = m.attn;
|
||||
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", Q, 0, true, false));
|
||||
m.a_ff.x = m.ff;
|
||||
RAD_ARCH_TRY(m.a_ff.declare_qs(b, nm, g, "ff", F, 0, true, false));
|
||||
m.had = rw(b, RAD_OP(b, "had_quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS),
|
||||
{m.h}, {m.a_h.q8, m.a_h.s8});
|
||||
if (!m.had) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
|
||||
|
||||
/* ---- the drafter's taps, when the container carries a drafter and this serve speculates.
|
||||
* Declared before the layer loop because the stream outlives it: the drafter's context pass
|
||||
* runs after the trunk's, on the residual streams the trunk saved here. */
|
||||
bool drafter = false;
|
||||
RAD_ARCH_TRY(drafter_kind(meta, &drafter));
|
||||
if (drafter && ctx->max_spec > 0) {
|
||||
m.taps.read(meta, g.n_layer);
|
||||
if (m.taps.n <= 0) {
|
||||
fprintf(stderr, "radiance: spark25: the drafter names no trunk layer to read, or names "
|
||||
"only layers past this target's last (`draft.target_layer_ids`)\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.x));
|
||||
}
|
||||
|
||||
auto weight = [&](const char* name, const char* src, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, RadWeightGroup group,
|
||||
int access = RAD_ACCESS_PER_TOKEN, int shard = RAD_SHARD_NONE) {
|
||||
if (map_copy(b, name, src) != RAD_OK) return (rad_weight)0;
|
||||
return decl_w(b, name, dt, shape, access, shard, group);
|
||||
};
|
||||
m.tok = weight(nm.f("token_embd.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
|
||||
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
|
||||
/* The head is the tied table again, at whatever the container holds it: bf16 as shipped, or
|
||||
* the int8 grid where the recipe quantised it, which is the widest GEMM a decode step runs. */
|
||||
if (map_copy(b, nm.f("output.weight"), nm.ckpt("model.embedding.weight")) != RAD_OK)
|
||||
return RAD_E_INVAL;
|
||||
m.head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, E}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.norm = weight(nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32,
|
||||
{E}, grp_model());
|
||||
if (!m.tok || !m.head || !m.norm) return RAD_E_INVAL;
|
||||
if (g.world > 1 && g.n_vocab_all % g.world) {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.tok, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.head, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
}
|
||||
|
||||
auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w)), {x}, {y});
|
||||
};
|
||||
auto gemm = [&](int64_t n, int64_t k, rad_weight w, rad_buf x, rad_buf y) {
|
||||
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
|
||||
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)), {x}, {y});
|
||||
};
|
||||
auto add = [&]() {
|
||||
return rw(b, RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.x, m.delta}, {m.x});
|
||||
};
|
||||
m.embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n_embd", E), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.tok)), {}, {m.h});
|
||||
auto widen = [&](rad_buf output) {
|
||||
return rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
|
||||
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.h}, {output});
|
||||
};
|
||||
m.widen = widen(m.x);
|
||||
/* Embedding shards contribute disjoint rows, so their widened sum is exact. Projection
|
||||
* shards must instead reduce in bf16, rounding the merged output before it is widened and
|
||||
* added to the f32 residual, as in the reference's BF16 linear layers. */
|
||||
auto reduce = [&](rad_buf x, const char* dtype) {
|
||||
if (g.world <= 1) return (rad_op)0;
|
||||
return rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", E, T * E), RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS), {x}, {x});
|
||||
};
|
||||
m.reduce_embed = reduce(m.x, "fp32");
|
||||
if (g.world > 1 && !m.reduce_embed) {
|
||||
fprintf(stderr, "radiance: spark25_w8a8 requires an exact fp32 all-reduce for TP=%d\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int l = 0; l < g.n_layer; ++l) {
|
||||
Layer& a = m.layers[(size_t)l];
|
||||
auto src = [&](const char* suffix) { return nm.ckpt("model.layers.%d.%s", l, suffix); };
|
||||
auto w = [&](const char* suffix, const char* s, uint32_t dt,
|
||||
std::initializer_list<int64_t> shape, int shard = RAD_SHARD_NONE) {
|
||||
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l),
|
||||
RAD_ACCESS_PER_TOKEN, shard);
|
||||
};
|
||||
a.an = w("attn_norm.weight", "input_layernorm.weight", RAD_F32, {E});
|
||||
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
|
||||
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
|
||||
const char* qkv = src("self_attn.q_k_v_proj.weight");
|
||||
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
|
||||
const int64_t qlo = needs_span(shards.q, g.n_head_all, g) ? shards.q.first * g.head_dim : 0;
|
||||
const int64_t qhi = needs_span(shards.q, g.n_head_all, g)
|
||||
? (shards.q.first + shards.q.count) * g.head_dim : 0;
|
||||
const int64_t kvlo = needs_span(shards.kv, g.n_head_kv_all, g)
|
||||
? shards.kv.first * g.head_dim : 0;
|
||||
const int64_t kvhi = needs_span(shards.kv, g.n_head_kv_all, g)
|
||||
? (shards.kv.first + shards.kv.count) * g.head_dim : 0;
|
||||
auto map_part = [&](const char* name, int64_t first, int64_t rows) {
|
||||
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
|
||||
return map_rows(b, target, {{qkv, (int)first, rows}});
|
||||
};
|
||||
const char* qb = nm.f("blk.%d.attn_q", l);
|
||||
const char* kb = nm.f("blk.%d.attn_k", l);
|
||||
const char* vb = nm.f("blk.%d.attn_v", l);
|
||||
RAD_ARCH_TRY(map_part("q", 0, qall));
|
||||
RAD_ARCH_TRY(map_part("k", qall, kall));
|
||||
RAD_ARCH_TRY(map_part("v", qall + kall, kall));
|
||||
a.q.mapped = a.k.mapped = a.v.mapped = true;
|
||||
RAD_ARCH_TRY(a.q.declare(b, nm, g, qb, Q, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
|
||||
m.a_h, m.q, 0, {}, qlo, qhi));
|
||||
RAD_ARCH_TRY(a.k.declare(b, nm, g, kb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
|
||||
m.a_h, m.k, 0, {}, kvlo, kvhi));
|
||||
RAD_ARCH_TRY(a.v.declare(b, nm, g, vb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
|
||||
m.a_h, m.v, 0, {}, kvlo, kvhi));
|
||||
const int64_t olo = qlo, ohi = qhi;
|
||||
RAD_ARCH_TRY(a.o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), E, Q,
|
||||
RAD_SHARD_COL, grp_layer(l), {src("self_attn.out_proj.weight")},
|
||||
m.a_attn, m.h, 0, {}, olo, ohi));
|
||||
RAD_ARCH_TRY(a.gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * F, E,
|
||||
RAD_SHARD_ROW, grp_layer(l),
|
||||
{src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")},
|
||||
m.a_h, m.gu, 0, {F, F}));
|
||||
const int64_t flo = needs_span(shards.ff, g.n_ff_all, g) ? shards.ff.first : 0;
|
||||
const int64_t fhi = needs_span(shards.ff, g.n_ff_all, g)
|
||||
? shards.ff.first + shards.ff.count : 0;
|
||||
if (needs_span(shards.ff, g.n_ff_all, g)) {
|
||||
const int64_t lo[2] = {shards.ff.first, shards.ff.first};
|
||||
const int64_t hi[2] = {shards.ff.first + shards.ff.count,
|
||||
shards.ff.first + shards.ff.count};
|
||||
const int64_t total[2] = {g.n_ff_all, g.n_ff_all};
|
||||
RAD_ARCH_TRY(a.gu.span_parts(b, lo, hi, total, 2));
|
||||
}
|
||||
RAD_ARCH_TRY(a.down.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), E, F,
|
||||
RAD_SHARD_COL, grp_layer(l), {src("mlp.down_proj.weight")},
|
||||
m.a_ff, m.h, 0, {}, flo, fhi));
|
||||
if (!a.an || !a.gate || !a.fn || !a.q.w || !a.k.w || !a.v.w || !a.o.w ||
|
||||
!a.gu.w || !a.down.w) return RAD_E_INVAL;
|
||||
if (g.world > 1 && needs_span(shards.q, g.n_head_all, g))
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
|
||||
shards.q.first + shards.q.count));
|
||||
a.kv = m.kv;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, a.kv));
|
||||
a.anorm = norm(a.an, m.x, m.h);
|
||||
a.gp = gemm(g.n_head, E, a.gate, m.h, m.gate);
|
||||
Geom rope = g;
|
||||
const int kind = local[(size_t)l] ? 1 : 0;
|
||||
rope.theta = (float)theta[kind];
|
||||
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
|
||||
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
|
||||
a.attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? 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", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS),
|
||||
{m.q}, {m.attn});
|
||||
a.store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
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, a.kv)), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS), {m.k, m.v}, {});
|
||||
a.sigmoid = rw(b, RAD_OP(b, "sigmoid", RAD_PARAMS(RAD_RANGE("M", 1, T),
|
||||
RAD_INT("n", g.n_head), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gate}, {m.gate});
|
||||
/* View dense [tokens, heads * dim] and [tokens, heads] as one row per head. */
|
||||
a.gate_heads = rw(b, RAD_OP(b, "scale_rows", RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("act", "none"), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
|
||||
a.reduce_attn = reduce(m.h, "bf16");
|
||||
a.widen_attn = widen(m.delta);
|
||||
a.add_attn = add();
|
||||
a.fnorm = norm(a.fn, m.x, m.h);
|
||||
a.act = rw(b, RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
|
||||
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
|
||||
a.reduce_ffn = reduce(m.h, "bf16");
|
||||
if (g.world > 1 && (!a.reduce_attn || !a.reduce_ffn)) {
|
||||
fprintf(stderr, "radiance: spark25_w8a8 requires exact bf16 all-reduces for TP=%d\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
a.widen_ffn = widen(m.delta);
|
||||
a.add_ffn = add();
|
||||
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
|
||||
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
|
||||
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
|
||||
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
|
||||
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
|
||||
}
|
||||
}
|
||||
m.final_norm = norm(m.norm, m.x, m.h);
|
||||
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.hout});
|
||||
m.logits_op = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(m.head)), {m.hout}, {m.logits});
|
||||
char ids[128] = "";
|
||||
/* The drafter is declared last, after the head. The buffer planner takes lifetimes in
|
||||
* declaration order, and a drafter's passes run after the whole trunk's, so declaring it in the
|
||||
* middle would let a trunk temporary be planned onto bytes the drafter is still reading. */
|
||||
if (m.taps.n > 0) {
|
||||
RAD_ARCH_TRY(declare_dspark(&m.ds, &m.dsw, &m.kv_draft, b, nm, meta, ctx, g, m.taps,
|
||||
(int)g.n_layer, m.tok, nm.ckpt("model.embedding.weight")));
|
||||
m.have_ds = true;
|
||||
for (int t = 0, off = 0; t < m.taps.n && off < (int)sizeof(ids) - 8; ++t)
|
||||
off += std::snprintf(ids + off, sizeof ids - off, "%s%d", t ? ", " : "",
|
||||
m.taps.layer[t]);
|
||||
rad_note(b, "the drafter reads the residual stream after layer(s) %s", ids);
|
||||
}
|
||||
|
||||
rad_note(b, "spark25 rank %d/%d: %lld layers, %lld query / %lld KV heads x %lld, "
|
||||
"FFN %lld, vocab [%lld, %lld), local window %lld", g.rank, g.world,
|
||||
(long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
|
||||
(long long)g.head_dim, (long long)g.n_ff, (long long)g.vocab_off,
|
||||
(long long)(g.vocab_off + g.n_vocab), (long long)window);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = models[rad_rank(c)];
|
||||
const Geom& g = m.g;
|
||||
/* A drafter pass; the sign gives the kind. Positive is the query pass, which denoises the whole
|
||||
* block and proposes from it; negative is the context pass, which turns the tokens the trunk
|
||||
* just committed into the drafter's own K and V. Zero is a trunk step. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (!m.have_ds) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
"container carries no `draft.` block, or declare ran at max_spec 0");
|
||||
return;
|
||||
}
|
||||
if (batch->draft_pass > 0) m.ds.step(c, batch);
|
||||
else m.ds.context(c, batch);
|
||||
return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadOperand pos = praw(batch->positions, RAD_I32, T);
|
||||
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.h, T));
|
||||
RAD_ISSUE(c, m.widen, brows(m.h, T), brows(m.x, T));
|
||||
if (m.reduce_embed) RAD_ISSUE_N(c, m.reduce_embed, T * g.n_embd, brows(m.x, T), RAD_NONE);
|
||||
for (size_t i = 0; i < m.layers.size(); ++i) {
|
||||
const Layer& a = m.layers[i];
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, a.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;
|
||||
RAD_ISSUE(c, a.anorm, brows(m.x, T), RAD_W(a.an), brows(m.h, T));
|
||||
a.tap_in.step(c, m.h, T, m.tap_live);
|
||||
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
|
||||
a.q.step(c, m.a_h, m.q, T);
|
||||
a.k.step(c, m.a_h, m.k, T);
|
||||
a.v.step(c, m.a_h, m.v, T);
|
||||
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
|
||||
RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
|
||||
RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
|
||||
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(a.kv, (int)i));
|
||||
RAD_ISSUE_N(c, a.attn, batch->max_q_len, brows(m.q, T), kv_cache(a.kv, (int)i),
|
||||
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(m.attn, T));
|
||||
RAD_ISSUE(c, a.sigmoid, brows(m.gate, T), brows(m.gate, T));
|
||||
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
|
||||
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
|
||||
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
|
||||
a.tap_o.step(c, m.attn, T, m.tap_live);
|
||||
a.o.step(c, m.a_attn, m.h, T);
|
||||
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
|
||||
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
|
||||
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
|
||||
a.tap_gu.step(c, m.h, T, m.tap_live);
|
||||
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
|
||||
a.gu.step(c, m.a_h, m.gu, T);
|
||||
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
|
||||
a.tap_down.step(c, m.ff, T, m.tap_live);
|
||||
a.down.step(c, m.a_ff, m.h, T);
|
||||
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
|
||||
RAD_ISSUE(c, a.add_ffn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
|
||||
/* The tap after this layer, on prefill and decode alike: the drafter conditions on every
|
||||
* committed token's residual stream, not only on prefill's. */
|
||||
m.taps.step(c, m.x, T, (int64_t)i, g.n_embd);
|
||||
}
|
||||
RAD_ISSUE(c, m.final_norm, brows(m.x, T), RAD_W(m.norm), brows(m.h, T));
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
|
||||
brows(m.logits, batch->n_out));
|
||||
}
|
||||
if (m.tap_live) {
|
||||
m.calib_rows += T;
|
||||
if (m.calib_rows >= calib_target()) {
|
||||
bool ok = true;
|
||||
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
|
||||
const Layer& a = m.layers[(size_t)l];
|
||||
char stem[96];
|
||||
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
|
||||
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
|
||||
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
|
||||
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
|
||||
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
|
||||
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
|
||||
}
|
||||
m.tap_live = false;
|
||||
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
|
||||
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
|
||||
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
|
||||
ok ? "" : ", with errors");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
static uint64_t pass_key(RadCtx* c, const RadBatch* batch, const int32_t* used_max_h) {
|
||||
if (!c || !batch) return 0;
|
||||
Model& m = models[rad_rank(c)];
|
||||
int group = -1;
|
||||
if (batch->kv) for (int i = 0; i < batch->n_kv_groups; ++i)
|
||||
if (batch->kv[i].group == m.kv) { group = i; break; }
|
||||
spark25_prefill_key::Request r;
|
||||
r.phase = batch->phase;
|
||||
r.n_tok = batch->n_tok;
|
||||
r.n_seq = batch->n_seq;
|
||||
r.max_q_len = batch->max_q_len;
|
||||
r.max_ctx = m.g.max_ctx;
|
||||
r.n_spec = batch->n_spec;
|
||||
r.draft_pass = batch->draft_pass;
|
||||
r.enc = batch->enc != 0;
|
||||
r.head_dim = m.g.head_dim;
|
||||
r.gqa = m.g.gqa();
|
||||
r.kv_heads = m.g.n_head_kv;
|
||||
r.kv_group_found = group >= 0;
|
||||
r.used = used_max_h && group >= 0 ? used_max_h[group] : 0;
|
||||
r.wgps = rad_ctx_wgp_count(c);
|
||||
return spark25_prefill_key::pass_key(r);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The speculation depth this container supports: zero without a drafter, or the block length a
|
||||
* DSpark drafter was trained at. `draft_depth_fixed` because a block-diffusion drafter denoises
|
||||
* exactly that many mask positions, and `declare` refuses to run it at any other depth. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
out->draft_depth_fixed = 0;
|
||||
bool present = false;
|
||||
if (drafter_kind(meta, &present) != RAD_OK) return RAD_E_UNSUPPORTED;
|
||||
if (!present) return RAD_OK;
|
||||
const long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (bs < 2) {
|
||||
fprintf(stderr, "radiance: spark25: the container carries a drafter with no "
|
||||
"draft.block_size\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
out->draft_depth = (int)bs;
|
||||
out->draft_depth_fixed = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static const RadChatFormat* chat_format(const RadModelMeta*) { return spark25_bf16::spark_chat_format(); }
|
||||
}
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PROBE(spark25_w8a8)
|
||||
RAD_ARCH_PLUGIN(spark25_w8a8, "spark25", "w8a8_fwht128", "0.1.0",
|
||||
"Spark X2.6 with an int8 trunk: i8 weights with a bf16 scale a 128 of K, rotated "
|
||||
"by a 128-wide Hadamard, against int8 activations the same rotation quantises")
|
||||
RAD_ARCH_CHAT_FORMAT(spark25_w8a8)
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
extern "C" uint64_t rad_arch_pass_key(RadCtx* c, const RadBatch* batch,
|
||||
const int32_t* used_max_h) {
|
||||
return spark25_w8a8::pass_key(c, batch, used_max_h);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
Reference in new issue
Block a user