merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port

Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.

Notable reconciliations:
  * videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
    (i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
    so upstream models keep refusing them as unknown tasks; input_reference,
    the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
    coexist with refs/ref2va; the prompt put() helper hoisted to block scope
    for the media branch.
  * video_schedule(): upstream's (steps, video_tokens, refine) keeps its
    positional slots; the port's shift_video/shift_audio overrides move to the
    tail so upstream's schedule tests call unchanged.
  * r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
    upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
    2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
    upstream's wadd/norm_once/norm parameters.
  * tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
    staging dir -- plugin .so files still land in the absolute
    RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
    relative bin/, which needs no root.

Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
gearwave00001andClaude committed 2026-10-22 18:38:04 -05:00
commit a1a75da7e9
415 files changed
+78837 -5310

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(anima LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(anima architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/anima.cpp)
+1367
View File
File diff suppressed because it is too large. Load diff
+109 -11
View File
@@ -432,6 +432,28 @@ inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list<R
return rad_decl_name_map(b, &m);
}
/* How adapter files name a generator's modules (rad_lora_root, rad_lora_alias): one network
* under the checkpoint prefix `native`, the prefixes adapter keys use for it, and the module paths
* that differ, '#' standing for a block index. */
struct LoraName {
std::string from, to;
int64_t from_lo = 0, from_hi = 0, to_lo = 0;
};
inline int lora_names(RadBuilder* b, const char* native, const char* spellings,
const std::vector<LoraName>& names) {
const int s = rad_lora_root(b, native, spellings);
if (s < 0) return s;
for (const LoraName& n : names) {
const int a = rad_lora_alias(b, native, n.from.c_str(), n.to.c_str(), n.from_lo, n.from_hi,
n.to_lo);
if (a < 0) return a;
}
return RAD_OK;
}
/* The prefixes ComfyUI, kohya and bare-key adapter files put before a diffusion model's modules. */
inline const char* kLoraDiffusionSpellings = "diffusion_model. model.diffusion_model. lora_unet_ "
"base_model.model. -";
/* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */
inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) {
RadNameMap m = map_base(declared, RAD_MAP_WNORM);
@@ -450,6 +472,17 @@ inline int map_transpose(RadBuilder* b, const char* declared, const char* src) {
return rad_decl_name_map(b, &m);
}
/* One index of one dimension of a checkpoint tensor (RAD_MAP_TAP): a causal 3-D convolution's
* last temporal tap is map_tap(b, name, src, 2, -1). */
inline int map_tap(RadBuilder* b, const char* declared, const char* src, int dim, int index) {
RadNameMap m = map_base(declared, RAD_MAP_TAP);
m.n_src = 1;
m.src[0] = src;
m.src_index[0] = index;
m.concat_dim = dim;
return rad_decl_name_map(b, &m);
}
/* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */
inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) {
RadNameMap m = map_base(declared, RAD_MAP_EMA);
@@ -554,6 +587,53 @@ inline rad_op rw(RadBuilder* b, rad_op h,
return h;
}
/* ---- A weight read into the on-die cache beside a collective (libr4d `prefetch`, docs/OPS.md).
* At decode heights a GEMM streams its weight once from memory, and a collective in front of it
* leaves the card's memory idle for its round trip. prefetch_beside issues `op`, a `prefetch` of
* the next GEMM's weight `w`, behind the GEMM before the collective, so the two do not share the
* memory, and the next GEMM finds its leading bytes in the cache. Nothing it reads or writes is a
* model value, so on the second lane it keeps that lane's rules with no buffer named
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
*
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
* reads touch. The reads stay off prompt steps all the same. */
constexpr int64_t kPrefetchRows = 16;
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
if (!op || T > kPrefetchRows) return;
if (prefetch_lane0()) {
RAD_ISSUE(c, op, RAD_W(w));
return;
}
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
rad_lane(c, 0);
}
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
inline bool prefetch_enabled() {
const char* e = std::getenv("RADIANCE_PREFETCH");
return !(e && !std::strcmp(e, "0"));
}
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
* otherwise. */
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
}
/* ================================================================== geometry */
/* Dimensions come from model metadata, so one plugin covers every size in a family. Sharded
* dimensions are already divided by world_size: the plugin declares divided dimensions and emits
@@ -1229,17 +1309,30 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
* over the ranks, and a plain RMS norm. A drafter is a second model, so nothing is defaulted: a
* config that does not describe one is refused, naming `what` (spec §17). So is a vocabulary
* other than the target's, since a drafter reads the target's embedding and lm_head. */
* other than the target's, since a drafter reads the target's embedding and lm_head.
*
* The layer config sits at the top of `draft.` in z-lab's and SpecForge's checkpoints, and under
* `draft.transformer_layer_config.` in vLLM's speculators format (RedHatAI's DFlash2 drafters),
* whose top level holds the speculator's own keys instead (drafter_layer_prefix). */
inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) > 0) return "draft.";
if (rad_meta_geti(meta, "draft.transformer_layer_config.num_hidden_layers", 0) > 0)
return "draft.transformer_layer_config.";
return "draft.";
}
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
dg = target;
dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0);
dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0);
dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0);
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
rad_meta_getf(meta, "draft.rope_theta", 0.0));
const char* pre = drafter_layer_prefix(meta);
char key[160];
auto k = [&](const char* name) { std::snprintf(key, sizeof key, "%s%s", pre, name); return key; };
dg.n_layer = rad_meta_geti(meta, k("num_hidden_layers"), 0);
dg.head_dim = rad_meta_geti(meta, k("head_dim"), 0);
dg.n_head_all = rad_meta_geti(meta, k("num_attention_heads"), 0);
dg.n_head_kv_all = rad_meta_geti(meta, k("num_key_value_heads"), 0);
dg.n_ff_all = rad_meta_geti(meta, k("intermediate_size"), 0);
dg.eps = (float)rad_meta_getf(meta, k("rms_norm_eps"), 0.0);
const double th = rad_meta_getf(meta, k("rope_theta"), 0.0);
dg.theta = (float)rad_meta_getf(meta, k("rope_parameters.rope_theta"), th);
dg.wadd = dg.wadd_qk = 0.0f;
if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
@@ -1250,11 +1343,11 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
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));
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, "draft.vocab_size", dg.n_vocab_all);
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
if (dvocab != dg.n_vocab_all) {
fprintf(stderr, "radiance: the %s drafter claims a %lld-token vocabulary and the target "
"has %lld; it reads the target's embedding and lm_head\n",
@@ -1331,6 +1424,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge
return NS::audio_format(m); \
}
/* Optional: RAD_ARCH_SERVES_IMPORTS(0) keeps a family's second quantised plugin out of the pick for
* an imported checkpoint (rad_builder.h, rad_arch_serves_imports). */
#define RAD_ARCH_SERVES_IMPORTS(V) \
extern "C" int rad_arch_serves_imports(void) { return V; }
} /* namespace arch */
} /* namespace rad */
+294 -39
View File
@@ -69,10 +69,21 @@
* 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.
*
* 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
* kept bit for bit. Each rank hands over an equal share of c's columns
* (n_embd / world) and computes the fewest whole 128-row scale blocks that cover
* it (the 31B at tp 4: 1344 columns a rank inside 11 blocks, 1408 rows, against
* 42 blocks whole), a row span of the one stored weight
* (DenseFP8::declare_slice), so no reconvert. The GEMM takes its K split from
* the whole width (OPS.md's `split_n`), so each output is summed as the unsplit
* fc sums it, and the all-gather reads each rank's window out of its wider rows
* (an input pitch) and writes c whole. A GEMM cannot write a column slice (the
* narrow fp8 kernel's store is tight), which is why the windows are the
* gather's to cut. One rank, or an fc off block fp8, keeps it whole.
*
* Replicated:
*
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
* all-reduce to the prefill path.
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
* replicated hidden row, so every rank needs every coefficient.
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
@@ -113,6 +124,12 @@ struct Dflash2 {
int64_t sel_topk = 16; /* candidates kept per position */
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The target's embedding scale, applied to the query block as the drafter was trained
* (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */
double escale = 1.0;
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
int64_t prefetch = 0;
int64_t steps() const { return block - 1; }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
@@ -124,6 +141,10 @@ struct Dflash2 {
/* the context pass */
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
/* [max_tok, fc_rows] the block-aligned rows of a split fc this rank computes, whose
* fc_share-wide window at fc_off is gathered into c. The block declares it (only when it
* splits fc); leave it 0. */
rad_buf cpart = 0;
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
@@ -188,10 +209,17 @@ struct Dflash2 {
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
* Quantisation can only change acceptance, since every draft is verified. */
DenseFP8 w_fc{};
/* fc split by rows (see SHARDING): w_fc is this rank's fc_rows block-aligned rows, holding its
* fc_share output columns at row fc_off. fc_rows 0: w_fc is the whole fc, replicated. */
int64_t fc_share = 0, fc_rows = 0, fc_off = 0;
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
rad_weight w_tok = 0; /* the target's embedding table */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit (or 8-bit) copy of the target's lm_head */
/* The copy is int8 with an f16 scale per (row, 128 of K) where the recipe made it so (the
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
bool head_i8 = false;
/* per-layer weights */
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
@@ -206,7 +234,11 @@ struct Dflash2 {
/* context-pass ops */
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
rad_op op_cgath = 0; /* the split fc's all-gather */
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
/* The k norm, the k rotary and the cache store as one launch a layer (qkv_norm_rope_kv_store
* with n_head 0 and v_norm 0), issued in place of those three where it resolves. */
rad_op op_cqkr[MAX_LAYERS] = {};
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
* serves every layer; ops with weights are per layer because a weight's prefetch interval
@@ -222,11 +254,26 @@ struct Dflash2 {
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {};
rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
/* The q and k norms, both rotaries and the cache store as one launch a layer
* (qkv_norm_rope_kv_store with v_norm 0), issued in place of those five where it resolves. */
rad_op op_qkr[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
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),
* op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after
* the last layer's (the final norm). All or none. */
rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0;
/* The reads beside the query pass's all-reduces (cfg.prefetch), each the GEMMs that follow
* in their order: beside the attention's, the feed-forward's coefficient projection, then
* gate_up; beside the feed-forward's, the next layer's attention coefficient projection, then
* its q -- after the last layer, the draft head; and o's beside the attention itself. 0 where
* none is declared. */
rad_op op_pfa[MAX_LAYERS][2] = {}, op_pff[MAX_LAYERS][2] = {}, op_pfo[MAX_LAYERS] = {};
rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {};
/* head and selector */
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
@@ -281,9 +328,38 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
{
const int64_t K = cfg.n_taps * g.n_embd;
const char* fwn = nm.f("dflash.fc.weight");
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
* 16-byte words (the gather's unit). */
RadEncoding fe{};
const RadEncPlane* fsc = nullptr;
const bool fp8 = weight_enc(b, fwn, &fe) && rad_enc_is(&fe, "affine") && fe.n_planes == 2 &&
!fe.transform[0] && fe.plane[0].dtype == RAD_F8E4M3 &&
(fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_FP8_BLOCK &&
fsc->block[1] == RAD_FP8_BLOCK;
const int64_t share = (g.world > 1 && g.n_embd % RAD_FP8_BLOCK == 0 &&
g.n_embd % g.world == 0 && (g.n_embd / g.world) % 8 == 0)
? g.n_embd / g.world : 0;
if (fp8 && share > 0) {
const int64_t B = RAD_FP8_BLOCK;
const int64_t lo = share * g.rank / B * B;
const int64_t hi = (share * (g.rank + 1) + B - 1) / B * B;
fc_share = share;
fc_rows = hi - lo;
fc_off = share * g.rank - lo;
RAD_ARCH_TRY(w_fc.declare_slice(b, nm, nm.f("dflash.fc"), fwn, lo, hi, K,
RAD_ACCESS_PER_TOKEN, grp_model()));
if (!w.cpart)
w.cpart = decl_b(b, nm.f("df_cpart"), g.act_dtype, { g.max_tok, fc_rows });
} else {
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, K, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) },
{}, true));
}
}
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"),
@@ -318,10 +394,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
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));
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());
/* 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;
/* ---------------------------------------------------------------- per-layer weights */
@@ -419,7 +513,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
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). */
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_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
RAD_NOWEIGHTS),
{w.cpart}, {w.c});
} else {
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
}
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
* written. */
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
@@ -468,12 +576,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* An unscaled lookup is declared exactly as before the scale existed, so a Qwen container
* resolves the same op. */
if (cfg.escale != 1.0)
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
else
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
/* The trunk's embedding is vocab-sharded, so the lookup is partial and needs an exact
* all-reduce. */
if (g.world > 1)
@@ -587,6 +705,62 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.k, w.v}, {});
/* The query pass's q/k norms, rotaries and store as one launch a layer where a library
* serves it: qkv_norm_rope_kv_store with v_norm 0 (v stored as it is), byte-identical to the
* two rmsnorms, the two ropes and kv_store (docs/OPS.md), which stay declared beside it for
* a library that does not. No YaRN (the fold takes none). */
{
/* Only for a shape a library serves: an op declared for one that resolves to no device
* kernel is a hole that refuses startup (Program::device_holes), whether or not it is
* issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in
* steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim
* 128) keeps the chain. */
const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 &&
!std::strcmp(g.dtype, "bf16") &&
(!std::strcmp(g.kv_dtype, "fp8_e4m3") ||
!std::strcmp(g.kv_dtype, "bf16"));
if (fold_shape && g.yarn.factor == 0.0f &&
rad_op_declared(b, "qkv_norm_rope_kv_store")) {
const int64_t bsz = rad_kv_block_size(b, kv);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_qkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head),
RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0), RAD_INT("block_size", bsz),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_qn[i], w_kn[i]));
if (!op_qkr[i] || !rad_op_resolved(b, op_qkr[i])) {
for (int j = 0; j <= i; ++j) op_qkr[j] = 0;
break;
}
op_qkr[i] = rw(b, op_qkr[i], {w.q, w.k, w.v}, {w.q, w.k, w.v});
}
/* The context pass's keys the same way: no q (n_head 0, `q` passed as k's buffer and
* `q_w` as k's norm, neither read), the context rows' slots. */
for (int64_t l = 0; op_qkr[0] && l < g.n_layer; ++l) {
const int i = (int)l;
op_cqkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", 0), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("eps", g.eps),
RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"),
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype),
RAD_INT("v_norm", 0), RAD_INT("block_size", bsz),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_WEIGHTS(w_kn[i], w_kn[i]));
if (!op_cqkr[i] || !rad_op_resolved(b, op_cqkr[i])) {
for (int j = 0; j <= i; ++j) op_cqkr[j] = 0;
break;
}
op_cqkr[i] = rw(b, op_cqkr[i], {w.ck, w.cv}, {w.ck});
}
}
}
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
@@ -611,6 +785,30 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* Each residual add and the norm after it as one launch where a library serves add_rmsnorm
* (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only
* where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run
* otherwise. */
if (rad_op_declared(b, "add_rmsnorm")) {
auto an = [&](rad_weight wt) -> rad_op {
const rad_op h = RAD_OP(b, "add_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wt));
return h && rad_op_resolved(b, h) ? rw(b, h, {w.x, w.h2}, {w.x, w.h}) : (rad_op)0;
};
bool all = true;
for (int64_t l = 0; all && l < g.n_layer; ++l) {
const int i = (int)l;
op_afn[i] = an(w_fnorm[i]);
if (l > 0) op_aan[i] = an(w_anorm[i]);
all = op_afn[i] && (l == 0 || op_aan[i]);
}
op_afinal = all ? an(w_norm) : 0;
if (!op_afinal)
for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0;
}
/* ---------------------------------------------------------------- the head and the selector
*
@@ -630,12 +828,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.dq, w.ds, w.dsum});
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
op_dlogits = head_i8
? rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w8a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds}, {w.dlog})
: rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
RAD_STR("dtype", "w2a8")),
RAD_WEIGHTS(w_dh, w_dhs)),
{w.dq, w.ds, w.dsum}, {w.dlog});
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
* with value 0 is a different declaration from an absent one. */
@@ -705,6 +910,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
/* The reads beside the all-reduces, after every weight they read is declared. */
if (op_ar && cfg.prefetch > 0)
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
pfa_w[i][0] = w_fcp[i];
pfa_w[i][1] = w_gu[i].w;
pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_dh;
pff_w[i][1] = l + 1 < g.n_layer ? w_q[i + 1].w : 0;
for (int j = 0; j < 2; ++j) {
op_pfa[i][j] = decl_prefetch(b, pfa_w[i][j], cfg.prefetch);
op_pff[i][j] = decl_prefetch(b, pff_w[i][j], cfg.prefetch);
}
pfo_w[i] = w_o[i].w;
op_pfo[i] = decl_prefetch(b, pfo_w[i], cfg.prefetch);
}
return RAD_OK;
}
@@ -718,8 +939,14 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
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());
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));
} 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());
}
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
@@ -729,6 +956,12 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
if (op_cqkr[i]) {
RAD_ISSUE_N(c, op_cqkr[i], T, brows(w.ck, T), brows(w.ck, T), brows(w.cv, T),
praw(batch->positions, RAD_I32, T), RAD_W(w_kn[i]), RAD_W(w_kn[i]),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
continue;
}
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
@@ -754,11 +987,23 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
/* x += h2 waits for the norm after it, which takes it in (add_rmsnorm) where declared */
bool add_pending = false;
auto norm = [&](rad_op plain, rad_op folded, rad_weight wt) {
if (add_pending && folded) {
RAD_ISSUE_N(c, folded, T, brows(w.x, T), brows(w.h2, T), RAD_W(wt), brows(w.h, T));
} else {
if (add_pending) RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
RAD_ISSUE_N(c, plain, T, brows(w.x, T), RAD_W(wt), brows(w.h, T));
}
add_pending = false;
};
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
/* ---- attention, wrapped in the two halves of one convolution */
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
norm(op_anorm[i], op_aan[i], w_anorm[i]);
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -770,13 +1015,20 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
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));
prefetch_beside(c, op_pfo[i], pfo_w[i], T);
if (op_qkr[i]) {
RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T),
praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]),
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
} else {
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
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),
@@ -787,16 +1039,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
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());
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pfa[i][j], pfa_w[i][j], T);
/* Reduce before the closing convolution. It is linear with coefficients from the
* replicated norm, so either order gives the same result; reducing first keeps x's
* update agreed across ranks. */
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
add_pending = true;
/* ---- the feed-forward, wrapped in the other convolution */
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
@@ -813,13 +1066,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T));
add_pending = true;
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
norm(op_final, op_afinal, w_norm);
/* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */
const int64_t S = batch->n_out;
@@ -830,9 +1084,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
* whole. */
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
* so an absent optional one is RAD_NONE, not a shorter list. */
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
* takes no asum. */
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
* the merge overwrites `cand`/`unary`. */
if (op_dmerge) {
+370
View File
@@ -0,0 +1,370 @@
/* GLM-5.3's DSA indexer: the stateful compressed-index core over its paged key cache (DsaCache),
* which scores every complete block of a sequence's history against each query and selects the
* 512 the MLA attends to, and the front end around it (GlmIndexer), whose casts bridge ordinary
* linear rows to the flattened per-head quantiser and join normalized keys with learned pool
* gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to
* the MLA.
*
* Under tensor parallelism the key side stays replicated (every rank pools into the whole index
* cache and scores against it), but from GlmTp::kSplitRows rows, or a smaller step whose rows x
* live blocks reach GlmTp::kSplitWork, each rank scores and selects for its own run of query rows
* (GlmTp::run_of) and two all_gathers join the runs' page tables and lengths: every row's
* selection is computed by the same kernels from the same operands as on one rank, so the joined
* table is the replicated one's bits. The query side (projection, head gates, quantiser) then runs
* on this rank's run of rows only, since no other rank reads them. */
#ifndef RAD_BLOCK_GLM_INDEXER_H
#define RAD_BLOCK_GLM_INDEXER_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
namespace rad {
namespace arch {
struct DsaCache {
struct Config {
int64_t blocks = 0, work = 0, ring = 0, topk = 512;
};
struct Wire {
rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0;
rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0;
rad_buf score = 0, selected = 0, nsel = 0, length = 0;
/* 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;
};
/* The narrower of the two gathered rows, one i32 length a query row (the page table's 513 a
* row is a multiple of it), so a run is whole 16-byte words of both: a multiple of four rows.
* The query and output planes hold world times this. */
static constexpr int64_t kGatherRowBytes = 4;
static int64_t part_rows(int64_t rows, int world) {
return GlmTp::run_rows(rows, world, kGatherRowBytes);
}
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup index = 0, tail = 0, attention = 0;
rad_weight ape = 0;
rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0;
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,
const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group,
rad_kvgroup* index_group, const char* ape_source) {
g = geom;
c = cfg;
w = wire;
layer = l;
attention = attn;
tail = tail_group;
if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 ||
c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 ||
!w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page ||
!w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel ||
!w.length)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail));
const char* name = nm.f("blk.%d.index_ape", l);
RAD_ARCH_TRY(map_copy(b, name, ape_source));
ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!ape) return RAD_E_INVAL;
// Query buffers are [tokens*32,128]; scoring uses their rank-three view.
op_query = rw(b,
RAD_OP(b, "dsa_query",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.query }, { w.codes, w.scales });
op_work = rw(
b,
RAD_OP(b, "qsa_work",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4),
RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs),
RAD_INT("work", c.work), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, { w.stage, w.page, w.bpos, w.nc });
// Declare immediately before the cache consumer: page size comes from that op.
if (!*index_group) {
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_U8;
d.n_head_kv = 1;
d.head_dim = 17;
*index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d);
}
index = *index_group;
if (!index) return RAD_E_INVAL;
op_pool =
rw(b,
RAD_OP(b, "dsa_pool",
RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4),
RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(ape)),
{ w.stage, w.page }, { w.pooled, w.pool_scale });
if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index));
op_tail = rw(b,
RAD_OP(b, "qsa_tail_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256),
RAD_INT("ratio", 4), RAD_INT("ring", c.ring),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.kg }, {});
op_score = rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score });
const bool split = g.world > 1;
const int64_t part = split ? part_rows(g.max_tok, g.world) : 0;
if (split && (!w.cu_part || !w.sel_part || !w.len_part)) return RAD_E_INVAL;
if (split)
op_score_part =
rw(b,
RAD_OP(b, "dsa_score",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("n", 128),
RAD_INT("heads", 32), RAD_INT("blocks", c.blocks),
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3"),
RAD_INT("row_part", g.rank)),
RAD_NOWEIGHTS),
{ w.codes, w.scales, w.gate, w.nc }, { w.score, w.cu_part });
op_select = rw(b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc }, { w.selected, w.nsel, w.length });
if (split) {
op_select_part = rw(
b,
RAD_OP(b, "qsa_select",
RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("blocks", c.blocks),
RAD_INT("topk", 512), RAD_INT("ratio", 4),
RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)),
RAD_NOWEIGHTS),
{ w.score, w.nc, w.cu_part }, { w.sel_part, w.nsel, w.len_part });
op_gather_sel = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4 * 513, part * 513),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.sel_part }, { w.selected });
op_gather_len = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4, part),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{ w.len_part }, { w.length });
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;
}
/* 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);
int64_t live = ((int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + 4) / 4 + 1;
if (live > c.blocks) live = c.blocks;
// T is the total across sequences, so the conservative bound can exceed the
// per-sequence page table. Columns without a table entry cannot be scored.
if (ib && live > ib->block_table_pitch) live = ib->block_table_pitch;
return live < 1 ? 1 : live;
}
/* 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. */
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));
}
/* 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
* projections into `query` and `gate` cover the same rows. */
void query_rows(const RadBatch* batch, int64_t* r0, int64_t* rows) const {
const int64_t T = batch->n_tok;
*r0 = 0;
*rows = T;
if (!splits(batch)) return;
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kGatherRowBytes);
*r0 = run.first;
*rows = run.rows;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto* ib = kv_batch(batch, index);
const auto* tb = kv_batch(batch, tail);
const auto* ab = kv_batch(batch, attention);
if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) {
rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t work = (T + 3) / 4 + S,
pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1;
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));
RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch),
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE,
brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work),
brows(w.nc, S));
RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work),
brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer));
// Gather before overwriting the tail; the wider ring preserves rejected-token rollback.
RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T),
praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer),
praw2(tb->state_index, RAD_I32, S, pitch));
const int64_t live = live_blocks(batch);
if (splits(batch)) {
step_split(ctx, batch, live);
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,
praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, T), RAD_NONE);
RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1),
brows(w.selected, T), brows(w.nsel, T), brows(w.length, T));
}
/* Rank r scores rows [r R, r R + R) (rows past the step score -inf) and selects for those
* that exist (query_rows), against the bounds the scorer rebased to its first row. The
* gathers lay the runs end to end, so rows past the step land past T, where nothing reads
* them. */
void step_split(RadCtx* ctx, const RadBatch* batch, int64_t live) const {
const auto* ib = kv_batch(batch, index);
const auto* ab = kv_batch(batch, attention);
const int64_t T = batch->n_tok, S = batch->n_seq, W = g.world;
const int64_t R = part_rows(T, g.world);
int64_t p0 = 0, rows = 0;
query_rows(batch, &p0, &rows);
RAD_ISSUE_N(ctx, op_score_part, R, brows(w.codes, W * R * 32),
brows(w.scales, W * R * 32), brows(w.gate, W * R), kv_cache(index, layer),
RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch),
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
bcol_at(w.score, 0, c.blocks, 0, live, R), brows(w.cu_part, S + 1));
RAD_ISSUE_N(ctx, op_select_part, rows, bcol_at(w.score, 0, c.blocks, 0, live, rows),
praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S),
praw(batch->positions + p0, RAD_I32, rows), brows(w.cu_part, S + 1),
brows(w.sel_part, rows), brows(w.nsel, rows), brows(w.len_part, rows));
RAD_ISSUE_N(ctx, op_gather_sel, R * 513, brows(w.sel_part, R), brows(w.selected, W * R));
RAD_ISSUE_N(ctx, op_gather_len, R, brows(w.len_part, R), brows(w.length, W * R));
}
};
struct GlmIndexer {
struct Wire {
rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0;
DsaCache::Wire cache{};
};
Geom g{};
Wire w{};
LinearFP8 query{}, key_gate{};
DsaCache cache{};
rad_weight gain = 0, bias = 0, head_weight = 0;
rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention,
rad_kvgroup tail, rad_kvgroup* index) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || !w.input || !w.q_low || !w.q_wide || !w.kg_raw)
return RAD_E_INVAL;
Geom bg = g;
bg.w_bf16 = true;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
RAD_ARCH_TRY(query.declare(b, nm, bg, nm.f("blk.%d.index_query", l), 4096, 1536,
RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wq_b.weight", prefix) }, act(w.q_low), w.q_wide));
RAD_ARCH_TRY(key_gate.declare(
b, nm, bg, nm.f("blk.%d.index_key_gate", l), 256, 4096, RAD_SHARD_NONE, grp_layer(l),
{ nm.ckpt("%s.wk.weight", prefix), nm.ckpt("%s.index_kpool_compress_gate", prefix) },
act(w.input), w.kg_raw, 0, { 128, 128 }));
const char *gn = nm.f("blk.%d.index_norm.weight", l),
*bn = nm.f("blk.%d.index_norm.bias", l),
*hn = nm.f("blk.%d.index_head.weight", l);
RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.k_norm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.k_norm.bias", prefix)));
RAD_ARCH_TRY(map_copy(b, hn, nm.ckpt("%s.weights_proj.weight", prefix)));
gain = decl_w(b, gn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
head_weight = decl_w(b, hn, RAD_F32, { 32, 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
if (!gain || !bias || !head_weight) return RAD_E_INVAL;
op_norm = rw(b,
RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain, bias)),
{ w.kg_raw }, { w.cache.kg });
op_query_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.q_wide }, { w.cache.query });
op_gate_copy = rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ w.kg_raw }, { w.cache.kg });
op_head = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32),
RAD_INT("K", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(head_weight)),
{ w.input }, { w.cache.gate });
RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index,
nm.ckpt("%s.index_kpool_compress_ape", prefix)));
return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
int64_t r0 = 0, rows = T;
cache.query_rows(batch, &r0, &rows);
/* 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));
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));
cache.step(ctx, batch);
}
};
}
} // namespace rad::arch
#endif
+223
View File
@@ -0,0 +1,223 @@
/* GLM-5.3's KDA layer: the seven bf16 projections around the recurrent core (GlmKda), and the
* core itself over already projected inputs (KdaState), whose ple_conv supplies exactly causal
* depthwise convolution + SiLU, cold start and accepted-history rollback included. The two
* low-rank gate paths have no intervening activation. The caller supplies the normalized input
* and owns the mHC residual connection.
*
* Under tensor parallelism the heads split (GlmTp::heads), and with them the q/k/v rows, the
* convolution taps, the state and the output projection's columns; the two rank-128 projections
* into the gates are replicated. The block's all_reduce sums the output. */
#ifndef RAD_BLOCK_GLM_KDA_H
#define RAD_BLOCK_GLM_KDA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct KdaState {
struct Config {
int64_t heads = 16, dim = 128, width = 4;
double lower = -5;
};
struct Src {
const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr,
*bias = nullptr, *norm = nullptr;
};
struct Wire {
rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup state = 0, history = 0;
rad_weight taps = 0, alog = 0, bias = 0, norm = 0;
rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
layer = l;
state = st;
history = cv;
if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 ||
!std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta ||
!w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv ||
!src.alog || !src.bias || !src.norm)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st));
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv));
const int64_t width = c.heads * c.dim;
const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l),
*bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l);
RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv }));
RAD_ARCH_TRY(map_copy(b, an, src.alog));
RAD_ARCH_TRY(map_copy(b, bn, src.bias));
RAD_ARCH_TRY(map_copy(b, nn, src.norm));
taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, { width, width, width });
alog =
decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
norm =
decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
if (!taps || !alog || !bias || !norm) return RAD_E_INVAL;
op_conv = rw(b,
RAD_OP(b, "ple_conv",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width),
RAD_INT("width", c.width), RAD_INT("dilation", 1),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(taps)),
{ w.qkv }, { w.conv });
for (int verify = 0; verify < 2; ++verify) {
const rad_op op = rw(
b,
RAD_OP(b, "kda_update",
RAD_PARAMS(
RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim),
RAD_F64("lower_bound", c.lower),
RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)),
RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"),
RAD_STR("dtype", "bf16"),
RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")),
RAD_WEIGHTS(alog, bias)),
{ w.conv, w.a, w.beta }, { w.out });
if (verify)
op_verify = op;
else
op_prefill = op;
}
op_norm = rw(b,
RAD_OP(b, "gdn_gated_rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim),
RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")),
RAD_WEIGHTS(norm)),
{ w.out, w.gate }, { w.out });
return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history);
if (!st || !cv || !st->state_index || !cv->state_index) {
rad_step_fail(ctx, "KDA requires recurrent and convolution state indices");
return;
}
const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim;
const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
for (int verify = 1; verify >= 0; --verify) {
const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T;
if (!seqs) continue;
const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1);
const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs);
const RadOperand accepted =
verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE;
RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps),
kv_cache(history, layer), cu, RAD_NONE,
praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted,
brows(w.conv, rows));
RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows),
bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows),
brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias),
kv_cache(state, layer),
praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted,
init, brows(w.out, rows));
}
RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm),
brows(w.out, T));
}
};
struct GlmKda {
struct Wire {
rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0;
KdaState::Wire core{};
};
Geom g{};
Wire w{};
KdaState core{};
LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{};
rad_op op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire,
const char* prefix, const KdaState::Src& src, rad_kvgroup state,
rad_kvgroup history, bool reduce = true) {
g = geom;
w = wire;
if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
w.forget_low == w.gate_low)
return RAD_E_INVAL;
// All seven projections are plain BF16 in the pinned checkpoint.
Geom bg = g;
bg.w_bf16 = true;
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
const auto group = grp_layer(layer);
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
RAD_ARCH_TRY(qkv.declare(
b, nm, bg, nm.f("blk.%d.attn_qkv", layer), 3 * width, 4096, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.q_proj.weight", prefix), nm.ckpt("%s.k_proj.weight", prefix),
nm.ckpt("%s.v_proj.weight", prefix) },
input, w.core.qkv, 0, { width, width, width }));
RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096,
RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) },
input, w.core.beta));
/* Both low-rank down-projections before either up-projection, in step() as here: the
* four reads of the input then share one ordered point of a recorded pass and the two
* up-projections the next, where forget_b between them cost a third. Declared in the
* issue order because the buffer plan takes lifetimes from this list, and forget_low and
* gate_low must not share bytes while both are live. */
RAD_ARCH_TRY(forget_a.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group,
{ nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low));
RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096,
RAD_SHARD_NONE, group,
{ nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low));
RAD_ARCH_TRY(forget_b.declare(
b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group,
{ nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a));
RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128,
RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) },
act(w.gate_low), w.core.gate));
KdaState::Config cfg;
cfg.heads = heads;
RAD_ARCH_TRY(core.declare(b, nm, bg, layer, state, history, cfg, w.core, src));
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
act(w.core.out), w.out));
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
!gate_b.bf16 || !output.bf16)
return RAD_E_UNSUPPORTED;
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
}
void step(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
auto act = [](rad_buf x) {
ActFP8 a{};
a.x = x;
return a;
};
const auto input = act(w.input);
qkv.step(ctx, input, w.core.qkv, T);
beta.step(ctx, input, w.core.beta, T);
forget_a.step(ctx, input, w.forget_low, T);
gate_a.step(ctx, input, w.gate_low, T);
forget_b.step(ctx, act(w.forget_low), w.core.a, T);
gate_b.step(ctx, act(w.gate_low), w.core.gate, T);
core.step(ctx, batch);
output.step(ctx, act(w.core.out), w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+138
View File
@@ -0,0 +1,138 @@
/* GLM-5.3's manifold-constrained residual connections (mHC): four residual streams in one
* 16384-wide row. read() mixes them down to the block's 4096-wide input and saves the mixing
* coefficients; write() adds the block's output back into every stream. The mixed residual must
* have a separate destination: each output stream reads every original input stream. */
#ifndef RAD_BLOCK_GLM_MHC_H
#define RAD_BLOCK_GLM_MHC_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct ManifoldConn {
struct Config {
int64_t hc = 4, iterations = 20;
double eps = 1e-6, hc_eps = 1e-6;
};
struct Src {
const char *fn = nullptr, *scale = nullptr, *base = nullptr;
};
struct Wire {
rad_buf h = 0, x = 0, y = 0, out = 0;
// Saved by read(), consumed by write() after the block produces y.
rad_buf post = 0, comb = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight w_fn = 0, w_scale = 0, w_base = 0;
rad_op op_pre = 0, op_post = 0;
/* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank
* computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them,
* and mhc_pre_finish completes the read on every rank (rad_glm_tp.h). */
static constexpr int64_t kChunk = 2048, kPartStride = 28;
rad_buf part = 0, parts = 0;
rad_op op_partial = 0, op_gather = 0, op_finish = 0;
int64_t split_rows = 0, part_row = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src, bool defer_post = false) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 ||
c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 ||
!std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 ||
!w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x ||
w.h == w.y || w.x == w.out || w.y == w.out || w.post == w.comb)
return RAD_E_INVAL;
const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2);
const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name),
*base = nm.f("%s.base", name);
RAD_ARCH_TRY(map_copy(b, fn, src.fn));
RAD_ARCH_TRY(map_copy(b, scale, src.scale));
RAD_ARCH_TRY(map_copy(b, base, src.base));
// Mixing coefficients are F32 in the checkpoint; keep them replicated under TP.
const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight ws = w_scale = decl_w(b, scale, RAD_F32, { 3 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
if (!wf || !ws || !wb) return RAD_E_INVAL;
op_pre = rw(b,
RAD_OP(b, "mhc_pre",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(wf, ws, wb)),
{ w.h }, { w.x, w.post, w.comb });
if (!op_pre) return RAD_E_INVAL;
RAD_ARCH_TRY(declare_split(b, nm, name));
return defer_post ? RAD_OK : declare_post(b);
}
int declare_split(RadBuilder* b, Names& nm, const char* name) {
const int64_t total = c.hc * g.n_embd / kChunk;
split_rows = GlmTp::kSplitRows;
if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) {
split_rows = 0;
return RAD_OK;
}
const int64_t mine = total / g.world, T = g.max_tok;
part_row = mine * kPartStride;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { T, part_row });
parts = decl_b(b, nm.f("%s.parts", name), RAD_F32, { T, total * kPartStride });
op_partial =
rw(b,
RAD_OP(b, "mhc_pre_partial",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc),
RAD_INT("chunk", kChunk), RAD_INT("first", g.rank * mine),
RAD_INT("chunks", mine), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fn)),
{ w.h }, { part });
op_gather = rw(b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", part_row, T * part_row),
RAD_STR("dtype", "f32"), RAD_INT("row", part_row)),
RAD_NOWEIGHTS),
{ part }, { parts });
op_finish = rw(b,
RAD_OP(b, "mhc_pre_finish",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations),
RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps),
RAD_INT("chunk", kChunk), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_scale, w_base)),
{ parts, w.h }, { w.x, w.post, w.comb });
return part && parts && op_partial && op_gather && op_finish ? RAD_OK : RAD_E_INVAL;
}
int declare_post(RadBuilder* b) {
op_post = rw(b,
RAD_OP(b, "mhc_post",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ w.y, w.h, w.post, w.comb }, { w.out });
return op_post ? RAD_OK : RAD_E_INVAL;
}
void read(RadCtx* ctx, int64_t rows) const {
if (split_rows && rows >= split_rows) {
RAD_ISSUE_N(ctx, op_partial, rows, brows(w.h, rows), RAD_W(w_fn), brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * part_row, brows(part, rows), brows(parts, rows));
RAD_ISSUE_N(ctx, op_finish, rows, brows(parts, rows), brows(w.h, rows), RAD_W(w_scale),
RAD_W(w_base), brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
return;
}
RAD_ISSUE_N(ctx, op_pre, rows, brows(w.h, rows), RAD_W(w_fn), RAD_W(w_scale), RAD_W(w_base),
brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows));
}
void write(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_post, rows, brows(w.y, rows), brows(w.h, rows), brows(w.post, rows),
brows(w.comb, rows), brows(w.out, rows));
}
};
}
} // namespace rad::arch
#endif
+190
View File
@@ -0,0 +1,190 @@
/* GLM-5.3's sparse latent attention (MLA, no RoPE): the projections and the latent cache store
* around the absorbed core (GlmMla), and the core itself over the latent cache (MlaLatent), whose
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
*
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
* replicated. */
#ifndef RAD_BLOCK_GLM_MLA_H
#define RAD_BLOCK_GLM_MLA_H
#include "rad_fp8.h"
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct MlaLatent {
struct Config {
int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513;
};
struct Wire {
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0;
};
Geom g{};
Config c{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
rad_weight projection = 0;
rad_op op_absorb = 0, op_attn = 0, op_expand = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
const Config& cfg, const Wire& wire, const char* source) {
g = geom;
c = cfg;
w = wire;
layer = l;
kv = group;
if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent ||
!w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent ||
w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 ||
c.head_dim != 256)
return RAD_E_INVAL;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group));
const char* name = nm.f("blk.%d.attn_kv_b.weight", l);
RAD_ARCH_TRY(map_copy(b, name, source));
// The conversion recipe decodes this small projection only.
projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim },
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
if (!projection) return RAD_E_INVAL;
op_absorb = rw(
b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.q }, { w.q_latent });
op_attn =
rw(b,
RAD_OP(b, "mla_attn",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim),
RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks),
RAD_INT("block_size", 4),
RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.q_latent, w.selected, w.length }, { w.attn_latent });
if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL;
op_expand = rw(
b,
RAD_OP(b, "mla_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim),
RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.attn_latent }, { w.out });
return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL;
}
void step(RadCtx* ctx, int64_t rows) const {
RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection),
brows(w.q_latent, rows));
RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer),
brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows));
RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection),
brows(w.out, rows));
}
};
struct GlmMla {
struct Wire {
ActFP8 input{}, q_low{}, attn{};
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
MlaLatent::Wire core{};
};
Geom g{};
Wire w{};
int layer = 0;
rad_kvgroup kv = 0;
LinearFP8 q_a{}, kv_a{}, q_b{}, output{};
NormQuantFP8 q_norm{};
QuantFP8 attn_quant{};
MlaLatent core{};
rad_weight q_gain = 0, kv_gain = 0;
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const char* prefix, rad_kvgroup group, bool reduce = true,
bool defer_finish = false) {
g = geom;
w = wire;
layer = l;
kv = group;
if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world ||
!w.input.x || !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x ||
w.attn.x != w.core.out)
return RAD_E_INVAL;
const auto wg = grp_layer(l);
RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), 1536, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.q_a_proj.weight", prefix) }, w.input, w.q_raw));
RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), 512, 4096, RAD_SHARD_NONE,
wg, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", prefix) }, w.input,
w.kv_raw));
const char* qn = nm.f("blk.%d.attn_q_a_norm.weight", l);
const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, qn, nm.ckpt("%s.q_a_layernorm.weight", prefix)));
RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", prefix)));
q_gain = decl_w(b, qn, RAD_F32, { 1536 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
kv_gain = decl_w(b, kn, RAD_F32, { 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
if (!q_gain || !kv_gain) return RAD_E_INVAL;
RAD_ARCH_TRY(q_norm.declare(b, g, q_gain, w.q_raw, w.q_low, 1536));
op_kv_norm = rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 512),
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(kv_gain)),
{ w.kv_raw }, { w.latent });
if (!op_kv_norm) return RAD_E_INVAL;
RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world),
1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
w.q_low, w.core.q));
// Cache stores contiguous halves of the normalized latent, with no duplicated K/V.
op_store = rw(b,
RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256),
RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4),
RAD_STR("kv_dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.latent }, {});
if (!op_store) return RAD_E_INVAL;
return defer_finish ? RAD_OK : declare_finish(b, nm, prefix, reduce);
}
int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) {
MlaLatent::Config cfg;
cfg.heads = GlmTp::heads(g.world);
RAD_ARCH_TRY(
core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix)));
RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, GlmTp::mla_width(g.world)));
RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096,
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
}
void prepare(RadCtx* ctx, const RadBatch* batch) const {
const auto* kb = kv_batch(batch, kv);
if (!kb || !kb->slot_mapping) {
rad_step_fail(ctx, "GLM MLA requires latent cache slot mapping");
return;
}
const int64_t T = batch->n_tok;
q_a.step(ctx, w.input, w.q_raw, T);
kv_a.step(ctx, w.input, w.kv_raw, T);
q_norm.step(ctx, T);
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
q_b.step(ctx, w.q_low, w.core.q, T);
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
}
void finish(RadCtx* ctx, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
core.step(ctx, T);
attn_quant.step(ctx, T);
output.step(ctx, w.attn, w.out, T);
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
}
};
}
} // namespace rad::arch
#endif
+194
View File
@@ -0,0 +1,194 @@
/* GLM-5.3's draft head: checkpoint layer 45 as a serial drafter (RAD_DRAFT_SERIAL), around the
* one MLA + indexer + MoE layer the plugin declares and steps itself.
*
* h = gather(the trunk's final hidden states, at the rows this pass continues from)
* e = embed(the token one position on), the encoder's rows over its placeholders
* x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first
* x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer
* h' = shared_head.norm(x); logits = the trunk's lm_head over h'
*
* h' is both the logits input and the next round's `h`. No mHC: the layer's residual is a plain
* add. By the sign of RadBatch::draft_pass a history pass (< 0) covers every row the trunk step
* had, fills the draft layer's latent, index and tail for all of them and runs the MoE and the
* head on the proposal rows only (draft_out_ids); a draft round (> 1) is one row a sequence.
*
* The block is declared and stepped in three parts around the layer, in this order: `inputs`
* before the layer's attention, `join` (the residual add and the proposal rows' selection) between
* its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's.
* Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj
* (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */
#ifndef RAD_BLOCK_GLM_MTP_H
#define RAD_BLOCK_GLM_MTP_H
#include "rad_glm_tp.h"
#include "rad_block_vit.h"
namespace rad {
namespace arch {
struct GlmMtp {
/* The trunk's: its final hidden states, its logits, its embedding and head. */
struct Wire {
rad_buf final_hidden = 0, logits = 0;
rad_weight token = 0, head = 0;
};
static constexpr int kDepth = 3; /* --num-speculative-tokens auto */
Names nm{ "mtp" };
Geom g{};
Wire w{};
rad_buf x = 0, hidden = 0, embedding = 0, concat = 0, out = 0;
rad_weight en = 0, hn = 0, eh = 0, norm = 0;
rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0;
rad_op op_residual = 0, op_select = 0, op_back = 0;
rad_op op_norm = 0, op_copy = 0, op_head = 0;
MediaRows mrows{};
/* The buffers, the weights, and the ops up to the layer's input. `media`: the encoder's rows
* replace the placeholders' embeddings, as the target's do (SGLang feeds its draft model the
* target's image rows); without them the drafts read the placeholder's embedding and
* acceptance falls on a prompt with a picture. */
int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire, bool media) {
g = geom;
w = wire;
if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1)
return RAD_E_INVAL;
x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 });
hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST);
embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 });
concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 });
out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 });
const char* pre = "model.language_model.layers.45";
auto gain = [&](const char* n, const char* src) {
const char* name = nm.f("%s", n);
if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0;
return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(45));
};
en = gain("enorm.weight", "enorm.weight");
hn = gain("hnorm.weight", "hnorm.weight");
norm = gain("output_norm.weight", "shared_head.norm.weight");
RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre)));
eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(45));
if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh)
return RAD_E_INVAL;
op_prev = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ w.final_hidden }, { hidden });
op_embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(w.token)),
{}, { embedding });
if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding));
op_embed_ar = GlmTp::reduce(b, g, embedding, true);
op_en = rmsnorm(b, en, embedding, concat);
op_hn = rmsnorm(b, hn, hidden, concat);
op_eh = rw(b,
RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096),
RAD_INT("K", 8192), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(eh)),
{ concat }, { x });
return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar)
? RAD_OK
: RAD_E_INVAL;
}
/* Between the layer's attention and its feed-forward: the residual add of the attention's
* output `y`, and on a history pass the proposal rows gathered to the head of `x`. */
int declare_join(RadBuilder* b, rad_buf y) {
op_residual = rw(b,
RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x, y }, { x });
// All history rows fill the draft cache; only proposal rows need its FFN.
op_select = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x }, { hidden });
op_back = cast(b, hidden, x);
return op_residual && op_select && op_back ? RAD_OK : RAD_E_INVAL;
}
/* After the layer: the head's norm, its output kept as the next round's hidden, the logits,
* and the drafter's declaration. */
int declare_head(RadBuilder* b) {
op_norm = rmsnorm(b, norm, x, out);
op_copy = cast(b, out, hidden);
op_head = rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w.head)),
{ hidden }, { w.logits });
if (!op_norm || !op_copy || !op_head) return RAD_E_INVAL;
RadDrafterDecl dd{};
dd.name = "mtp";
dd.kind = RAD_DRAFT_SERIAL;
dd.depth = g.max_spec;
dd.mask_token = -1;
return rad_declare_drafter(b, &dd);
}
/* The rows a pass runs its feed-forward and head on: the proposal rows of a history pass,
* every row of a draft round. */
static int64_t head_rows(const RadBatch* batch) {
return batch->draft_pass < 0 ? batch->n_draft_out : batch->n_tok;
}
void step_inputs(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (batch->draft_pass < 0 && batch->n_out > 0)
RAD_ISSUE_N(c, op_prev, batch->n_out, RAD_B(w.final_hidden),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out));
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token),
brows(embedding, T));
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));
RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T));
}
void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const {
const int64_t T = batch->n_tok, L = head_rows(batch);
RAD_ISSUE_N(c, op_residual, T, brows(x, T), brows(y, T), brows(x, T));
if (batch->draft_pass < 0) {
RAD_ISSUE_N(c, op_select, L, RAD_B(x), praw(batch->draft_out_ids, RAD_I32, L),
brows(hidden, L));
RAD_ISSUE_N(c, op_back, L, brows(hidden, L), brows(x, L));
}
}
void step_head(RadCtx* c, const RadBatch* batch) const {
const int64_t L = head_rows(batch);
RAD_ISSUE_N(c, op_norm, L, brows(x, L), RAD_W(norm), brows(out, L));
RAD_ISSUE_N(c, op_copy, L, brows(out, L), brows(hidden, L));
RAD_ISSUE_N(c, op_head, L, brows(hidden, L), RAD_W(w.head), brows(w.logits, L));
}
private:
rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(gain)),
{ in }, { out });
}
rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ in }, { out });
}
};
}
} // namespace rad::arch
#endif
+82
View File
@@ -0,0 +1,82 @@
/* GLM noaux_tc router. Correction bias changes selection only; mixture weights
* come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */
#ifndef RAD_BLOCK_GLM_ROUTER_H
#define RAD_BLOCK_GLM_ROUTER_H
#include "rad_glm_tp.h"
#include <cmath>
namespace rad {
namespace arch {
struct GlmRouter {
struct Config {
int64_t experts = 288, top_k = 8, rows = 32;
int norm = 1;
double route_scale = 2.5;
};
struct Src {
const char *weight = nullptr, *correction = nullptr;
};
struct Wire {
rad_buf input = 0, logits = 0, ids = 0, weights = 0;
};
Geom g{};
Config c{};
Wire w{};
rad_weight projection = 0, correction = 0;
rad_op op_project = 0, op_select = 0;
SplitF32Proj split{};
int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name,
const Config& cfg, const Wire& wire, const Src& src) {
g = geom;
c = cfg;
w = wire;
if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 ||
c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 ||
c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input ||
!w.logits || !w.ids || !w.weights || w.logits == w.weights)
return RAD_E_INVAL;
const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name);
RAD_ARCH_TRY(map_copy(b, pn, src.weight));
RAD_ARCH_TRY(map_copy(b, cn, src.correction));
projection = decl_w(b, pn, RAD_F32, { c.experts, g.n_embd }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_layer(layer));
correction = decl_w(b, cn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(layer));
if (!projection || !correction) return RAD_E_INVAL;
op_project = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.experts),
RAD_INT("K", g.n_embd), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(projection)),
{ w.input }, { w.logits });
RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input,
w.logits));
op_select =
rw(b,
RAD_OP(b, "router_sigmoid_topk",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts),
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm),
RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")),
RAD_WEIGHTS(correction)),
{ w.logits }, { w.ids, w.weights });
return op_project && op_select ? RAD_OK : RAD_E_INVAL;
}
void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
if (split.takes(rows))
split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection,
brow_slice(w.logits, output_first, rows, c.experts));
else
RAD_ISSUE_N(ctx, op_project, rows, brow_slice(w.input, first, rows, g.n_embd),
RAD_W(projection), brow_slice(w.logits, output_first, rows, c.experts));
}
void step(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const {
project(ctx, first, rows, output_first);
RAD_ISSUE_N(ctx, op_select, rows, brow_slice(w.logits, output_first, rows, c.experts),
RAD_W(correction), brow_slice(w.ids, output_first, rows, c.top_k),
brow_slice(w.weights, output_first, rows, c.top_k));
}
};
}
} // namespace rad::arch
#endif
+379
View File
@@ -0,0 +1,379 @@
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
* glm5next.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
* patch row is (channel, frame, y, x), no position
* table
* depth times:
* h = RMS(x) gain only
* q, k, v = qkv(h) with bias; q and k RMS-normed per head with a
* gain, then a 2-D rotary over (row, column):
* `axial` over NeoX pairs (i, i + head_dim / 2),
* the row on the first head_dim / 4 frequencies and
* the column on the next, each on its own ladder
* x += proj(attn(q, k, v)) full attention within a segment (one picture)
* x += down(silu(min(g, L)) * clamp(u, -L, L)), g | u = gate_up(RMS(x)) all with bias
* y = RMS(x) post_layernorm
* d = conv2d(y viewed [rows / 2, 2, 2, width], 2 x 2, stride 2) + bd the downsample: one row
* a merged block of merge x merge patches
* out = down'(silu(min(g', L)) * clamp(u', -L, L)), g' | u' = gate_up'(gelu(LN(proj'(d))))
* the merger: no biases but the LayerNorm's, exact
* GELU, the clip of the blocks
*
* which is the reference module for module. The processor stages patches in merge-block order (the
* merge x merge patches of one output row consecutive), so the downsample's input view is the
* reference's own: `conv2d_unfold` writes each merged block's receptive field as one row, its
* columns in the checkpoint weight's order (channel, kernel row, kernel column), and the weight is
* read as stored. Every linear with a bias is `gemm_nt_bias`, its residual in the epilogue.
*
* Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the
* weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx::
* max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's
* step and nothing is declared to the core. */
#ifndef RAD_BLOCK_GLM_VISION_H
#define RAD_BLOCK_GLM_VISION_H
#include "rad_arch.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace rad {
namespace arch {
struct GlmVision {
/* Geometry, from the container's vision_config. */
int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0;
int64_t chans = 0, merge = 0, n_embd = 0, proj_ff = 0, patch_dim = 0, P = 0;
double eps = 1e-5, theta = 10000.0, limit = 0.0;
bool on = false;
struct Layer {
rad_weight n1 = 0, qkv_w = 0, qkv_b = 0, q_norm = 0, k_norm = 0, out_w = 0, out_b = 0;
rad_weight n2 = 0, gu_w = 0, gu_b = 0, down_w = 0, down_b = 0;
rad_op op_n1 = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_gu = 0;
rad_op op_act = 0, op_down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_post = 0, w_ds = 0, b_ds = 0;
rad_weight w_mproj = 0, w_mln = 0, b_mln = 0, w_mgu = 0, w_mdown = 0;
rad_op op_patch = 0, op_post = 0, op_unfold = 0, op_ds = 0, op_mproj = 0, op_mln = 0;
rad_op op_gelu = 0, op_mgu = 0, op_mact = 0, op_mdown = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_post = 0, b_unf = 0;
rad_buf b_d = 0, b_m = 0, b_mgu = 0, b_mff = 0, b_out = 0;
char sec[48] = {};
/* Whether the container carries GLM-5.3's tower. */
static bool present(const RadModelMeta* m) {
const char* t = rad_meta_gets(m, "vision_config.model_type", "");
return t && !std::strcmp(t, "glm5_next_vision");
}
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 GlmVision::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.depth", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
temporal = rad_meta_geti(m, "vision_config.temporal_patch_size", 0);
chans = rad_meta_geti(m, "vision_config.in_channels", 3);
merge = rad_meta_geti(m, "vision_config.spatial_merge_size", 0);
n_embd = rad_meta_geti(m, "vision_config.out_hidden_size", 0);
proj_ff = rad_meta_geti(m, "vision_config.projection_intermediate_size", 0);
eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-5);
limit = rad_meta_getf(m, "vision_config.swiglu_limit", 0.0);
/* The checkpoint states no rotary; the reference's default is axial at 10000. */
theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0);
const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial");
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "");
const bool bias = rad_meta_geti(m, "vision_config.attention_bias", 1) != 0;
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
chans <= 0 || merge <= 0 || n_embd <= 0 || proj_ff <= 0 || width % heads ||
(width / heads) % 4 || !(eps > 0) || !(theta > 0)) {
fprintf(stderr, "radiance: glm5next: the container's vision_config is incomplete or "
"inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"merge %lld, out %lld, projection %lld)\n", (long long)depth,
(long long)width, (long long)heads, (long long)ff, (long long)patch,
(long long)merge, (long long)n_embd, (long long)proj_ff);
return RAD_E_INVAL;
}
/* The clipped SwiGLU, the axial rotary and the biased linears are what this tower is; a
* checkpoint that turns one of them off is another tower. */
if (std::strcmp(act, "silu") || !(limit > 0) || !std::isfinite(limit) ||
std::strcmp(rt, "axial") || !bias) {
fprintf(stderr, "radiance: glm5next: this vision tower has a '%s' activation, swiglu_limit "
"%g, a '%s' rotary or no attention bias; it serves silu, a positive "
"limit, axial and biased linears\n", act, limit, rt);
return RAD_E_UNSUPPORTED;
}
/* The merger's rows replace token embeddings, so they must be the model's width. */
if (n_embd != model_embd) {
fprintf(stderr, "radiance: glm5next: the vision tower emits %lld-wide rows and the model "
"embeds %lld-wide tokens\n", (long long)n_embd, (long long)model_embd);
return RAD_E_INVAL;
}
head_dim = width / heads;
patch_dim = chans * temporal * patch * patch;
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4),
(long long)(head_dim / 4));
const int64_t mm = merge * merge;
P = ctx->max_enc_patches;
/* The longest segment attention may see: the real pass size, even in a sizing declare (see
* rad_block_vit.h). */
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);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
/* ---- weights, replicated: model-level groups for the stem, downsample and merger, one group
* a block from `first_group` on. gate and up are joined into one GEMM, gate first, as
* swiglu_clamped splits its operand. */
auto copy = [&](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);
};
auto join = [&](const char* dn, const char* gate, const char* up,
std::initializer_list<int64_t> shp, RadWeightGroup g) -> rad_weight {
if (map_concat(b, dn, { gate, up }) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* V = "model.visual";
w_patch = copy(nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", V),
{ width, patch_dim }, grp_model());
b_patch = copy(nm.f("v.patch.bias"), nm.ckpt("%s.patch_embed.proj.bias", V), { 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;
auto src = [&](const char* s) { return nm.ckpt("%s.blocks.%d.%s", V, li, s); };
auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); };
l.n1 = copy(dn("norm1.weight"), src("norm1.weight"), { width }, g);
l.qkv_w = copy(dn("qkv.weight"), src("attn.qkv.weight"), { 3 * width, width }, g);
l.qkv_b = copy(dn("qkv.bias"), src("attn.qkv.bias"), { 3 * width }, g);
l.q_norm = copy(dn("q_norm.weight"), src("attn.q_norm.weight"), { head_dim }, g);
l.k_norm = copy(dn("k_norm.weight"), src("attn.k_norm.weight"), { head_dim }, g);
l.out_w = copy(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g);
l.out_b = copy(dn("proj.bias"), src("attn.proj.bias"), { width }, g);
l.n2 = copy(dn("norm2.weight"), src("norm2.weight"), { width }, g);
l.gu_w = join(dn("gate_up.weight"), src("mlp.gate_proj.weight"), src("mlp.up_proj.weight"),
{ 2 * ff, width }, g);
l.gu_b = join(dn("gate_up.bias"), src("mlp.gate_proj.bias"), src("mlp.up_proj.bias"),
{ 2 * ff }, g);
l.down_w = copy(dn("down.weight"), src("mlp.down_proj.weight"), { width, ff }, g);
l.down_b = copy(dn("down.bias"), src("mlp.down_proj.bias"), { width }, g);
if (!l.n1 || !l.qkv_w || !l.qkv_b || !l.q_norm || !l.k_norm || !l.out_w || !l.out_b ||
!l.n2 || !l.gu_w || !l.gu_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
w_post = copy(nm.f("v.post_norm.weight"), nm.ckpt("%s.post_layernorm.weight", V), { width },
grp_model());
/* [out, width, merge, merge] read as [out, width * merge^2]: conv2d_unfold's column order. */
w_ds = copy(nm.f("v.downsample.weight"), nm.ckpt("%s.downsample.weight", V),
{ n_embd, mm * width }, grp_model());
b_ds = copy(nm.f("v.downsample.bias"), nm.ckpt("%s.downsample.bias", V), { n_embd },
grp_model());
w_mproj = copy(nm.f("v.merger.proj.weight"), nm.ckpt("%s.merger.proj.weight", V),
{ n_embd, n_embd }, grp_model());
w_mln = copy(nm.f("v.merger.norm.weight"),
nm.ckpt("%s.merger.post_projection_norm.weight", V), { n_embd }, grp_model());
b_mln = copy(nm.f("v.merger.norm.bias"), nm.ckpt("%s.merger.post_projection_norm.bias", V),
{ n_embd }, grp_model());
w_mgu = join(nm.f("v.merger.gate_up.weight"), nm.ckpt("%s.merger.gate_proj.weight", V),
nm.ckpt("%s.merger.up_proj.weight", V), { 2 * proj_ff, n_embd }, grp_model());
w_mdown = copy(nm.f("v.merger.down.weight"), nm.ckpt("%s.merger.down_proj.weight", V),
{ n_embd, proj_ff }, grp_model());
if (!w_patch || !b_patch || !w_post || !w_ds || !b_ds || !w_mproj || !w_mln || !b_mln ||
!w_mgu || !w_mdown)
return RAD_E_INVAL;
/* ---- activations. `post` is declared at merge x width: the norm writes P rows of `width`
* and conv2d_unfold reads the same bytes as P / merge rows of `merge` columns (dh rows of dw
* columns), the reference's view() with 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_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, { P, 2 * ff });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_post = decl_b(b, nm.f("v.post"), RAD_BF16, { P / merge, merge * width });
b_unf = decl_b(b, nm.f("v.unf"), RAD_BF16, { R, mm * width });
b_d = decl_b(b, nm.f("v.d"), RAD_BF16, { R, n_embd });
b_m = decl_b(b, nm.f("v.m"), RAD_BF16, { R, n_embd });
b_mgu = decl_b(b, nm.f("v.mgu"), RAD_BF16, { R, 2 * proj_ff });
b_mff = decl_b(b, nm.f("v.mff"), RAD_BF16, { R, proj_ff });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_gu || !b_ff || !b_post || !b_unf || !b_d || !b_m ||
!b_mgu || !b_mff || !b_out)
return RAD_E_INVAL;
auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight bw) -> 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", "none")),
RAD_WEIGHTS(w, bw));
};
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 rms = [&](int64_t rows, rad_weight w) -> rad_op {
return RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w));
};
auto swiglu = [&](int64_t rows, int64_t n) -> rad_op {
return RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("limit", limit), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS);
};
op_patch = rw(b, gemm_b(P, width, patch_dim, w_patch, b_patch), {}, { b_x });
for (Layer& l : L) {
l.op_n1 = rw(b, rms(P, l.n1), { b_x }, { b_h });
l.op_qkv = rw(b, gemm_b(P, 3 * width, width, l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads),
RAD_F64("theta", theta), RAD_F64("eps", eps),
RAD_STR("mode", "axial"),
RAD_INT("rotary_dim", head_dim),
RAD_STR("sections", sec)),
RAD_WEIGHTS(l.q_norm, l.k_norm)),
{ b_qkv }, { b_qkv });
l.op_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.op_proj = rw(b, gemm_b(P, width, width, l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.op_n2 = rw(b, rms(P, l.n2), { b_x }, { b_h });
l.op_gu = rw(b, gemm_b(P, 2 * ff, width, l.gu_w, l.gu_b), { b_h }, { b_gu });
l.op_act = rw(b, swiglu(P, ff), { b_gu }, { b_ff });
l.op_down = rw(b, gemm_b(P, width, ff, l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, rms(P, w_post), { b_x }, { b_post });
/* Input rows are P / merge (one kernel row of merge patches each) and a segment's rows are its
* patches over merge, so a picture of whole merged blocks starts on an even row. */
op_unfold = rw(b, RAD_OP(b, "conv2d_unfold",
RAD_PARAMS(RAD_RANGE("M", 1, P / merge), RAD_INT("width", merge),
RAD_INT("cin", width), RAD_INT("kh", merge),
RAD_INT("kw", merge), RAD_INT("stride", merge),
RAD_INT("pad", 0), RAD_INT("cu_div", merge),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_post }, { b_unf });
op_ds = rw(b, gemm_b(R, n_embd, mm * width, w_ds, b_ds), { b_unf }, { b_d });
op_mproj = rw(b, gemm(R, n_embd, n_embd, w_mproj), { b_d }, { b_m });
/* torch.nn.LayerNorm's default eps: the merger states none. */
op_mln = rw(b, RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_mln, b_mln)),
{ b_m }, { b_d });
op_gelu = rw(b, RAD_OP(b, "gelu",
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ b_d }, { b_m });
op_mgu = rw(b, gemm(R, 2 * proj_ff, n_embd, w_mgu), { b_m }, { b_mgu });
op_mact = rw(b, swiglu(R, proj_ff), { b_mgu }, { b_mff });
op_mdown = rw(b, gemm(R, n_embd, proj_ff, w_mdown), { b_mff }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld clipped at %g, "
"patch %lld x %lld x %lld, %lld x %lld downsample, merger %lld; %lld patches a "
"pass -> %lld rows of %lld", (long long)depth, (long long)width,
(long long)heads, (long long)head_dim, (long long)ff, limit, (long long)temporal,
(long long)patch, (long long)patch, (long long)merge, (long long)merge,
(long long)proj_ff, (long long)P, (long long)R, (long long)n_embd);
}
on = true;
return RAD_OK;
}
inline void GlmVision::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, Rn = Pn / mm;
if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or "
"more patches than it was declared for, or not whole merged rows");
return;
}
/* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column)) and segment boundaries,
* staged by the core. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.op_n1, Pn, brows(b_x, Pn), RAD_W(l.n1), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_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.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
RAD_ISSUE_N(c, l.op_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.op_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.op_n2, Pn, brows(b_x, Pn), RAD_W(l.n2), brows(b_h, Pn));
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gu_w), RAD_W(l.gu_b), RAD_NONE,
brows(b_gu, Pn));
RAD_ISSUE_N(c, l.op_act, Pn, brows(b_gu, Pn), brows(b_ff, Pn));
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The norm writes Pn rows of `width`; the unfold reads them as Pn / merge rows. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(w_post), brows(b_post, Pn / merge));
RAD_ISSUE_N(c, op_unfold, Pn / merge, brows(b_post, Pn / merge), cu, RAD_NONE,
brows(b_unf, Rn));
RAD_ISSUE_N(c, op_ds, Rn, brows(b_unf, Rn), RAD_W(w_ds), RAD_W(b_ds), RAD_NONE,
brows(b_d, Rn));
RAD_ISSUE_N(c, op_mproj, Rn, brows(b_d, Rn), RAD_W(w_mproj), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mln, Rn, brows(b_m, Rn), RAD_W(w_mln), RAD_W(b_mln), brows(b_d, Rn));
RAD_ISSUE_N(c, op_gelu, Rn, brows(b_d, Rn), brows(b_m, Rn));
RAD_ISSUE_N(c, op_mgu, Rn, brows(b_m, Rn), RAD_W(w_mgu), brows(b_mgu, Rn));
RAD_ISSUE_N(c, op_mact, Rn, brows(b_mgu, Rn), brows(b_mff, Rn));
RAD_ISSUE_N(c, op_mdown, Rn, brows(b_mff, Rn), RAD_W(w_mdown), brows(b_out, Rn));
}
} /* namespace arch */
} /* namespace rad */
#endif /* RAD_BLOCK_GLM_VISION_H */
+98
View File
@@ -368,6 +368,104 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
* every block leaves its delta in the activation its norm produced, and the input is dead by
* then. */
/* ================================================================== the control-vector projection
*
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
* for a request, a steered layer's wide stream is projected off that layer's direction right after
* the feed-forward's write:
*
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
*
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
*
* Two properties the architecture plugin does not have to think about, both here:
*
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
* the table at issue, so nothing is configured per deployment or scanned per layer.
*
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
* deployment without a vector declares no op, no buffer and no branch in the step. */
struct HcProject {
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
const float* dir = nullptr; /* this layer's row of the device direction table */
rad_buf on = 0; /* [rows] int32: 1 = project this row */
rad_buf h = 0; /* the model's wide stream */
int64_t n = 0, hc = 0;
bool steered() const { return op != 0; }
/* The per-token switch, declared once per model as a derived buffer. 0 when the deployment has
* no vector (or one of another width), which leaves every layer unsteered. */
static rad_buf declare_mask(RadBuilder* b, const char* name, const Geom& g,
const RadControlVector* cv) {
if (!b || g.n_embd <= 0 || g.max_tok <= 0) return 0;
if (!cv || !cv->dir || cv->n_layers <= 0) return 0;
if (cv->n_embd != g.n_embd) {
fprintf(stderr, "radiance: %s: the control vector is %lld wide and this model's "
"residual streams are %lld; not steering it\n",
name, (long long) cv->n_embd, (long long) g.n_embd);
return 0;
}
RadBufDecl d{};
d.dtype = RAD_I32;
d.rank = 1;
d.shape[0] = g.max_tok;
d.kind = RAD_BUF_DERIVED;
d.domain = RAD_DOMAIN_DEVICE;
d.derive = "projection_on_rows";
return rad_decl_buffer(b, name, &d);
}
/* `layer`'s projection, when the vector steers it. Called for every layer; the unsteered ones
* (outside the file, outside the range, or no vector at all) declare nothing. */
int declare(RadBuilder* b, const char* name, const Geom& g, int64_t layer,
const RadControlVector* cv, rad_buf mask, rad_buf stream, int64_t hc_streams) {
if (!b || !mask || !stream || !cv || !cv->dir || hc_streams <= 1) return RAD_OK;
if (layer <= 0 || layer >= cv->n_layers || layer >= g.n_layer) return RAD_OK;
const float scale = cv->scales ? cv->scales[(size_t) layer] : 0.0f;
if (scale == 0.0f) return RAD_OK;
n = g.n_embd;
hc = hc_streams;
on = mask;
h = stream;
dir = cv->dir + (size_t) layer * (size_t) n;
op = rw(b, RAD_OP(b, "hc_project",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_INT("hc", hc),
RAD_F64("scale", (double) scale), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{h, mask}, {h});
if (!op) {
fprintf(stderr, "radiance: %s: hc_project resolves to no kernel at n %lld, hc %lld -- "
"this rank cannot serve the control vector\n",
name, (long long) n, (long long) hc);
return RAD_E_INVAL;
}
return RAD_OK;
}
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
* call per piece, in the same place in the graph. */
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
if (!op) return;
RAD_ISSUE_N(c_, op, rows,
brow_slice(h, r0, rows, hc * n),
praw(dir, RAD_F32, n),
praw((const int32_t*) rad_buf_ptr(c_, on) + r0, RAD_I32, rows));
}
};
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
if (!op_write) return;
if (takes_gather(T)) {
+17 -7
View File
@@ -60,13 +60,16 @@ struct MlpFP8 {
/* The next block absorbs this block's closing all-reduce, so this one must not issue it.
* Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */
bool ar_out = false;
/* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch
* (GateQuantFP8::fuse_clamped). */
bool swiglu_quant = false;
/* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add
* (false for the first block of a chain). `add_out`: issue the trailing add here. See
* rad_fp8.h. */
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
@@ -76,7 +79,7 @@ struct MlpFP8 {
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
const Src& src, bool fold, bool add_out,
int ar_in, bool ar_out_) {
int ar_in, bool ar_out_, double swiglu_limit) {
g = geom; w = wire; layer = l;
ar_out = ar_out_;
@@ -93,14 +96,21 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
{ src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
/* The bf16 silu product is written only if the down projection reads the bf16 plane
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */
* (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales, and so does an
* int8 one fed its codes (ActFP8::q8_fed). */
const char* down_base = nm.f("blk.%d.ffn_down", l);
RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down }));
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x));
gq_ffn.fuse_clamped = swiglu_quant;
RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0,
down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, false,
swiglu_limit));
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit and 4-bit gate_up
* weights take the pair. */
if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4)
/* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit
* and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product.
* Declared over int8 codes, only a host kernel would take it, and that would pin the layer's
* weights to the host. */
if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx &&
!gate_up.paro5 && !gate_up.w4 && !gate_up.i8)
op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws,
{ w.h.q, w.h.s },
gq_ffn.want_x
+205 -47
View File
@@ -48,6 +48,7 @@
#define RAD_BLOCK_MOE_FP8_H
#include "rad_fp8.h"
#include "rad_block_glm_router.h"
#include "rad_device.h"
#include <cstdio>
@@ -72,8 +73,10 @@ static const int64_t kMoeRouterFusedRows = 64;
*
* The core's histogram (core/runtime/ctx.cpp) shows which experts were chosen and dbg_resid shows
* each arm's magnitude; neither shows the weights, so a top-k that sums to 0.4 instead of 1 would
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) {
* go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all.
* `f32`: the weights are f32 rather than bf16 (the sigmoid router). */
inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew,
bool f32 = false) {
static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING");
if (!dbg || !ids || !ew) return;
static const int want = (int)std::strtol(dbg, nullptr, 10);
@@ -85,8 +88,9 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
RadStream s = rad_stream(c_);
std::vector<int32_t> vi((size_t)top_k);
std::vector<uint16_t> vw((size_t)top_k);
std::vector<float> vf((size_t)top_k);
rad_memcpy_async(vi.data(), pi, top_k * 4, s);
rad_memcpy_async(vw.data(), pw, top_k * 2, s);
rad_memcpy_async(f32?(void*)vf.data():(void*)vw.data(), pw, top_k * (f32?4:2), s);
rad_stream_sync(s);
std::string line;
@@ -95,6 +99,7 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids,
const uint32_t u = (uint32_t)vw[(size_t)r] << 16;
float f;
std::memcpy(&f, &u, 4);
if (f32) f = vf[(size_t)r];
sum += f;
char b[48];
std::snprintf(b, sizeof b, "%s%d:%.4f", r ? " " : "", vi[(size_t)r], f);
@@ -167,6 +172,23 @@ struct MoeFP8 {
* units a routed GEMM's tail leaves idle. */
int64_t shared_lo = 0, shared_hi = 0;
int norm_topk = 1; /* renormalise the kept routing weights to sum to one */
/* GLM routing (GlmRouter): sigmoid scores with a correction bias, top-k, `route_scale` on
* the kept weights, which are then f32 in `ew`. */
int sigmoid_router = 0;
/* With `sigmoid_router`: the selection, the scatter and an ungated shared arm's gate fill in
* one launch (`router_sigmoid_topk_scatter`) wherever the pass fits the sort's one
* workgroup; the separate ops otherwise. Byte-identical either way. */
int router_fuse = 0;
/* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */
int expert_f32_scale = 0;
double route_scale = 1.0;
/* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */
double swiglu_limit = 0.0;
/* With `swiglu_limit`: the clamped product and its quantiser as one launch
* (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */
int swiglu_quant = 0;
/* A shared arm without its sigmoid gate: the gate plane is filled with 1. */
int shared_ungated = 0;
/* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for
* Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8`
* registry row). It is the stored encoding: probe() reads it from the first expert's
@@ -176,6 +198,8 @@ struct MoeFP8 {
* A packed 4-bit row is K/2 bytes, so a width shard must fall on a scale group; declare()
* checks this per rank. */
int expert_w4 = 0;
/* OCP E2M1 codes with E8M0 scales per 32 of K; kept canonical for host-tier reads. */
int expert_mx = 0;
/* Rotated: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and the
* activation meeting it (the encoding's `fwht128` transform, dtype `w4a8h`; only with
* `expert_w4`).
@@ -242,11 +266,14 @@ struct MoeFP8 {
/* the routing, one row per token */
rad_buf logits = 0; /* [max_tok, n_expert_all] bf16, the model's expert count */
rad_buf ids = 0; /* [max_tok, top_k] i32 */
rad_buf ew = 0; /* [max_tok, top_k] bf16 */
rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */
rad_buf eoff = 0; /* [n_expert + 1] i32 */
rad_buf ecnt = 0; /* [n_expert] i32 */
/* the expert planes, one row per (token, slot), a pass tall */
rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */
/* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot
* table (moe_scatter_inv, moe_gather_inv). Optional. */
rad_buf inv = 0; /* [rows * top_k] i32 */
rad_buf egu = 0; /* [rows * top_k, 2 * n_ff_exp] bf16 */
ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */
rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */
@@ -268,6 +295,7 @@ struct MoeFP8 {
Config cfg{};
const char* norm = nullptr;
const char* router = nullptr; /* mlp.gate.weight, [n_expert, n_embd] bf16 */
const char* router_bias = nullptr; /* GLM noaux_tc correction bias */
const char* experts = nullptr; /* prefix; ".<e>.{gate,up,down}_proj.weight" */
const char* shared = nullptr; /* prefix; ".{gate,up,down}_proj.weight" */
/* Stacked checkpoints (recent releases) store all experts in two tensors:
@@ -287,6 +315,7 @@ struct MoeFP8 {
int layer = 0;
rad_weight w_norm = 0, w_router = 0, w_sgate = 0;
GlmRouter glm_router{};
/* The input was normed and quantised by the caller; this block declares no norm. */
bool ext_in = false;
/* The weight runs. Only the first handle and the count reach an issue (RAD_WTAB); the rest are
@@ -297,6 +326,9 @@ struct MoeFP8 {
GateQuantFP8 gq_exp{}, gq_sh{};
LinearFP8 sh_gate_up{}, sh_down{};
rad_op op_router = 0, op_topk = 0, op_scatter = 0;
/* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and
* the gather reads it (Wire::inv). */
bool scatter_inv = false, gather_inv = false;
/* `router_topk_scatter`, if it resolves: topk and scatter in one launch. The pair is declared
* either way, since the fused form is bounded by the sort's single workgroup and a prefill
* chunk exceeds it. */
@@ -308,6 +340,11 @@ struct MoeFP8 {
rad_op op_router_fused = 0;
int64_t router_fused_rows = 0;
bool router_fused_gate = false;
/* `router_sigmoid_topk_scatter` (Config::router_fuse), up to `sigmoid_scatter_rows` tokens,
* writing the shared gate's fill too when `sigmoid_scatter_gate`. */
rad_op op_sigmoid_scatter = 0;
int64_t sigmoid_scatter_rows = 0;
bool sigmoid_scatter_gate = false;
/* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and
* the caller does not already write `w.hr`. */
rad_op op_hq = 0;
@@ -390,11 +427,11 @@ struct MoeFP8 {
static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg);
/* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the
* rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its
* five-bit form per 64; RAD_E_DTYPE otherwise. */
* five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */
static int format_of(const RadEncoding& e);
/* format_of's numbers as the grouped GEMMs' dtype strings. */
static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h" };
static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h",
"w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" };
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
@@ -424,6 +461,7 @@ struct MoeFP8 {
};
inline int MoeFP8::format_of(const RadEncoding& e) {
if (linear_is_mxfp4(e)) return 8;
if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3;
if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
@@ -443,7 +481,11 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
return 7;
return RAD_E_DTYPE;
}
if (!sc || sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (!sc) return RAD_E_DTYPE;
if (e.n_planes == 2 && e.plane[0].dtype == RAD_F8E4M3 && sc->dtype == RAD_F32 &&
!e.transform[0] && sc->block[0] == 128 && sc->block[1] == 128)
return 9;
if (sc->dtype != RAD_BF16) return RAD_E_DTYPE;
if (e.n_planes == 3) {
const RadEncPlane* t = rad_enc_plane(&e, "table");
if (t && t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 &&
@@ -530,7 +572,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
"(fp8_e4m3*bf16[128x128]), four-bit (i4*bf16[1x128], optionally "
"/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain "
"bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed "
"f32, or its 32-entry five-bit form at a 64. "
"f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 "
"(fp4_e2m1*e8m0[1x32]). "
"Convert it with a recipe that makes one of them.\n", guw, en);
return RAD_E_DTYPE;
}
@@ -542,6 +585,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config
cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0;
cfg->expert_w5 = f == 7 ? 1 : 0;
cfg->expert_bf16 = f == 3 ? 1 : 0;
cfg->expert_mx = f == 8 ? 1 : 0;
cfg->expert_f32_scale = f == 9 ? 1 : 0;
return RAD_OK;
}
@@ -560,6 +605,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
* all-reduce carries the others' share. */
const bool shared = c.n_ff_shared > 0 && src.shared;
if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL;
/* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by
* the fused router's gate write (see there). */
bool sgate_concurrent = false;
@@ -592,7 +638,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
prot.clear();
{
const int want = c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6
: c.expert_g64 ? 5 : c.expert_nl ? 4
: c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0;
auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) {
@@ -665,16 +711,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The router is replicated (see Config::n_expert_all): every rank computes the same routing
* from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks
* without a collective. */
* without a collective. The sigmoid router (GlmRouter) declares its own projection. */
if (!c.sigmoid_router) {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router));
w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16,
{c.n_expert_all, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
}
if (!ext_in)
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
fold ? w.x : 0, 0, ar_in));
if (c.sigmoid_router) {
if (!src.router_bias) return RAD_E_INVAL;
GlmRouter::Config rc;
rc.experts = c.n_expert_all;
rc.top_k = c.top_k;
rc.rows = c.rows;
rc.norm = c.norm_topk;
rc.route_scale = c.route_scale;
const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew };
const GlmRouter::Src rs{ src.router, src.router_bias };
RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs));
w_router = glm_router.projection;
op_router = glm_router.op_project;
op_topk = glm_router.op_select;
} else {
op_router = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
@@ -686,6 +749,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.logits}, {w.ids, w.ew});
}
/* Protected experts are sorted last (`protect`); layers without them declare no protect
* list, so it is the last parameter and cut off. */
const int n_prot = prot_list ? 1 : 0;
@@ -693,8 +757,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const RadParam ps[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert),
RAD_INT("top_k", c.top_k), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list) };
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
/* With `w.inv` the sort also writes the gather's slot table. It writes everything
* moe_scatter does, so a moe_gather_inv that does not resolve leaves moe_gather to serve. */
if (w.inv && rad_op_declared(b, "moe_scatter_inv") && rad_op_declared(b, "moe_gather_inv"))
op_scatter = rw(b, rad_decl_op(b, "moe_scatter_inv", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt, w.inv});
scatter_inv = op_scatter != 0;
if (!op_scatter)
op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS),
{w.ids}, {w.sorted, w.eoff, w.ecnt});
}
/* topk and scatter in one launch. At decode each is a single 256-thread workgroup ranking
@@ -705,9 +776,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* M*top_k <= 1024 and three above (for a stable sort without atomics), and only the first is
* fusible. That covers decode (eight sequences at depth 3 and top_k 10 is 320); prefill
* chunks exceed it. The pair is declared either way, so the graph and buffer plan do not
* depend on it. */
* depend on it. The sigmoid router selects in its own op and takes no fused pair. */
topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows
: kMoeSortRows / c.top_k;
if (c.sigmoid_router || scatter_inv) topk_scatter_rows = 0;
/* Asked for only where a loaded library declares it: a CPU-only engine would refuse the
* declare, and the two separate ops serve without it. */
if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) {
@@ -752,6 +824,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
* the parity classes. */
const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0;
ncls = c.ff_hi4[0] > 0 ? 4 : 2;
if (c.expert_mx && ncls == 4) {
fprintf(stderr, "radiance: MXFP4 experts use two parity tables; use equal TP width slices\n");
return RAD_E_UNSUPPORTED;
}
if (ncls == 4 && n_reg < 4) {
fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four "
"classes need at least one each\n", l, (long long)n_reg);
@@ -791,7 +867,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The codes view's dtype and planes; a codebook's table is selected with its codes so the
* relayout sees it. */
auto edt_of = [&](int f) {
return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4
: c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3;
};
const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) };
@@ -819,19 +895,23 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW;
const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL;
const int n_parts = ep ? 0 : 2;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit. `sdiv` is
* how many weight rows or columns one scale covers along the split dimension. */
const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK;
/* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32
* for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split
* dimension. */
const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK;
/* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the
* experts' encoding or the kernel is not a candidate. */
const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] };
/* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group
* forms E4M3 per (row, 64 of K) selected with the fixed second level. With two planes it is a
* forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile
* (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a
* view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's
* extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout
* hook. `sgk` is the K one declared scale column covers. */
const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32
: c.expert_mx ? (uint32_t)RAD_E8M0
: c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK;
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
/* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale
* planes the same in their own units. */
@@ -880,7 +960,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
true, false));
true, false, false, c.swiglu_limit));
op_dn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne),
@@ -914,8 +994,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
c.expert_w4 ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
{(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]),
(c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)},
RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0),
parts, n_parts);
if (!h) return RAD_E_INVAL;
@@ -941,7 +1021,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
(long long)(c.expert_base + e)),
escale, sdt,
{c.expert_w4 ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
{(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk},
RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1));
if (!h) return RAD_E_INVAL;
RAD_ARCH_TRY(span(h, q, sgk));
@@ -1012,8 +1092,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM,
* which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to
* the rotated op at no extra launch. */
gq_exp.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k,
false, rot));
false, rot, false, c.swiglu_limit));
{
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
rad_op h = ncls == 4
@@ -1116,7 +1197,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
Geom gx = g;
gx.w_bf16 = true;
RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true,
false));
false, false, c.swiglu_limit));
op_pdn = rw(b, rad_decl_op(b, "moe_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
RAD_INT("K", wp), RAD_INT("n_expert", np),
@@ -1209,18 +1290,20 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
/* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a
* separate gather would be two dispatches per layer and a 160 KiB round trip. */
gfold = shared;
{
rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate };
for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) {
rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate };
rad_buf gwr[1] = { w.h.x };
op_gather = RAD_OP(b, "moe_gather",
op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd),
RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype),
RAD_STR("act", gfold ? "sigmoid" : "none")),
RAD_STR("act", gfold && !c.shared_ungated ? "sigmoid" : "none")),
RAD_NOWEIGHTS);
if (!op_gather) return RAD_E_INVAL;
if (!op_gather) continue;
gather_inv = !form;
rad_op_reads (b, op_gather, grd, gfold ? 5 : 3);
rad_op_writes(b, op_gather, gwr, 1);
}
if (!op_gather) return RAD_E_INVAL;
/* ---- the shared expert. Ordinary dense linears over the same normed input. */
if (shared) {
@@ -1243,7 +1326,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8));
}
if (!w.sff.q || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)))
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
@@ -1258,8 +1341,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{ c.n_ff_shared, c.n_ff_shared },
c.shared_lo, c.shared_hi));
/* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */
gq_sh.fuse_clamped = c.swiglu_quant != 0;
RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows,
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8)));
sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false,
false, c.swiglu_limit));
RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base,
g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l),
{ nm.ckpt("%s.down_proj.weight", src.shared) },
@@ -1267,7 +1352,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
c.shared_lo, c.shared_hi));
/* The shared gate, replicated like the router so every rank computes the same gate. One
* output column: the skinny GEMM kernel clamps its N tile rather than masking, so N = 1 is
* legal. */
* legal. An ungated arm (shared_ungated) fills the gate with 1 instead. */
if (c.shared_ungated) {
op_sgate = rw(b, RAD_OP(b, "fill",
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", 1),
RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)),
RAD_NOWEIGHTS),
{}, {w.sgate});
} else {
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate));
w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
@@ -1276,6 +1368,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_sgate)),
{w.h.x}, {w.sgate});
}
}
/* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the
@@ -1290,7 +1383,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
*
* The parameter list, weights and write set are conditional, so each is an array cut to
* length. */
if (op_topk_scatter && rad_op_declared(b, "router_gemm_topk_scatter")) {
if (op_topk_scatter && !c.shared_ungated && rad_op_declared(b, "router_gemm_topk_scatter")) {
router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows
: kMoeRouterFusedRows;
const bool gate = op_sgate != 0;
@@ -1319,6 +1412,50 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
router_fused_gate = op_router_fused && gate;
}
/* GLM's selection and the sort as one op, plus the ungated shared arm's gate fill. Declared
* here for the reason the fused router above is: it writes `w.sgate` ahead of `op_sgate`'s
* declared index, which is safe only with `sgate` out of the sharing pool. Its other outputs
* and its input are also declared by the ops it replaces, so their planned lifetimes cover it.
* Undeclared or unresolved, the separate ops serve. */
if (c.sigmoid_router && c.router_fuse) {
if (!rad_op_declared(b, "router_sigmoid_topk_scatter")) {
static bool told = false;
if (!told) rad_note(b, "no loaded library declares router_sigmoid_topk_scatter; the "
"selection and the sort stay separate launches");
told = true;
} else {
sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows
? c.rows : kMoeSortRows / c.top_k;
const bool gate = op_sgate != 0 && c.shared_ungated;
if (gate && !sgate_concurrent) {
fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate "
"ahead of its declared writer, which needs `sgate` out of the "
"sharing pool, and it is not\n", l);
return RAD_E_STATE;
}
const RadParam sp[] = {
RAD_RANGE("M", 1, sigmoid_scatter_rows), RAD_INT("n_expert", c.n_expert_all),
RAD_INT("n_local", c.n_expert), RAD_INT("top_k", c.top_k),
RAD_INT("norm", c.norm_topk), RAD_F64("route_scale", c.route_scale),
RAD_STR("dtype", "f32"), RAD_INT("expert_base", c.expert_base),
RAD_STR("protect", prot_list),
};
const int n_sp = (int)(sizeof(sp) / sizeof(sp[0])) - (prot_list ? 0 : 1);
op_sigmoid_scatter = rad_decl_op(b, "router_sigmoid_topk_scatter", sp, n_sp,
&glm_router.correction, 1);
if (op_sigmoid_scatter) {
const rad_buf rd[1] = { w.logits };
rad_buf wr[7] = { w.ids, w.ew, w.sorted, w.eoff, w.ecnt };
int n_wr = 5;
if (gate) wr[n_wr++] = w.sgate;
if (scatter_inv) wr[n_wr++] = w.inv;
rad_op_reads (b, op_sigmoid_scatter, rd, 1);
rad_op_writes(b, op_sigmoid_scatter, wr, n_wr);
}
sigmoid_scatter_gate = op_sigmoid_scatter && gate;
}
}
if (g.world > 1)
op_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
@@ -1347,7 +1484,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
if (!c.sigmoid_router && !c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
@@ -1376,7 +1513,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
bool gate_done) const {
/* `gate_done`: the fused router already wrote this pass's gate. */
if (!gate_done)
if (!gate_done && c.shared_ungated)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1));
else if (!gate_done)
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
brow_slice(w.sgate, r0, rows, 1));
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
@@ -1415,7 +1554,18 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
/* The fused router when it resolved and the pass fits: router, topk + scatter and (with
* `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */
const bool rfused = op_router_fused && rows <= router_fused_rows;
if (rfused)
const bool sfused = op_sigmoid_scatter && rows <= sigmoid_scatter_rows;
if (sfused) {
glm_router.project(c_, r0, rows, r0);
RAD_ISSUE_N(c_, op_sigmoid_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
RAD_W(glm_router.correction), brow_slice(w.ids, r0, rows, k),
brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k),
brows(w.eoff, ne + 1), ecnt,
sigmoid_scatter_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
scatter_inv ? brows(w.inv, rows * k) : RAD_NONE);
} else if (c.sigmoid_router) {
glm_router.step(c_, r0, rows, r0);
} else if (rfused)
RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE,
brow_slice(w.logits, r0, rows, ne_all),
@@ -1426,17 +1576,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
brow_slice(w.logits, r0, rows, ne_all));
/* topk + scatter fused, or the pair. In the fused op `w.ids` is an output. */
if (rfused) {
if (rfused || sfused) {
/* the fused router wrote all five */
} else if (op_topk_scatter && rows <= topk_scatter_rows) {
RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
} else {
if (!c.sigmoid_router)
RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all),
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k));
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
if (scatter_inv)
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt,
brows(w.inv, rows * k));
else
RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k),
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
}
/* The rotated quantisation of the input, when the experts are rotated and the caller did not
@@ -1476,7 +1632,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
brows(w.egu, rows * k));
if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate);
if (shared) shared_up(c_, T, r0, rows,
(rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate));
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
if (c.expert_bf16)
@@ -1562,7 +1719,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o
* the block's delta into `h.x`. */
if (!gather_taken(g, T, gather_out_rows, gather_out_rows6))
RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k),
brows(w.sorted, rows * k),
brows(gather_inv ? w.inv : w.sorted, rows * k),
gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE,
gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE,
brow_slice(w.h.x, r0, rows, g.n_embd));
@@ -1640,9 +1797,10 @@ inline void MoeFP8::route_report(RadCtx* c_) const {
* It reports the last pass, which is the whole step by default (`c.rows` is the prefill
* chunk). With more passes it is a sample, adequate for a popularity estimate.
*
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16.
* Nothing in the core reads it (the heat engine uses `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew);
* `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16
* (f32 under the sigmoid router). Nothing in the core reads it (the heat engine uses
* `expert_count`). */
moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0);
RadRouting r{};
r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids);
r.expert_w = nullptr;
+174 -25
View File
@@ -68,6 +68,10 @@ struct ActFP8 {
* epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it
* declares the pair, before the wires are copied. */
bool q8_fed = false;
/* With q8_fed: the producer's int8 codes are rotated, had_quant_act_i8g's (a `_had_quant_i8g`
* producer), so only a weight stored rotated (LinearFP8 at i8a8h) reads them, and it declares
* no quantiser of its own. Set by the model with q8_fed. */
bool q8_rot = false;
/* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */
rad_buf cq() const { return q8_fed ? q8 : q; }
@@ -374,6 +378,8 @@ struct NormQuantFP8 {
* (the T * n_embd * 2-byte message then crosses --tp-wire-min-kb). The wire is a declare-time
* parameter, hence a separate op. */
rad_op op_arn6 = 0;
/* The ops write had_quant_act_i8g's rotated int8 codes into the int8 pair (ActFP8::q8_rot). */
bool hi8 = false;
Geom gm{};
/* The row width, for turning a row slice into element offsets. */
int64_t n = 0;
@@ -407,8 +413,12 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
"linears are bf16; its blocks take a prepared input instead\n");
return RAD_E_UNSUPPORTED;
}
if (!src || !a.x || !a.q || !a.s || !w || n <= 0) return RAD_E_INVAL;
op = RAD_OP(b, "rmsnorm_quant_fp8",
/* Rotated int8 codes (ActFP8::q8_rot) come from the `_had_quant_i8g` twins, into the int8
* pair; the model checked they are declared before feeding. Otherwise E4M3, as always. */
hi8 = a.q8_fed && a.q8_rot;
const rad_buf cq = hi8 ? a.q8 : a.q, cs = hi8 ? a.s8 : a.s;
if (!src || !a.x || !cq || !cs || !w || n <= 0) return RAD_E_INVAL;
op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
@@ -419,7 +429,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
* lifetime-extended. `residual` is INOUT, so it is in both sets; otherwise the planner could
* reorder a reader around it. */
rad_buf rd[2] = { src, res };
rad_buf wr[4] = { a.q, a.s, a.x, res };
rad_buf wr[4] = { cq, cs, a.x, res };
rad_op_reads (b, op, rd, res ? 2 : 1);
rad_op_writes(b, op, wr, res ? 4 : 3);
@@ -431,7 +441,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
* with `x` the stream and no residual. The kernel supports it (r4d_fused_quant_fp8.hip) and the
* schema marks `residual` optional. */
if (fuse_ar && g.world == 2) {
op_arn = RAD_OP(b, "ar_rmsnorm_quant_fp8",
op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
@@ -439,14 +449,14 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
RAD_WEIGHTS(w));
if (!op_arn) return RAD_E_INVAL;
rad_buf wr_ar[4] = { a.q, a.s, a.x, res ? res : src };
rad_buf wr_ar[4] = { cq, cs, a.x, res ? res : src };
rad_op_reads (b, op_arn, rd, res ? 2 : 1);
rad_op_writes(b, op_arn, wr_ar, 4);
/* Only where the compressed wire is reachable and servable: a lossy payload accepted, and
* the width tiled by the chunk (otherwise a fatal step-time shape refusal). */
if (fuse_ar != kArExact && !g.wire_exact && (n % kArWire6Chunk) == 0) {
op_arn6 = RAD_OP(b, "ar_rmsnorm_quant_fp8",
op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok),
RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_INT("group", RAD_FP8_BLOCK),
@@ -470,8 +480,8 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
if (rows <= 0) rows = T - r0;
RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n),
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
brow_slice(a.q, r0, rows, n),
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(hi8 ? a.q8 : a.q, r0, rows, n),
brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK),
brow_slice(a.x, r0, rows, n));
}
@@ -480,6 +490,15 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c
struct GateQuantFP8 {
ActFP8 a{};
rad_op op = 0;
/* The swiglu_clamped path (`limit` > 0): `op` writes the clamped bf16 product and `op_quant`
* quantises it into the codes; with `clamped_fused`, `op` is `swiglu_clamped_quant_fp8` doing
* both and `op_quant` is unset. */
rad_op op_quant = 0;
bool clipped = false;
/* Set before declare: serve the clamped path as one `swiglu_clamped_quant_fp8` where a loaded
* library declares it and it resolves (E4M3 codes only). Byte-identical to the pair. */
bool fuse_clamped = false;
bool clamped_fused = false;
/* Whether the bf16 product is written. A consumer of the bf16 value must request it
* (docs/OPS.md), but a block-fp8 down_proj reads only codes and scales; only one that reads
* the bf16 plane (LinearFP8::reads_x) needs it. Skipping it saves [T, n_ff] per layer (18.2 GB
@@ -500,7 +519,7 @@ struct GateQuantFP8 {
* and `gated_quant_fp8` cannot supply it alone (its code and scale outputs are mandatory). */
int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n,
const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true,
bool rot = false, bool silu_only = false);
bool rot = false, bool silu_only = false, double limit = 0);
void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
};
@@ -509,13 +528,59 @@ struct GateQuantFP8 {
* bf16 output is unrotated either way. */
inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act,
int64_t n, const char* act_name, int64_t max_rows,
bool bf16_out, bool rot, bool silu_only) {
bool bf16_out, bool rot, bool silu_only, double limit) {
a = act;
want_x = bf16_out;
op_quant = 0;
this->n = n;
/* bf16 linears read the product itself, and an int8 trunk's down projection quantises its own
* input (`silu_only`): `silu_mul` into the bf16 plane only, and no rotation. */
bf16 = g.w_bf16 || silu_only;
clipped = limit > 0;
clamped_fused = false;
if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL;
if (clipped) {
/* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. A `silu_only`
* linear quantises its output through its consumer, so it carries no clamp. */
if (!gate_up || !a.x || n <= 0 || rot || silu_only || (a.q8_fed && a.q8_rot) ||
std::strcmp(act_name, "silu"))
return RAD_E_INVAL;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() &&
rad_op_declared(b, "swiglu_clamped_quant_fp8")) {
op =
RAD_OP(b, "swiglu_clamped_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS);
if (op) {
const rad_buf wr[3] = { a.cq(), a.cs(), a.x };
rad_op_reads(b, op, &gate_up, 1);
rad_op_writes(b, op, wr, want_x ? 3 : 2);
clamped_fused = true;
return RAD_OK;
}
}
want_x = true;
op = rw(b,
RAD_OP(b, "swiglu_clamped",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ gate_up }, { a.x });
if (!bf16) {
if (!a.cq() || !a.cs()) return RAD_E_INVAL;
op_quant =
rw(b,
RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{ a.x }, { a.cq(), a.cs() });
if (!op_quant) return RAD_E_INVAL;
}
return op?RAD_OK:RAD_E_INVAL;
}
if (bf16) {
if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) {
fprintf(stderr, "radiance: a bf16 gate is silu over [gate|up] into a bf16 plane; "
@@ -533,9 +598,13 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL;
/* Rotated codes feed a four-bit expert, which reads E4M3 only. */
if (rot && a.q8_fed) return RAD_E_INVAL;
/* Rotated int8 codes (ActFP8::q8_rot) feed a down projection stored at i8a8h:
* gated_had_quant_i8g, which the model checked is declared before feeding. */
const bool hi8 = a.q8_fed && a.q8_rot;
const int64_t rows = max_rows > 0 ? max_rows : g.max_tok;
const char* gq = hi8 ? "gated_had_quant_i8g" : rot ? "gated_had_quant_fp8" : "gated_quant_fp8";
if (!rot || rad_op_declared(b, "gated_had_quant_fp8"))
op = RAD_OP(b, rot ? "gated_had_quant_fp8" : "gated_quant_fp8",
op = RAD_OP(b, gq,
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype),
RAD_STR("act", act_name)),
@@ -564,6 +633,22 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up,
inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0,
int64_t rows) const {
if (rows <= 0) rows = T - r0;
if (clamped_fused) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK),
want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE);
return;
}
if (clipped) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n),
brow_slice(a.x, r0, rows, n));
if (op_quant)
RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n),
brow_slice(a.cq(), r0, rows, n),
brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK));
return;
}
if (bf16 || op_q) {
RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n));
if (op_q)
@@ -616,6 +701,9 @@ struct LinearFP8 {
/* Plain bf16 weight read by `gemm_nt` over the bf16 activation (Geom::w_bf16): no scale plane,
* no quantiser. */
bool bf16 = false;
/* Block-fp8 weight whose scale plane is f32 rather than bf16 (GLM's checkpoints), read by
* `gemm_nt_q` at dtype fp8a8f32. Read from the weight's encoding. */
bool f32_scale = false;
/* Int8 weight read by `gemm_nt_q` at dtype i8a8: i8 codes with a bf16 scale per row per 128 of
* K (libquant `codes=i8 group=128 scale=bf16`), against an i8 activation with an f32 scale per
* (row, 128). A quarter of E4M3's error at the same bytes, and iu8 WMMA runs at the fp8 rate.
@@ -771,6 +859,17 @@ inline bool linear_is_w8(const RadEncoding& e) {
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
}
/* The same planes rotated by the unnormalised 128-wide Hadamard along K, the 1/128 in the scale
* (libquant's `transform=fwht128`), served at i8a8h behind had_quant_act_i8g. */
inline bool linear_is_w8h(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 ||
std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0)
return false;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
}
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32],
* no transform (libr4d's MXFP4 layout hook). */
enum { RAD_MX_GROUP = 32 };
@@ -832,7 +931,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char*
const bool known = weight_enc(b, wn, &enc);
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
enc.plane[0].dtype == RAD_BF16;
probed_i8 = known && linear_is_w8(enc);
probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc));
/* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or
* quantises it. */
const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc));
@@ -990,9 +1089,21 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
/* ---- int8 weight, `gemm_nt_q` at i8a8 over the input's `a.q8` / `a.s8`. The scale plane is
* one bf16 per row per 128 of K: row parts and row slices apply as is, column slices in groups
* of 128. The codes come from the producer (ActFP8::q8_fed) or from op_q over `a.x` (probe()
* set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). */
i8 = known && linear_is_w8(enc);
* set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`).
*
* A rotated weight (i8a8h) takes had_quant_act_i8g instead. It reads a producer's codes only
* when they are rotated too (ActFP8::q8_rot, a `_had_quant_i8g` producer); a plain int8 weight
* only when they are not. */
const bool rot8 = known && linear_is_w8h(enc);
i8 = known && (linear_is_w8(enc) || rot8);
if (i8) {
/* Upstream's rot guard: fed codes must match the weight's rotation form. */
if (a.q8_fed && rot8 != a.q8_rot) {
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
"producer wrote %s\n", wn, rot8 ? " rotated" : " plain",
rot8 ? "unrotated" : "rotated");
return RAD_E_DTYPE;
}
/* The codes come from the producer (`q8_fed`, which declares no `op_q` and so needs no bf16
* plane) or from this linear's own `op_q` over `a.x`. Either way the int8 pair must exist;
* the bf16 plane is required only when this linear quantises, exactly as the fp8 branch
@@ -1031,14 +1142,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
if (!a.q8_fed)
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ a.x }, { a.q8, a.s8 });
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8")),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", rot8 ? "i8a8h" : "i8a8")),
RAD_WEIGHTS(w, ws)),
{ a.q8, a.s8 }, { y });
return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL;
@@ -1260,12 +1372,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
if (known) {
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 ||
enc.plane[0].dtype != RAD_F8E4M3 || !sc ||
(sc->dtype != RAD_BF16 && sc->dtype != RAD_F32) ||
sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) {
char en[256];
rad_enc_format(&enc, en, sizeof en);
fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they "
"read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], "
"read bf16, fp8_e4m3*bf16[128x128] or *f32[128x128], i8*bf16[1x128], "
"fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the "
"ParoQuant forms. A recipe rule stores the weight in one of them "
"(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en);
@@ -1291,13 +1404,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks"));
const char* sn = nm.f("%s.scale", base);
const auto* fp8_scale = known ? rad_enc_plane(&enc, "scale") : nullptr;
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
* the checkpoint or made so by rad-convert's recipe. */
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
access, shard, grp, rp.w, rp.n);
ws_row_div = RAD_FP8_BLOCK;
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
access, shard, grp, rp.s, rp.n);
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
if (!w || !ws) return RAD_E_INVAL;
/* An uneven slice; the scale plane takes the same slice in blocks. */
if (span_hi > 0) {
@@ -1318,7 +1433,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", f32_scale?"fp8a8f32":"fp8a8")),
RAD_WEIGHTS(w, ws)),
{ a.q, a.s }, { y });
return RAD_OK;
@@ -1415,19 +1530,53 @@ struct DenseFP8 {
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
bool mapped = false;
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts = {});
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
std::initializer_list<int64_t> row_parts = {}, bool mapped = false);
/* Rows [lo, hi) of the stored block-fp8 weight `src_wn` (codes and scale plane; mapped by
* whoever declared it), read as an [hi - lo, K] weight named `<base>`: a row slice that need
* not be a rank's even share, and may be the same rows on every rank. Whole 128-row blocks,
* so each slice's codes and scales are the stored ones. fp8 only: an MXFP4 linear's GEMM
* splits K by its own rule. A slice issued with `gemm(..., split_n)` set to the stored width
* computes the stored linear's outputs to the bit. */
int declare_slice(RadBuilder* b, Names& nm, const char* base, const char* src_wn, int64_t lo,
int64_t hi, int64_t K, int access, RadWeightGroup grp) {
if (lo < 0 || hi <= lo || lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK)
return RAD_E_INVAL;
mx = false;
ref = 0;
const char* wn = nm.f("%s.weight", base);
const char* sn = nm.f("%s.scale", base);
const bool own = !std::strcmp(wn, src_wn); /* the stored weight's own name */
w = decl_view(b, wn, own ? nullptr : src_wn, "codes", RAD_F8E4M3, { hi - lo, K }, access,
RAD_SHARD_ROW, grp);
s = decl_view(b, sn, src_wn, "scale", RAD_BF16, { fp8_blocks(hi - lo), fp8_blocks(K) },
access, RAD_SHARD_ROW, grp);
if (!w || !s) return RAD_E_INVAL;
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);
}
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` 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). */
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
int64_t split_n = 0) const {
if (mx)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
RAD_WEIGHTS(w, s, ref)),
reads, writes);
if (split_n > 0)
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
RAD_INT("split_n", split_n)),
RAD_WEIGHTS(w, s)),
reads, writes);
return rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
@@ -1441,7 +1590,7 @@ struct DenseFP8 {
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
int access, int shard, RadWeightGroup grp,
std::initializer_list<const char*> src,
std::initializer_list<int64_t> row_parts) {
std::initializer_list<int64_t> row_parts, bool mapped) {
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
/* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
File diff suppressed because it is too large. Load diff
+145
View File
@@ -0,0 +1,145 @@
/* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step
* size a replicated or head-split piece of work splits over the ranks instead, how a step's rows
* fall into one run a rank, and the column split of a replicated F32 projection.
*
* The residual stream is replicated (spec.md §9). Three kinds of split share the ranks' work:
*
* heads the MLA and KDA heads, with them the rows of their projections, the KDA state and
* the convolution history; the experts' and the dense feed-forward's width
* (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce
* rows a prefill-sized step's rows, one run a rank, each rank computing its run with the
* unsplit kernels (`run_rows`, `run_of`); joined by an all_gather of whole runs
* columns a replicated F32 projection's output columns (SplitF32Proj); joined by a
* row-interleaved all_gather, bit for bit the replicated projection
*
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
* lie wholly past a small step (`run_of`). */
#ifndef RAD_GLM_TP_H
#define RAD_GLM_TP_H
#include "rad_arch.h"
#include <algorithm>
#include <numeric>
namespace rad {
namespace arch {
struct GlmTp {
/* The model's widths a rank's shard divides: 64 heads of 128 (KDA) and 256 (MLA), experts of
* 2048 and a dense feed-forward of 12288. */
static constexpr int64_t kHeads = 64, kKdaDim = 128, kMlaDim = 256, kExpertFF = 2048,
kDenseFF = 12288;
static bool world_ok(int world) { return world == 1 || world == 2 || world == 4 || world == 8; }
static int64_t heads(int world) { return kHeads / world; }
static int64_t kda_width(int world) { return heads(world) * kKdaDim; }
static int64_t mla_width(int world) { return heads(world) * kMlaDim; }
static int64_t expert_width(int world) { return kExpertFF / world; }
static int64_t dense_width(int world) { return kDenseFF / world; }
/* Rows from which a step splits by rows or columns over the ranks. Below it, as in decode, the
* collective's latency outweighs the saved arithmetic and every rank runs the replicated or
* head-split form. */
static constexpr int64_t kSplitRows = 256;
/* Rows x live blocks from which the indexer splits a smaller step as well: a decode step at
* long context, where scoring every query row against every block of its sequence outweighs
* the two gathers. On one R9700 48 rows over 8000 blocks (32k of context) score and select in
* about 250 us and a run of 8 in 50, against roughly 50 us for the two eight-rank gathers;
* over 4000 blocks the saving is about the gathers' cost, and six rows never pay. From 16
* rows, so that at least four ranks share the work and every run fits in the step. */
static constexpr int64_t kSplitWork = 1 << 18, kSplitWorkRows = 16;
static bool splits(int64_t rows, int world) { return world > 1 && rows >= kSplitRows; }
/* A rank's run of a step of `rows`, gathered as rows of `row_bytes`: ceil(rows / world) rounded
* up to whole 16-byte words of the gathered row. Every rank but possibly the last takes a whole
* run; the planes a split writes hold world runs, which can reach past the step. */
static int64_t run_rows(int64_t rows, int world, int64_t row_bytes) {
const int64_t word = 16 / std::gcd<int64_t>(16, row_bytes);
return word * ((rows + word * world - 1) / (word * world));
}
struct Run {
int64_t run = 0, first = 0, rows = 0;
};
/* Rank `rank`'s rows [first, first + rows) of a step of `rows`. A rank whose run lies wholly
* past a small step takes the step's first run instead, so every plane it computes from and
* gathers is written; what it computes there is dead rows past the step, and the gather lays
* them past T, where nothing reads them. */
static Run run_of(int64_t rows, int world, int rank, int64_t row_bytes) {
Run r;
r.run = run_rows(rows, world, row_bytes);
r.first = rank * r.run;
r.rows = std::min(r.run, rows - r.first);
if (r.rows <= 0) {
r.first = 0;
r.rows = r.run;
}
return r;
}
/* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact)
* and each head-split block's (the deployment's wire). */
static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) {
if (g.world == 1) return 0;
return rw(b,
RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", 4096, g.max_tok * 4096),
RAD_STR("dtype", "bf16"),
RAD_INT("exact", exact ? 1 : g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{ x }, { x });
}
};
/* The split's ops are declared whatever the step size, and each gather's message as a range of
* rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph
* with the same fixed parameters.
*
* A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on
* rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices
* out as the full [M, n]. The kernel computes every output column independently of n and the
* gather moves bytes, so each value is bit-identical to the replicated projection's. */
struct SplitF32Proj {
rad_buf part = 0;
rad_op op_part = 0, op_gather = 0;
int64_t cols = 0, k = 0, min_rows = 0, first_col = 0;
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n,
int64_t width, rad_weight weight, rad_buf input, rad_buf output) {
min_rows = GlmTp::kSplitRows;
if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) {
min_rows = 0;
return RAD_OK;
}
cols = n / g.world;
k = width;
first_col = g.rank * cols;
part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols });
op_part = rw(b,
RAD_OP(b, "gemm_nt_f32",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(weight)),
{ input }, { part });
op_gather = rw(
b,
RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols),
RAD_STR("dtype", "f32"), RAD_INT("row", cols)),
RAD_NOWEIGHTS),
{ part }, { output });
return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL;
}
bool takes(int64_t rows) const { return min_rows && rows >= min_rows; }
void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight,
RadOperand output) const {
RadOperand slice = RAD_W(weight);
slice.offset = first_col * k;
slice.rows = cols;
RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows));
RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output);
}
};
}
} // namespace rad::arch
#endif
+430
View File
@@ -0,0 +1,430 @@
/* rad_vae2d.h -- an image VAE (encoder or decoder) as a recorded list of ops over NHWC images.
*
* Image size varies per request, so a VAE's ops are declared once for the largest image and issued
* with each pass's extents (`Vae::issue`). Qwen-Image 2.1's residual Wan-2.2 VAE, Qwen-Image's
* and Krea 2's Wan-2.1 one and FLUX's GroupNorm one are each a few lines of `conv`, `norm`,
* `resblock` and `attention` calls in their plugin.
*/
#pragma once
#include <arch/rad_arch.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <utility>
#include <vector>
namespace rad {
namespace arch {
/* ================================================================== the VAE as a recorded graph
*
* Image size varies per request, so the VAE's ops are declared once for the largest image and
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
* and step() walk the same list.
*
* Every output is its own buffer, sized for its stage; the planner shares storage between those
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
* in declaration order. */
struct VImg {
rad_buf buf = 0;
int64_t ch = 0;
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
};
struct VOp {
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN, GNORM, LIN } kind = CONV;
rad_op op = 0;
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
rad_weight w = 0, b = 0;
int k = 1, up = 1, stride = 1;
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
};
/* What a checkpoint stores a VAE's convolutions as. */
enum VaeConvForm {
VAE_CONV_2D, /* [cout, cin, k, k] */
VAE_CONV_CAUSAL, /* a causal 3-D convolution [cout, cin, kt, k, k], run on one frame: its
* last temporal tap (RAD_MAP_TAP) */
};
struct Vae {
std::vector<VOp> ops;
Names* nm = nullptr;
RadBuilder* b = nullptr;
const char* scope = ""; /* "dec" or "enc" */
bool down = false; /* an encoder: a level halves the side */
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
int n_buf = 0;
int first_group = 0;
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
* tail. */
int band_from = -1;
int64_t halo = 0;
std::vector<rad_buf> whole;
VaeConvForm form = VAE_CONV_2D;
/* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */
rad_buf gn_stats = 0;
int64_t px_at(int lvl) const {
int64_t p = base_px;
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
return p;
}
VImg img(int64_t ch, int lvl) {
VImg v;
v.ch = ch;
v.lvl = lvl;
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
return v;
}
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape,
bool tap = false) {
if ((tap ? map_tap(b, name, src, 2, -1) : map_copy(b, name, src)) < 0) return 0;
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
grp_layer(first_group));
}
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
const char* ckpt) {
VOp o;
o.kind = VOp::CONV;
o.x = x;
o.up = up;
o.stride = stride;
int lvl = x.lvl;
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
o.y = img(cout, lvl);
o.k = k;
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k },
form == VAE_CONV_CAUSAL);
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = RAD_OP(b, "conv2d_nhwc",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", cout), RAD_INT("k", k),
RAD_INT("stride", stride), RAD_STR("pad", pad),
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
/* An input with no buffer is the picture the pass staged, read where it lies. */
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
else rw(b, o.op, {}, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
VOp o;
o.kind = VOp::NORM;
o.x = x;
o.y = img(x.ch, x.lvl);
const char* dn = nm->f("%s.gamma", ckpt);
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
o.w = gamma_rank == 4
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
o.op = rw(b, RAD_OP(b, "l2norm_chan",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("act", silu ? "silu" : "none"),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
VImg add(const VImg& x, const VImg& z) {
VOp o;
o.kind = VOp::ADD;
o.x = x;
o.z = z;
o.y = img(x.ch, x.lvl);
o.op = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, z.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* y += the resampling shortcut of x (in place on y). */
void shortcut(const VImg& x, const VImg& y, int ft) {
VOp o;
o.kind = down ? VOp::S2D : VOp::D2S;
o.x = x;
o.y = y;
o.up = ft;
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, y.buf }, { y.buf });
ops.push_back(o);
}
/* A residual block, in -> out channels. */
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* The mid-block's single-head attention over every pixel. */
VImg attention(const VImg& x, const char* ckpt) {
const int64_t C = x.ch;
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = qkv;
o.y = img(C, x.lvl);
o.qkv_ch = 3 * C;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ qkv.buf }, { o.y.buf });
ops.push_back(o);
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
return add(p, x);
}
/* PyTorch's GroupNorm over the whole picture, `silu` or not (FLUX's VAE). Not row-local, so a
* VAE that has one runs whole (no banded tail). */
VImg gnorm(const VImg& x, bool silu, const char* ckpt, int64_t groups, double eps) {
VOp o;
o.kind = VOp::GNORM;
o.x = x;
o.y = img(x.ch, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { x.ch });
if (!gn_stats)
gn_stats = decl_b(b, nm->f("%s.gn_stats", scope), RAD_F32, { 64 * (2 + 3 * 1024) });
o.k = (int)groups;
o.op = RAD_OP(b, "group_norm",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_INT("groups", groups), RAD_F64("eps", eps),
RAD_STR("act", silu ? "silu" : "none"), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
rw(b, o.op, { x.buf, gn_stats }, { o.y.buf, gn_stats });
ops.push_back(o);
return o.y;
}
/* A per-pixel linear with a bias (a 1x1 convolution kept as a Linear): `cout` from x's
* channels. */
VImg lin(const VImg& x, int64_t cout, const char* ckpt) {
VOp o;
o.kind = VOp::LIN;
o.x = x;
o.y = img(cout, x.lvl);
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = rw(b, RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("N", cout),
RAD_INT("K", x.ch), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* A GroupNorm residual block (FLUX's VAE, diffusers' ResnetBlock2D): norm1, silu, conv1,
* norm2, silu, conv2, plus the input or its 1x1 `conv_shortcut`. */
VImg resblock_gn(const VImg& x, int64_t out, const char* ckpt, int64_t groups, double eps) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = gnorm(x, true, nm->f("%s.norm1", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = gnorm(t, true, nm->f("%s.norm2", ckpt), groups, eps);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* diffusers' single-head VAE attention: GroupNorm, to_q / to_k / to_v linears with biases,
* attention over every pixel, to_out.0, plus the input. */
VImg attention_gn(const VImg& x, const char* ckpt, int64_t groups, double eps) {
const int64_t C = x.ch;
VImg t = gnorm(x, false, nm->f("%s.group_norm", ckpt), groups, eps);
VImg q = lin(t, C, nm->f("%s.to_q", ckpt));
VImg k = lin(t, C, nm->f("%s.to_k", ckpt));
VImg v = lin(t, C, nm->f("%s.to_v", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = q;
o.y = img(C, x.lvl);
o.z = k;
o.w = 0;
o.qkv_ch = 0;
o.k = 0;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ q.buf, k.buf, v.buf }, { o.y.buf });
attn_v.push_back({ ops.size(), v });
ops.push_back(o);
VImg p = lin(o.y, C, nm->f("%s.to_out.0", ckpt));
return add(p, x);
}
/* The value image of each separate-projection attention, by op index. */
std::vector<std::pair<size_t, VImg>> attn_v;
const VImg* value_of(size_t i) const {
for (const auto& e : attn_v) if (e.first == i) return &e.second;
return nullptr;
}
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
* for the decoder), in the op's schema order, and its ranged value. */
static int64_t side(int64_t s0, int lvl, bool dn) {
int64_t s = s0;
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
return s;
}
/* Declares `cu`, a buffer of the plugin's, as read by every attention: issue() hands it to
* them. */
int attn_reads(rad_buf cu) const {
for (const VOp& o : ops)
if (o.kind == VOp::ATTN) RAD_ARCH_TRY(rad_op_reads(b, o.op, &cu, 1));
return RAD_OK;
}
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
bool is_whole(rad_buf v) const {
for (rad_buf w : whole) if (w == v) return true;
return false;
}
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
* holds an op that is not row-local, or reads a whole buffer above level 0. */
int64_t band_halo() const {
if (band_from < 0 || ops.empty()) return -1;
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
auto get = [&](rad_buf v) -> int64_t {
for (const auto& e : need) if (e.first == v) return e.second;
return 0;
};
auto want = [&](rad_buf v, int64_t m) {
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
need.push_back({ v, m });
};
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
const VOp& o = ops[i];
const int64_t my = get(o.y.buf);
switch (o.kind) {
case VOp::CONV: {
if (o.stride != 1) return -1;
const int64_t m = my + o.k / 2;
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
break;
}
case VOp::NORM: want(o.x.buf, my); break;
case VOp::LIN: want(o.x.buf, my); break;
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
default: return -1;
}
}
int64_t h = 0;
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
const VOp& o = ops[i];
for (const VImg* v : { &o.x, &o.z })
if (v->buf && is_whole(v->buf)) {
if (v->lvl != 0) return -1;
h = std::max(h, get(v->buf));
}
}
return h;
}
};
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
const void* input, size_t from, size_t to, int64_t row0) const {
auto ptr = [&](const VImg& v) -> const void* {
if (!v.buf) return input;
const char* p = (const char*)rad_buf_ptr(c, v.buf);
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
};
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
*H = side(H0, v.lvl, down);
*W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
};
auto rows = [&](const VImg& v, int64_t cols) {
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
};
for (size_t i = from; i < to && i < ops.size(); ++i) {
const VOp& o = ops[i];
int64_t Hx, Wx, Hy, Wy;
switch (o.kind) {
case VOp::CONV: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
break;
}
case VOp::NORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
break;
}
case VOp::ADD: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
break;
}
case VOp::D2S:
case VOp::S2D: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
break;
}
case VOp::ATTN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
const int64_t C = o.y.ch, n = H * W;
if (const VImg* v = value_of(i)) {
/* Separate q, k and v images. */
RAD_ISSUE_N(c, o.op, n, rows(o.x, C), rows(o.z, C), rows(*v, C), cu,
brows(o.y.buf, n));
} else {
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
}
break;
}
case VOp::GNORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
RAD_P_T2(rad_buf_ptr(c, gn_stats), RAD_F32, 1, 64 * (2 + 3 * 1024)),
rows(o.y, o.y.ch));
break;
}
case VOp::LIN: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE,
rows(o.y, o.y.ch));
break;
}
}
}
}
} /* namespace arch */
} /* namespace rad */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3.cpp)
+1273
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see
# cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(flux3distilled LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(flux3distilled architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3distilled.cpp)
+13
View File
@@ -0,0 +1,13 @@
/* flux3distilled -- arch/flux3 under the architecture name of FLUX.3 [klein]'s step-distilled
* release.
*
* The released pipeline is a `Flux3DistilledModularPipeline` and its base a
* `Flux3ModularPipeline`, so rad-convert names them `flux3distilled` and `flux3`. Both hold the same
* networks; the transformer's `flow_map` flag is what tells them apart inside the plugin. A
* separate .so because a plugin answers to one architecture name (spec §2.4). Everything else is
* arch/flux3/flux3.cpp.
*/
#define FLUX3_NS flux3distilled
#define FLUX3_ID "flux3distilled"
#include "../flux3/flux3.cpp"
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/gemma3 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(gemma3 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(gemma3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma3.cpp)
File diff suppressed because it is too large. Load diff
+20 -183
View File
@@ -90,8 +90,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_gemma4_chat.h>
#include "gemma4_dflash.h"
#include <arch/rad_gemma4_dflash.h>
#include <cmath>
#include <cstdint>
@@ -223,16 +222,15 @@ struct Model {
rad_weight w_tok = 0, w_onorm = 0;
rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
enum { MAX_TAPS = 8 };
enum { MAX_TAPS = Dflash1::MAX_TAPS };
int n_taps = 0;
int tap_layer[MAX_TAPS] = {};
rad_buf b_dfsrc = 0;
Dflash1 df{};
Dflash1::Wire dfw{};
rad_kvgroup kv_draft = 0;
bool have_df = false;
const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */
const char* tok_src = nullptr; /* the checkpoint's table, which the 8-bit draft head copies */
std::vector<Layer> layers;
};
@@ -301,159 +299,19 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t
/* ============================================================== the drafter */
/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), past the trunk's layers, reading the
* taps the trunk copies into `dflash_src` and the trunk's tied table. */
static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
Model& m, int base_layer) {
Names& nm = m.nm;
Geom dg{};
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash"));
if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) {
fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads "
"the target's embedding and head, so it is not this target's drafter\n",
(long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd);
return RAD_E_UNSUPPORTED;
}
Dflash1::Config dc{};
dc.n_taps = m.n_taps;
dc.escale = m.escale;
/* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */
long long trained = rad_meta_geti(meta, "draft.block_size", 0);
if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
if (trained < 2) {
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n");
return RAD_E_FORMAT;
}
if ((long long)ctx->max_spec + 1 != trained) {
fprintf(stderr, "radiance: gemma4: the DFlash 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 "
"--num-speculative-tokens %lld (or `auto`).\n",
trained, trained - 1, ctx->max_spec, trained - 1);
return RAD_E_UNSUPPORTED;
}
dc.block = trained;
if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED;
{
std::vector<int> full;
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
if (lt) {
RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention",
&full));
if ((int64_t)full.size() != dg.n_layer) {
fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and "
"it has %lld\n", full.size(), (long long)dg.n_layer);
return RAD_E_INVAL;
}
} else {
full.assign((size_t)dg.n_layer, 1);
}
bool any_swa = false;
for (int64_t l = 0; l < dg.n_layer; ++l) {
dc.full[l] = full[(size_t)l];
any_swa = any_swa || !full[(size_t)l];
}
if (any_swa) {
dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size",
rad_meta_geti(meta, "draft.sliding_window", 0));
if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) {
fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no "
"window\n");
return RAD_E_INVAL;
}
}
}
/* One unbounded cache for all the drafter's layers, because its full layer reads every
* position. The sliding layers bound themselves with their attention op's `window`, so the
* declared drafter window is 0 and the core stages the whole context. A separate window group
* for the sliding layers would save memory. */
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft));
const int64_t qd = dg.n_head * dg.head_dim;
const int64_t kvd = dg.n_head_kv * dg.head_dim;
int64_t qr = dg.max_seqs * dc.block;
if (qr > dg.max_tok) qr = dg.max_tok;
const int64_t sr = dg.max_seqs * dc.steps();
const int64_t tw = dc.n_taps * dg.n_embd;
Dflash1::Wire& dw = m.dfw;
dw.src = m.b_dfsrc;
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw});
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)});
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd});
dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd});
dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd});
dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd});
dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd});
dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd});
dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd});
dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd});
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab});
if (Dflash1::head_sharded(dg)) {
const int64_t R = Dflash1::kTopR;
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R});
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R});
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2});
} else {
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1});
}
if (!Dflash1::head_sharded(dg) && dg.world > 1) {
fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole "
"16-row blocks over %d ranks, which the drafter's sharded head needs\n",
(long long)dg.n_vocab_all, dg.world);
return RAD_E_UNSUPPORTED;
}
/* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch
* `steps`, read by the engine through the drafter declaration below. */
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1});
RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw,
m.tok_src));
Dflash1::Trunk t{};
t.n_taps = m.n_taps;
t.escale = m.escale;
t.src = m.b_dfsrc;
t.w_tok = m.w_tok;
t.tok_src = m.tok_src;
t.base_layer = base_layer;
RAD_ARCH_TRY(Dflash1::declare_drafter(b, meta, ctx, m.nm, m.g, t, &m.df, &m.kv_draft));
m.have_df = true;
RadDrafterDecl drf{};
drf.name = "dflash";
drf.kind = RAD_DRAFT_BLOCK;
drf.depth = ctx->max_spec;
drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.window = 0; /* the full layer reads everything; see the group */
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id",
rad_meta_geti(meta, "draft.mask_token_id", -1));
if (drf.mask_token < 0) {
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n");
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
int nfull = 0;
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
"trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is "
"%s, argmax %s",
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull,
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps,
(long long)dc.block, (long long)dc.steps(),
m.df.fp8_head
? "the container's block-fp8 copy of the target's table (dflash.draft_head)"
: "the target's tied bf16 table",
Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary");
return RAD_OK;
}
@@ -662,7 +520,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the embedding scale and the rotary scaling the converter may have written. The scale
* is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066
* multiplies as 53.0. */
m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
m.escale = embed_scale(E);
RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd));
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) {
fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's "
@@ -794,24 +652,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- the drafter's taps, declared when the container carries a DFlash drafter and this
* serve speculates. DFlash2 is refused by name: its convolutions and selector are another
* block. */
if (ctx->max_spec > 0) {
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash2")) {
fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin "
"serves the DFlash (v1) block z-lab publishes for Gemma 4\n");
return RAD_E_UNSUPPORTED;
}
if (da && std::strstr(da, "DFlash")) {
const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS);
if (m.n_taps <= 0) {
fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model "
"has; it is paired with a different target\n");
return RAD_E_UNSUPPORTED;
}
m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E});
}
{
const int n = Dflash1::taps(meta, ctx, m.n_layer, m.tap_layer, Model::MAX_TAPS);
if (n < 0) return n;
m.n_taps = n;
if (n > 0) m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)n * E});
}
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
@@ -1869,15 +1714,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
out->draft_depth = 0;
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) {
long long bs = rad_meta_geti(meta, "draft.block_size", 0);
if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
if (bs > 1) {
out->draft_depth = (int)(bs - 1);
out->draft_depth_fixed = 1;
}
}
(void)dflash_probe(meta, out);
return RAD_OK;
}
-682
View File
@@ -1,682 +0,0 @@
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
*
* ============================== WHAT IT IS ==============================
*
* rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
* attention and the feed-forward, and the candidate selector). The original DFlash is a small
* Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
* forward and takes every position's argmax from the target's lm_head.
*
* context pass, one row a committed token:
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
*
* query pass, `block` rows a sequence:
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
* for each layer:
* h = input_layernorm(x)
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
* x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window,
* the full layer non-causal over everything
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
* x = norm(x)
* over the mask rows: logits = lm_head(x) [the target's]; draft = argmax
*
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
*
* From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
* verified against the trunk.
*
* The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
* bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
* applies it. `embed_lookup`'s `mult` carries it.
*
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
* layers and `False` on the full one, so this block declares two attention ops and issues the one
* each layer's type names.
*
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
* cap * tanh(x / cap) is strictly increasing.
*
* ============================== THE HEAD ==============================
*
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
* ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
* and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
* slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
*
* The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
* 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
* table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
* weights, as in rad_block_dflash2.h), made by the recipe line
*
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
*
* the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
* coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
* text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
* table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
* DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
*
* ============================== THE LINEARS ARE FP8 ==============================
*
* As in DFlash2, since the drafter is read whole on every decode step: the container must be
* converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
* one by name rather than letting the loader fail on a view.
*/
#ifndef GEMMA4_DFLASH_H
#define GEMMA4_DFLASH_H
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <cstdio>
#include <cstring>
namespace gemma4 {
using namespace rad::arch;
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
inline bool block_fp8_128(const RadEncoding& e) {
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
}
struct Dflash1 {
enum { MAX_LAYERS = 8 };
struct Config {
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
int64_t window = 0; /* the sliding layers' window; 0 for none */
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
int64_t steps() const { return block - 1; }
};
struct Wire {
/* the context pass */
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
/* the query pass */
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
/* the head, one row per draft position */
rad_buf sel_h = 0; /* [srows, n_embd] */
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */
};
Geom g{}; /* the drafter's geometry */
Config cfg{};
Wire w{};
int first_layer = 0;
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
rad_kvgroup kv = 0;
bool sharded = false;
DenseFP8 w_fc{};
rad_weight w_hnorm = 0, w_norm = 0;
rad_weight w_tok = 0; /* the target's table: embedding and head */
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
bool fp8_head = false;
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
DenseFP8 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] = {};
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
/* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
* (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
* the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
* is issued instead. */
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
/* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
* moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
* refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
* reduces the world * 2 of them to the global top-1. */
static constexpr int64_t kTopR = 2;
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
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 Wire& wire,
const char* tok_src);
void context(RadCtx* c, const RadBatch* batch) const;
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; }
/* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
* whatever the container holds, and the loader's error for a bf16 weight read through an fp8
* view would name the view, not the missing recipe. */
static int need_quantised(RadBuilder* b, const char* wn) {
RadEncoding e{};
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
const uint32_t dt = e.plane[0].dtype;
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
"ffn_down.\n", wn, rad_dtype_name(dt));
return RAD_E_DTYPE;
}
};
/* ------------------------------------------------------------------------------ declare */
inline int Dflash1::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 Wire& wire, const char* tok_src) {
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most "
"%d\n", (long long)g.n_layer, MAX_LAYERS);
return RAD_E_UNSUPPORTED;
}
if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL;
const int64_t qd = q_dim(), kvd = kv_dim();
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();
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
sharded = head_sharded(g);
/* ---------------------------------------------------------------- model-scope weights */
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
{ nm.ckpt("%s.fc.weight", ck) }));
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight")));
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)));
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());
/* ---------------------------------------------------------------- per-layer weights */
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const RadWeightGroup gl = grp_layer(first_layer + i);
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
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, gl);
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
/* The declared names match rad_block_dflash2.h's, so one recipe quantises both
* drafters. */
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
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, gl,
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff,
g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
{ g.n_ff, g.n_ff }));
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
"ffn_down" })
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
}
/* ---------------------------------------------------------------- attention: two kinds
* Declared before either kv_store, which reads `block_size` back from the resolved kernel.
* Both read the one KV group, so whichever resolves first answers for it. */
auto attn = [&](int causal, int64_t window) {
return 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", causal),
RAD_INT("window", 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});
};
bool any_full = false, any_swa = false;
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
if (any_swa) op_attn_swa = attn(1, cfg.window);
if (any_full) op_attn_full = attn(0, 0);
/* ---------------------------------------------------------------- the context pass */
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.src}, {w.srcq, w.srcs});
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_hnorm)),
{w.c}, {w.c});
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.c}, {w.cq, w.cs});
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
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", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.ck}, {w.ck});
}
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.ck}, {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),
{w.ck, w.cv}, {});
/* ---------------------------------------------------------------- the query pass */
op_embed = rw(b, RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
RAD_WEIGHTS(w_tok)),
{}, {w.x});
if (g.world > 1)
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS),
{w.x}, {w.x});
op_qh = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.hq, w.hs});
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.attn}, {w.atq, w.ats});
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.ffn}, {w.ffq, w.ffs});
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
* fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
* the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
RAD_WEIGHTS(gain));
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
};
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", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_anorm[i])),
{w.x}, {w.h});
op_anq[i] = norm_quant(w_anorm[i], l > 0);
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v});
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", g.dtype)),
RAD_WEIGHTS(w_qn[i])),
{w.q}, {w.q});
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", g.dtype)),
RAD_WEIGHTS(w_kn[i])),
{w.k}, {w.k});
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_fnorm[i])),
{w.x}, {w.h});
op_fnq[i] = norm_quant(w_fnorm[i], true);
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
/* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
* rule, band included). */
{
const int64_t hi = qrows < 64 ? qrows : 64;
if (hi > 0 && !w_gu[i].mx) {
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
RAD_INT("K", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
{w.hq, w.hs}, {w.ffq, w.ffs});
if (op_gug[i]) gated_rows = hi;
}
}
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
}
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.k}, {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),
{w.k, w.v}, {});
op_act = rw(b, RAD_OP(b, "silu_mul",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.gate_up}, {w.ffn});
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, qrows * g.n_embd),
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
RAD_INT("min_bytes", g.wire_min_bytes)),
RAD_NOWEIGHTS),
{w.h}, {w.h});
op_add = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h}, {w.x});
op_final = rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_norm)),
{w.x}, {w.h});
/* ---------------------------------------------------------------- the head
* The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
* projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
* each rank reports its best kTopR as global ids with logits; these are all-gathered and
* reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
* global winner is its own shard's first. */
op_gather = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.h}, {w.sel_h});
/* The fp8 copy, where the container holds one (see the file header). The name map comes first
* since it is how the encoding is looked up; rad-convert writes only declared weights. The
* copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
* `vocab_off` holds. */
const char* dhn = nm.f("dflash.draft_head.weight");
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
RadEncoding he{};
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
if (fp8_head) {
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
"is not whole %d-row scale blocks\n",
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
RAD_ACCESS_PER_TOKEN, shard, grp_model());
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
shard, grp_model());
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.sel_h}, {w.selq, w.sels});
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
} else {
op_head = rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_tok)),
{w.sel_h}, {w.dlog});
}
if (sharded) {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.cand, w.unary, w.dpair});
/* Row-interleaved, so one draft position's pairs from every rank land side by side. */
op_dgather = rw(b, RAD_OP(b, "all_gather",
RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
RAD_INT("row", kTopR * 2)),
RAD_NOWEIGHTS),
{w.dpair}, {w.dgath});
op_pick = rw(b, RAD_OP(b, "pair_argmax",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
RAD_STR("dtype", "f32")),
RAD_NOWEIGHTS),
{w.dgath}, {w.tokens});
if (!op_pick) {
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
"device, and no loaded kernel library serves it there\n");
return RAD_E_UNSUPPORTED;
}
} else {
op_topk = rw(b, RAD_OP(b, "row_topk",
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.dlog}, {w.tokens, w.unary});
}
return RAD_OK;
}
/* ------------------------------------------------------------------------------ the context pass */
inline void Dflash1::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;
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
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());
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, 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.cq, T), brows(w.cs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
brows(w.ck, T));
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T),
kv_cache(kv, first_layer + i));
}
}
/* ------------------------------------------------------------------------------ the query pass */
inline void Dflash1::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;
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
if (op_embed_ar)
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
for (int64_t l = 0; l < g.n_layer; ++l) {
const int i = (int)l;
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
/* The attention input, with the last layer's residual add where one launch takes both. */
if (op_anq[i]) {
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
brows(w.hs, T), RAD_NONE);
} else {
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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
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));
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());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
if (op_fnq[i]) {
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, 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_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
}
if (op_gug[i] && T <= gated_rows) {
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
RAD_NONE);
} else {
RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T),
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
w_gu[i].bref());
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
}
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
/* the residual add, unless the next layer's input norm takes it */
if (l + 1 == g.n_layer || !op_anq[i + 1])
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
}
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
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 (fp8_head) {
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
} else {
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
}
if (sharded) {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
brows(w.dpair, S));
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
} else {
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
RAD_NONE);
}
}
} /* namespace gemma4 */
#endif /* GEMMA4_DFLASH_H */
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(glm5next LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(glm5next architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/glm5next.cpp)
+557
View File
@@ -0,0 +1,557 @@
/* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC
* residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer,
* 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32
* scales, each weight served as the container stores it; its MTP layer is a serial drafter, and
* its vision tower is declared when the container carries it and the deployment asks for an
* encoder. docs/ARCHITECTURES.md describes the model and its traps.
*
* The blocks live in arch/common (installed as <arch/...>), one a file:
*
* rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write
* rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence
* rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core
* rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection
* rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8)
* rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45
* rad_block_glm_vision.h GlmVision the tower, MediaRows its rows over the embeddings
* rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds
*
* This file declares the buffers the blocks share, places the blocks and issues the step's
* order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue
* order is the recorded pass, so both are kept as they read here. This plugin uses only the
* public ABI and the installed common headers. */
#include <arch/rad_block_glm_mhc.h>
#include <arch/rad_block_glm_kda.h>
#include <arch/rad_block_glm_mla.h>
#include <arch/rad_block_glm_indexer.h>
#include <arch/rad_block_glm_mtp.h>
#include <arch/rad_block_glm_vision.h>
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include <memory>
namespace glm5next {
using namespace rad::arch;
struct Layer {
bool full = false, draft = false;
ManifoldConn attn_hc{}, ffn_hc{};
NormQuantFP8 norm{};
GlmKda kda{};
GlmMla mla{};
GlmIndexer index{};
MlpFP8 dense{};
MoeFP8 moe{};
};
struct Model {
Names nm{};
Geom g{};
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. */
rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0,
logits = 0;
ActFP8 act{};
/* The blocks' wires: one set of activations, shared by every layer of a kind. */
GlmKda::Wire kw{};
GlmMla::Wire aw{};
GlmIndexer::Wire iw{};
MlpFP8::Wire dw{};
MoeFP8::Wire mw{};
rad_weight token = 0, head = 0, final_gain = 0;
rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0;
/* The draft head and its layer, declared only when the deployment speculates. */
bool have_mtp = false;
GlmMtp mtp{};
Layer draft{};
/* Media: the tower, and its rows over the trunk's embedding (the draft head scatters its own). */
bool media = false;
GlmVision vit{};
MediaRows mrows{};
};
static std::unique_ptr<Model> models[MAX_RANKS];
static thread_local std::unique_ptr<Model> probe_model;
static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) {
char nested[160];
std::snprintf(nested, sizeof nested, "text_config.%s", key);
return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback));
}
static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_STR("from", "bf16"), RAD_STR("to", "bf16")),
RAD_NOWEIGHTS),
{ x }, { y });
}
static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) {
return rw(b,
RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)),
{ x }, { y });
}
/* ------------------------------------------------------------------ the shared activations */
static int stream_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 });
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096));
m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST);
m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 });
m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab });
return rad_declare_logits(b, m.logits);
}
static int kda_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, W = GlmTp::kda_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& kw = m.kw;
kw.input = m.act.x;
kw.out = m.y;
kw.forget_low = bf("forget_low", 128);
kw.gate_low = bf("gate_low", 128);
kw.core.qkv = bf("qkv", 3 * W);
kw.core.conv = bf("convolved", 3 * W);
kw.core.a = bf("forget", W);
kw.core.beta = bf("beta", GlmTp::heads(g.world));
kw.core.gate = bf("gate", W);
kw.core.out = bf("recurrent_out", W);
return RAD_OK;
}
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under
* TP the selection planes hold every rank's run of rows, which can reach past the step
* (DsaCache::part_rows). */
static int mla_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, H = GlmTp::heads(g.world), Q = GlmTp::mla_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& aw = m.aw;
aw.input = m.act;
aw.q_raw = bf("q_raw", 1536);
aw.kv_raw = bf("kv_raw", 512);
aw.q_low.x = bf("q_low", 1536);
RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536));
aw.latent = bf("latent", 512);
aw.out = m.y;
aw.core.q = bf("query", Q);
aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 });
aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 });
aw.attn.x = bf("expanded", Q);
RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q));
aw.core.out = aw.attn.x;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
return RAD_OK;
}
static int indexer_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok;
const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0;
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1;
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& iw = m.iw;
iw.input = m.act.x;
iw.q_low = m.aw.q_low.x;
iw.q_wide = bf("index_query", 4096);
iw.kg_raw = bf("index_key_gate", 256);
auto& c = iw.cache;
c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 });
c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { TQ * 32, 128 });
c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { TQ * 32, 1 });
c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { TQ, 32 });
c.kg = bf("index_normalized_key_gate", 256);
c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 });
c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work });
c.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work });
c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs });
c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 });
c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 });
/* A split step scores one run of rows a rank and an unsplit one is under GlmTp::kSplitRows:
* 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.selected = m.aw.core.selected;
c.length = m.aw.core.length;
c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T });
if (g.world > 1) {
c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 });
c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 });
c.len_part = decl_b(b, nm.f("length_part"), RAD_I32, { part });
}
return RAD_OK;
}
static int ffn_buffers(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
const int64_t T = g.max_tok, F = GlmTp::expert_width(g.world);
auto bf = [&](const char* n, int64_t width) {
return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width });
};
auto& dw = m.dw;
dw.x = m.x;
dw.h = m.act;
dw.gate_up = bf("dense_gate_up", 2 * g.n_ff);
dw.ffn.x = bf("dense_ff", g.n_ff);
RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff));
auto& mw = m.mw;
mw.x = m.x;
mw.h = m.act;
mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 });
mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 });
mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 });
mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 });
mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 });
mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 });
mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 });
mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F });
mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F });
RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8));
mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 });
mw.sgu = bf("shared_gate_up", 2 * F);
mw.sff.x = bf("shared_ff", F);
RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F));
mw.sout = bf("shared_out", 4096);
mw.sgate = bf("shared_one", 1);
return RAD_OK;
}
static int kv_groups(RadBuilder* b, Model& m) {
auto& g = m.g;
auto& nm = m.nm;
RadKVGroupDecl d{};
d.kind = RAD_KV_FULL;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 256;
m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.state_dim[0] = 4 + g.max_spec;
d.state_dim[1] = 256;
m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d);
d = {};
d.kind = RAD_KV_LINEAR;
d.dtype = RAD_F32;
d.n_head_kv = GlmTp::heads(g.world);
d.state_dim[0] = d.state_dim[1] = 128;
m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d);
d = {};
d.kind = RAD_KV_CONV;
d.dtype = RAD_BF16;
d.n_head_kv = 1;
d.head_dim = 3 * GlmTp::kda_width(g.world);
d.conv_width = 4;
m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d);
// The index group is declared by the first indexer, right before its cache consumer.
return m.latent && m.tail && m.state && m.conv ? RAD_OK : RAD_E_INVAL;
}
/* ------------------------------------------------------------------ one layer */
static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) {
const auto& g = m.g;
lay.draft = draft;
lay.full = draft || l % 4 == 3;
const char* pre = nm.ckpt("model.language_model.layers.%d", l);
const char* ap = nm.ckpt("%s.self_attn", pre);
rad_buf input = draft ? m.mtp.x : m.x;
ManifoldConn::Config hc;
hc.eps = g.eps;
if (!draft) {
ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb };
ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre),
nm.ckpt("%s.hc_attn_base", pre) };
RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true));
}
const char* nn = nm.f("blk.%d.attn_norm.weight", l);
RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre)));
const auto gain =
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
if (lay.full) {
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true));
DsaCache::Config c;
c.blocks = (g.max_ctx + 3) / 4 + 1;
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
c.ring = 4 + g.max_spec;
RAD_ARCH_TRY(lay.index.declare(b, nm, g, l, m.iw, nm.ckpt("%s.indexer", ap), c, m.latent,
m.tail, &m.index));
RAD_ARCH_TRY(lay.mla.declare_finish(b, nm, ap));
} else {
KdaState::Src s{ nm.ckpt("%s.q_conv1d.weight", ap), nm.ckpt("%s.k_conv1d.weight", ap),
nm.ckpt("%s.v_conv1d.weight", ap), nm.ckpt("%s.A_log", ap),
nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) };
RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv));
}
// The ffn connection is declared after the attention's post: declaration order is liveness.
if (!draft) {
RAD_ARCH_TRY(lay.attn_hc.declare_post(b));
ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb };
ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre),
nm.ckpt("%s.hc_ffn_base", pre) };
RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true));
} else {
RAD_ARCH_TRY(m.mtp.declare_join(b, m.y));
}
if (l < 3) {
auto w = m.dw;
w.x = input;
MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre),
nm.ckpt("%s.mlp.gate_proj.weight", pre),
nm.ckpt("%s.mlp.up_proj.weight", pre),
nm.ckpt("%s.mlp.down_proj.weight", pre) };
lay.dense.swiglu_quant = true;
RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10));
} else {
auto w = m.mw;
w.x = input;
MoeFP8::Src s;
s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre);
s.router = nm.ckpt("%s.mlp.gate.weight", pre);
s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre);
s.experts = nm.ckpt("%s.mlp.experts", pre);
s.shared = nm.ckpt("%s.mlp.shared_experts", pre);
s.cfg.n_expert = s.cfg.n_expert_all = 288;
s.cfg.top_k = 8;
s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world);
s.cfg.rows = g.max_tok;
s.cfg.sigmoid_router = 1;
s.cfg.route_scale = 2.5;
s.cfg.swiglu_limit = 10;
s.cfg.shared_ungated = 1;
s.cfg.router_fuse = 1;
s.cfg.swiglu_quant = 1;
for (int q = 0; q < 2; ++q) {
s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world);
s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world);
}
RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg));
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft));
}
if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b));
return RAD_OK;
}
/* ------------------------------------------------------------------ declare */
static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) {
g.n_layer = 45;
g.n_embd = 4096;
g.head_dim = GlmTp::kMlaDim;
g.n_head_all = g.n_head_kv_all = GlmTp::kHeads;
g.n_head = g.n_head_kv = GlmTp::heads(world);
g.n_ff_all = GlmTp::kDenseFF;
g.n_ff = GlmTp::dense_width(world);
g.n_vocab_all = 154880;
g.n_vocab = shard_extent(154880, world, ctx->rank);
g.vocab_off = shard_begin(154880, world, ctx->rank);
g.rank = ctx->rank;
g.world = world;
g.attn_world = world;
g.attn_rank = ctx->rank;
g.max_tok = ctx->max_tok;
g.max_ctx = ctx->max_ctx;
g.max_seqs = ctx->max_seqs;
g.max_spec = ctx->max_spec;
g.max_logit_rows = std::min<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;
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;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
return RAD_E_INVAL;
const int world = ctx->world_size ? ctx->world_size : 1;
if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 ||
meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 ||
cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 ||
cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 ||
(ctx->kv_dtype && ctx->kv_dtype != RAD_BF16))
return RAD_E_UNSUPPORTED;
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
slot = std::make_unique<Model>();
auto& m = *slot;
auto& g = m.g;
m.nm = Names(ctx->scope);
auto& nm = m.nm;
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
RAD_ARCH_TRY(stream_buffers(b, m));
RAD_ARCH_TRY(kda_buffers(b, m));
RAD_ARCH_TRY(mla_buffers(b, m));
RAD_ARCH_TRY(indexer_buffers(b, m));
RAD_ARCH_TRY(ffn_buffers(b, m));
RAD_ARCH_TRY(kv_groups(b, m));
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"),
nm.ckpt("model.language_model.embed_tokens.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight")));
RAD_ARCH_TRY(
map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight")));
m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB,
RAD_SHARD_ROW, grp_model());
m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN,
RAD_SHARD_NONE, grp_model());
m.embed = rw(b,
RAD_OP(b, "embed_lookup",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096),
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)),
RAD_WEIGHTS(m.token)),
{}, { m.x });
// The encoder's rows overwrite the lookup before its reduction (MediaRows).
m.media = GlmVision::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, 4096, m.x));
m.embed_ar = GlmTp::reduce(b, g, m.x, true);
m.expand = copy(b, g, m.x, m.h0);
m.layers.resize(45);
for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false));
// Every rank computes the whole normed latent and pools into the whole index cache
// (rad_block_glm_mla.h, rad_block_glm_indexer.h), so the host tier keeps each once a slot.
RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent));
if (m.index) RAD_ARCH_TRY(rad_kv_group_replicated(b, m.index));
m.contract = rw(b,
RAD_OP(b, "mhc_contract",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096),
RAD_INT("hc", 4), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.h0 }, { m.x });
m.norm = norm(b, g, m.final_gain, m.x, m.final_hidden);
m.gather = rw(b,
RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ m.final_hidden }, { m.logit_input });
m.head_op =
rw(b,
RAD_OP(b, "logits_gemm",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab),
RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)),
{ m.logit_input }, { m.logits });
if (g.max_spec > 0) {
GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head };
RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw, m.media));
RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true));
RAD_ARCH_TRY(m.mtp.declare_head(b));
m.have_mtp = true;
}
// The tower, last: an encoder pass issues nothing else, so its activations share the arena
// with every buffer above. Its weight groups follow the 45 layers and the MTP layer's.
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, 4096, 46));
rad_note(b,
"GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP "
"%s, vision %s",
world, m.have_mtp ? "enabled" : "disabled", m.media ? "enabled" : "disabled");
return RAD_OK;
}
/* ------------------------------------------------------------------ step */
static void attention(RadCtx* c, Layer& l, const RadBatch* batch) {
l.norm.step(c, batch->n_tok);
if (l.full) {
l.mla.prepare(c, batch);
l.index.step(c, batch);
l.mla.finish(c, batch);
} else
l.kda.step(c, batch);
}
static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) {
if (!m.have_mtp || batch->draft_pass == 1) {
rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1");
return;
}
const int64_t T = batch->n_tok;
m.mtp.step_inputs(c, batch);
auto& l = m.draft;
l.norm.step(c, T);
l.mla.prepare(c, batch);
l.index.step(c, batch);
// A history pass with no proposal row fills the draft caches and ends there.
if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return;
l.mla.finish(c, batch);
m.mtp.step_join(c, batch, m.y);
l.moe.step_rows(c, GlmMtp::head_rows(batch));
m.mtp.step_head(c, batch);
}
static void step(RadCtx* c, const RadBatch* batch) {
auto& m = *models[rad_rank(c)];
const int64_t T = batch->n_tok;
// An encoder pass runs only the vision tower (RadBatch::enc).
if (batch->enc) {
m.vit.step(c, batch);
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));
m.mrows.step(c, batch, m.x, T);
if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE);
for (int i = 0; i < 4; ++i)
RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T));
for (int i = 0; i < 45; ++i) {
auto& l = m.layers[i];
l.attn_hc.read(c, T);
attention(c, l, batch);
l.attn_hc.write(c, T);
l.ffn_hc.read(c, T);
if (i < 3)
l.dense.step(c, batch);
else
l.moe.step(c, batch);
l.ffn_hc.write(c, T);
}
RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), brows(m.x, T));
RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T),
praw(batch->out_ids, RAD_I32, batch->n_out),
brows(m.logit_input, batch->n_out));
RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
}
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth;
// The tower's merged block, so a pass size the core picks itself is whole output rows.
if (GlmVision::present(meta)) {
const int64_t k = rad_meta_geti(meta, "vision_config.spatial_merge_size", 0);
if (k > 0) out->enc_merge = k * k;
}
out->shape_probe_ok = 1;
return RAD_OK;
}
} // namespace glm5next
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PROBE(glm5next)
RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0",
"GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP")
#endif
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/krea2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(krea2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(krea2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/krea2.cpp)
+1466
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(ltx2 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(ltx2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ltx2.cpp)
+4196
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -928,6 +928,41 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
return m.op_embed ? RAD_OK : RAD_E_INVAL;
}
/* ================================================================== adapter key names */
/* LoRA files for H3 name the DiT by ComfyUI's modules (comfy/ldm/minimax): one fused
* `attn.qkv_proj` (q, k, v), `attn.out_proj`, and `mlp.fc1` with the SwiGLU's gate half first,
* where the checkpoint keeps the value half first in `ff.net.0.proj`. */
static int declare_lora_names(RadBuilder* b, const Model& m) {
std::vector<LoraName> n;
const int64_t Q = m.gd.n_head_all * m.gd.head_dim, KV = m.gd.n_head_kv_all * m.gd.head_dim;
const int64_t F = m.gd.n_ff_all;
static const char* const kBlocks[][2] = {
{ "blocks.#.", "transformer_blocks.#." },
{ "token_refiner.blocks.#.", "token_refiner.refiner_blocks.#." },
};
for (const auto& bl : kBlocks) {
const std::string f = bl[0], t = bl[1];
n.push_back({ f + "attn.qkv_proj", t + "attn.to_q", 0, Q, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_k", Q, Q + KV, 0 });
n.push_back({ f + "attn.qkv_proj", t + "attn.to_v", Q + KV, Q + 2 * KV, 0 });
n.push_back({ f + "attn.out_proj", t + "attn.to_out.0" });
n.push_back({ f + "attn.to_gate_compress", t + "attn.to_gate_compress" });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", 0, F, F });
n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", F, 2 * F, 0 });
n.push_back({ f + "mlp.fc2", t + "ff.net.2" });
}
n.push_back({ "blocks.#.adaln_proj.linear", "transformer_blocks.#.adaln_proj.linear" });
n.push_back({ "video_patch_proj", "proj_in" });
n.push_back({ "audio_patch_proj", "audio_proj_in" });
n.push_back({ "condition_proj", "context_embedder" });
n.push_back({ "time_embedder.proj_in", "time_embedder.linear_1" });
n.push_back({ "time_embedder.proj_out", "time_embedder.linear_2" });
n.push_back({ "final_layer.video_out", "proj_out" });
n.push_back({ "final_layer.audio_out", "audio_proj_out" });
n.push_back({ "final_layer.adaln_proj.linear", "norm_out.linear" });
return lora_names(b, "transformer.", kLoraDiffusionSpellings, n);
}
/* ================================================================== the token refiner */
/* `context_embedder` (5120 -> 5376, bf16, replicated), two plain blocks with full attention over
* the prompt and no rotary, and the final RMSNorm into the lane's prompt rows. The feed-forward is
@@ -3201,6 +3236,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */
m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D },
RAD_BUF_PERSIST);
RAD_ARCH_TRY(declare_lora_names(b, m));
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_refiner(b, meta, m));
RAD_ARCH_TRY(declare_tables(b, meta, m));
+150 -9
View File
@@ -45,9 +45,30 @@
* and includes this file. Every difference is behind `#if QWEN35_MOE`: the expert-count check, the
* routing geometry read from metadata, the block's buffers, the per-layer source names, the MTP
* head's feed-forward, and the plugin identity. */
/* ============================== AND A THIRD: qwen35_w8a8 ==============================
*
* `qwen35_w8a8` is the dense build with an int8 trunk: every large linear `i8*bf16[1x128]/fwht128`,
* rotated by a 128-wide Hadamard and served at i8a8h, each quantising its own input from the bf16
* plane (LinearFP8's int8 branch). The producers already write that plane, as they do for a rotated
* MXFP4 linear, so the graph is this one. It is a plugin of its own because the quantisation
* descriptor is half of the selection key: `w8a8_fwht128`, which names the rotation, so a plain
* int8 trunk is refused.
*
* Its differences are behind `#if QWEN35_W8A8`: check_format's method, the probe that learns the
* trunk is int8 before the activations are declared (and refuses one that is not), and the plugin
* identity. The int8 activation pairs follow from the probe. */
#ifndef QWEN35_MOE
#define QWEN35_MOE 0
#endif
#ifndef QWEN35_W8A8
#define QWEN35_W8A8 0
#endif
#if QWEN35_MOE && QWEN35_W8A8
#error "qwen35_w8a8 is the dense build; a routed int8 trunk is not a format this file serves"
#endif
/* The plugin's name for a message, expanded once more so it is QWEN35_NS's value. */
#define QWEN35_STR_X(x) #x
#define QWEN35_STR(x) QWEN35_STR_X(x)
#ifndef QWEN35_NS
#define QWEN35_NS qwen35_fp8
#endif
@@ -101,6 +122,10 @@ struct Model {
rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0;
/* The trunk's linears are int8 (LinearFP8::i8), learned before the activations are declared
* because it decides whether they carry an int8 code pair. Only qwen35_w8a8 sets it. */
bool trunk_i8 = false;
/* the residual stream and the two vocabulary edges */
rad_buf b_x = 0, b_hout = 0, b_logits = 0;
ActFP8 a_h{};
@@ -126,6 +151,8 @@ struct Model {
ActFP8 a_eff{};
rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0;
ActFP8 a_sff{};
/* Rotated codes of the expert input, for rotated four-bit experts (MoeFP8::Config::expert_rot). */
ActFP8 a_hr{};
#endif
/* The DFlash2 drafter, declared only when the container carries one and the deployment
@@ -178,6 +205,18 @@ static Model g_model[MAX_RANKS];
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 QWEN35_W8A8
/* The format the convert stated (the recipe's --set keys); the trunk probe in declare() holds
* the weights to it. */
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
fprintf(stderr, "radiance: qwen35_w8a8 serves a container converted for an int8 trunk "
"(quant_method 'w8a8', fmt 'fwht128': data/recipes/"
"q38-27b-w8a8-df2.recipe's --set keys); this one says '%s' / '%s'.\n",
method ? method : "(none)", fmt ? fmt : "(none)");
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
#else
const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr);
if (method && std::strcmp(method, "fp8") != 0) {
@@ -204,6 +243,7 @@ static int check_format(const RadModelMeta* meta) {
}
}
return RAD_OK;
#endif
}
/* The DFlash2 drafter: its geometry, KV group, buffers and block.
@@ -406,8 +446,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
#else
if (meta->n_expert > 0) {
fprintf(stderr, "radiance: qwen35_fp8 refuses a checkpoint with %lld experts; that is "
"qwen35moe\n", (long long)meta->n_expert);
fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " refuses a checkpoint with %lld "
"experts; that is qwen35moe\n", (long long)meta->n_expert);
return RAD_E_UNSUPPORTED;
}
#endif
@@ -516,9 +556,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with f16
* scales, K E4M3 as above or int6 the same way (libr4d's fp8_v4 / k6_v4 rows). A token's row
* is 25 or 22 * head_dim / 16 bytes instead of 2 * head_dim, so the group is declared at half
* that and the core sizes pages from it; only those kernels read the layout. The drafter's
* group stays E4M3 (declare_dflash2). The engine asks only for a layout probe() offered. */
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" : nullptr;
if (kvq != RAD_KVQ_NONE && !kvq_name) {
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
return RAD_E_UNSUPPORTED;
}
if (kvq_name && !(g.head_dim == 256 && g.n_head == 6 * g.n_head_kv)) {
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256, gqa 6 "
"only; this model is head_dim %lld, gqa %lld\n", kvq_name,
(long long)g.head_dim, (long long)(g.n_head_kv ? g.n_head / g.n_head_kv : 0));
return RAD_E_UNSUPPORTED;
}
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
fd.head_dim = g.head_dim * row16 / 32;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
/* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */
g.kv_dtype = rad_dtype_name(fd.dtype);
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
if (kvq_name)
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a token "
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
/* The SSM state cache is f32.
*
@@ -544,13 +607,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
cd.conv_width = gc.conv_width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd);
#if QWEN35_W8A8
/* ---- the trunk's stored format, read from the first delta-net layer's input projection as
* qwen4exp_fp8 reads its own: the activations below carry an int8 code pair only for an int8
* trunk, and this build serves only the rotated one its descriptor names. The probe maps the
* weight through the layer's own LinearFP8, which then does not map it again; the resize
* before the layer loop keeps the layers sized here. */
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
if (is_full_attention(l, interval)) continue;
const char* pre = "model.language_model.layers";
RAD_ARCH_TRY(m.layers[(size_t)l].gdn.in.probe(
b, nm, g, nm.f("blk.%lld.ssm_inz", (long long)l),
{ nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l),
nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l) }));
RadEncoding enc{};
m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) &&
linear_is_w8h(enc);
break;
}
if (!m.trunk_i8) {
fprintf(stderr, "radiance: qwen35_w8a8 serves a rotated int8 trunk (i8 codes with a bf16 "
"scale a [1 x 128], /fwht128), and this container's first delta-net input "
"projection is not one; convert with "
"data/recipes/q38-27b-w8a8-df2.recipe\n");
return RAD_E_DTYPE;
}
#endif
/* ---- activation buffers. Every activation that feeds a GEMM has an fp8 copy: an E4M3 plane
* of the same shape and an f32 scale plane with one column per 128. They are transients that
* liveness analysis can share, but not free: the largest, `ffn`'s, is 8192 x 17408 bytes
* (143 MiB) beside its 285 MiB bf16 buffer. */
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd));
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8));
m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim});
m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim});
@@ -566,7 +657,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* it must not share storage with transients. */
m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot},
RAD_BUF_PERSIST);
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim));
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8));
/* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the
* checkpoint keeps them bf16, while the fp8 output gate is the tail of this one
@@ -586,7 +677,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the
* row. */
m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v});
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim));
RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8));
#if QWEN35_MOE
/* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is
@@ -624,6 +715,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
(long long)mc.top_k, (long long)mc.n_expert);
return RAD_E_INVAL;
}
/* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */
mc.calib = calib_dir() != nullptr ? 1 : 0;
/* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a
* container with four-bit experts is served in that format. */
{
MoeFP8::Src ps{};
RAD_ARCH_TRY(moe_expert_sources(b, nm, "format",
"model.language_model.layers.0.mlp.experts", &ps));
RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
}
if (mc.expert_bf16) {
fprintf(stderr, "radiance: qwen35moe: plain bf16 experts are not served by this "
"plugin; convert with a quantising recipe\n");
return RAD_E_UNSUPPORTED;
}
}
{
/* The step's height for everything with one row per token, and a pass's height only for
@@ -654,11 +760,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1});
}
if (mc.expert_rot) RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd));
}
#else
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff));
RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8));
#endif
#if QWEN35_W8A8
/* ---- the rotated trunk's quantisers in their producers. Every reader of `h`'s codes is a
* rotated int8 projection (q, k, v; the delta net's qkv|z; gate_up), and of `ffn`'s the down
* projection, so where libr4d serves the `_had_quant_i8g` forms the norms and the gated
* product write had_quant_act_i8g's codes themselves (ActFP8::q8_rot) and those projections
* declare no quantiser: one launch for q, k and v instead of three, and none before down. The
* codes are the same bytes. Where the forms are not declared (the CPU kernels), each
* projection quantises its own input from the bf16 plane, as before. */
if (rad_op_declared(b, "rmsnorm_had_quant_i8g") &&
(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;
#endif
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
@@ -762,6 +883,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt;
mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe;
mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate;
mw.hr = m.a_hr;
#else
mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn;
#endif
@@ -813,7 +935,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ms.cfg = m.moecfg;
ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l);
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l);
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
if (m.moecfg.n_ff_shared > 0) {
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
@@ -916,7 +1039,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* MtpBlockFP8 is a template over the feed-forward. */
ts.mlp.cfg = m.moecfg;
ts.mlp.router = nm.ckpt("mtp.layers.0.mlp.gate.weight");
ts.mlp.experts = nm.ckpt("mtp.layers.0.mlp.experts");
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("mtp.layers.0.mlp.experts"),
&ts.mlp));
if (m.moecfg.n_ff_shared > 0) {
ts.mlp.shared = nm.ckpt("mtp.layers.0.mlp.shared_expert");
ts.mlp.shared_gate = nm.ckpt("mtp.layers.0.mlp.shared_expert_gate.weight");
@@ -1109,6 +1233,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
* 0 when the container carries no drafter. */
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (!meta || !out) return RAD_E_INVAL;
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d's rows for them are the h256/gqa6 attention
* family's (Qwen3.8-27B), so other geometries are refused at startup rather than in declare. */
{
const long long hd = meta->head_dim ? meta->head_dim
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
}
const char* da = rad_meta_gets(meta, "draft.architectures", "");
if (da && std::strstr(da, "DFlash2")) {
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
@@ -1137,6 +1270,14 @@ QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
"dense graph with a routed feed-forward (256 experts, 8 a token, and a shared "
"expert), gated attention over paged KV every fourth layer and gated delta net "
"between")
#elif QWEN35_W8A8
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), 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; gated attention over paged KV every fourth layer and "
"gated delta net between")
/* An imported checkpoint is never a rotated int8 trunk: qwen35_fp8 serves those. */
RAD_ARCH_SERVES_IMPORTS(0)
#else
QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0",
"Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), block-scaled fp8 weights and fp8 "
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/qwen35_w8a8 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(qwen35_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(qwen35_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_w8a8.cpp)
+19
View File
@@ -0,0 +1,19 @@
/* qwen35_w8a8 -- Qwen3.5 / 3.6 / 3.8 dense with an int8 trunk: i8 weights with a bf16 scale a 128
* of K, rotated by a 128-wide Hadamard, against int8 activations quantised under the same rotation.
*
* This is arch/qwen35_fp8/qwen35_fp8.cpp built again, as qwen35moe_fp8 is: the same gated
* attention, gated delta net, MLP, layer schedule, rope, vocabulary edges, drafters and vision
* tower. A linear's weight encoding makes it int8 (arch/common/rad_fp8.h: LinearFP8):
* `i8*bf16[1x128]/fwht128` is gemm_nt_q at i8a8h behind had_quant_act_i8g, each linear quantising
* its own input from the bf16 plane its producer already writes. The places this build differs are
* behind `#if QWEN35_W8A8` in that file.
*
* A plugin of its own rather than qwen35_fp8 serving any encoding it is handed, because the
* quantisation descriptor is half of the selection key (spec §2.4): a container converted with
* data/recipes/q38-27b-w8a8-df2.recipe says `w8a8_fwht128`.
*/
#define QWEN35_W8A8 1
#define QWEN35_NS qwen35_w8a8
#define QWEN35_ARCH_ID "qwen35"
#include "../qwen35_fp8/qwen35_fp8.cpp"
+56 -1
View File
@@ -109,6 +109,11 @@ struct Layer {
QsaIndexer qsa; /* full-attention layers only; inert when the checkpoint has none */
GdnFP8 gdn;
MoeFP8 mlp;
/* The control vector's projection, applied to the wide stream right after this layer's
* feed-forward write -- where llama.cpp's `build_cvec(res_hc, il)` sits in the `qwen4exp`
* graph. Inert (no op) when the deployment has no vector or this layer is outside its range
* (arch/common/rad_block_hc.h). */
HcProject proj;
};
struct Model {
@@ -649,8 +654,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
/* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with
* f16 scales, K E4M3 as above or int6 the same way (libr4d's gqa12 and four-rank gqa6
* rows for these layers). A token's row is 25 or 22 * head_dim / 16 bytes instead of
* 2 * head_dim, so the group is declared at half that and the core sizes pages from it;
* only those kernels read the layout. The MTP head's layer shares this group. The engine
* asks only for a layout probe() offered. */
const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE;
const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4"
: nullptr;
if (kvq != RAD_KVQ_NONE && !kvq_name) {
fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq);
return RAD_E_UNSUPPORTED;
}
/* A rank's ratio: twelve at one and two ranks, six at four (each KV head replicated
* across a rank pair). */
if (kvq_name && !(g.head_dim == 256 && (g.gqa() == 12 || g.gqa() == 6))) {
fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256 and a "
"rank's gqa 12 or 6 only; this rank is head_dim %lld, gqa %lld\n",
kvq_name, (long long)g.head_dim, (long long)g.gqa());
return RAD_E_UNSUPPORTED;
}
const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32;
fd.head_dim = g.head_dim * row16 / 32;
m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype);
if (kvq_name)
rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a "
"token and head instead of %lld", kvq_name,
kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16),
(long long)(2 * g.head_dim));
RadKVGroupDecl sd{};
sd.kind = RAD_KV_LINEAR;
@@ -913,6 +946,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
/* The stream's initial value: hc identical copies of the embedding. */
RAD_ARCH_TRY(m.enter.declare(b, g, m.hccfg.hc, m.a_x.x, m.b_h));
/* The control vector's per-token switch, when this deployment found one (HcProject). All zeros
* is the stock model, so a request that does not ask for the vector is unaffected. */
const rad_buf proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec);
/* ---- the layers.
*
* Declaration order is the buffer planner's liveness: a transient lives over [first
@@ -1142,6 +1179,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
lay.mlp.gather_out_rows = lay.hc_ffn.gather_rows;
lay.mlp.gather_out_rows6 = lay.hc_ffn.gather_rows6;
}
/* The control vector's projection for this layer, if the vector steers it. */
RAD_ARCH_TRY(lay.proj.declare(b, nm.f("blk.%lld.proj", (long long) l), g, l, ctx->cvec,
proj_on, m.b_h, m.hccfg.hc));
}
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
@@ -1513,6 +1554,8 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
for (int64_t p = 0; p < K; ++p) {
if (p == K - 1) wait1();
l.hc_ffn.write(c, T, r0(p), rn(p));
/* The projection of this piece, before the next layer reads it. */
l.proj.step(c, r0(p), rn(p));
if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p));
}
if (ple_next) {
@@ -1556,6 +1599,8 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
l.hc_ffn.read_pieces(c, T);
l.mlp.step(c, batch);
l.hc_ffn.write(c, T, 0, T);
/* The request's control vector, on the stream the write just finished. */
l.proj.step(c, 0, T);
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
}
}
@@ -1622,6 +1667,16 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0)
out->draft_depth = 3;
out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */
/* --kv-cache-dtype fp8_v4 / k6_v4: libr4d has their rows for the QSA layers' geometry
* (head_dim 256, twelve queries per KV head; gqa6 with 4-token pages at four ranks), so other
* geometries are refused at startup rather than in declare. */
{
const long long hd = meta->head_dim ? meta->head_dim
: (meta->n_head ? meta->n_embd / meta->n_head : 0);
const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head;
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
}
return RAD_OK;
}
+12 -285
View File
@@ -47,6 +47,7 @@
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include <arch/rad_block_vit.h>
#include <arch/rad_vae2d.h>
#include <algorithm>
#include <cmath>
@@ -75,291 +76,6 @@ static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 1
static const char* kSysPrompt = "Comprehend and analyze the provided prompt.";
/* ================================================================== the VAE as a recorded graph
*
* Image size varies per request, so the VAE's ops are declared once for the largest image and
* issued with the actual extents: every image operand is a raw [height, width * channels] view of
* its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the
* stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare()
* and step() walk the same list.
*
* Every output is its own buffer, sized for its stage; the planner shares storage between those
* whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued
* in declaration order. */
struct VImg {
rad_buf buf = 0;
int64_t ch = 0;
int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */
};
struct VOp {
enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN } kind = CONV;
rad_op op = 0;
VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */
rad_weight w = 0, b = 0;
int k = 1, up = 1, stride = 1;
int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */
};
struct Vae {
std::vector<VOp> ops;
Names* nm = nullptr;
RadBuilder* b = nullptr;
const char* scope = ""; /* "dec" or "enc" */
bool down = false; /* an encoder: a level halves the side */
int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */
int n_buf = 0;
int first_group = 0;
/* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows
* (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts),
* so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its
* band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach
* the band. The ops before it include the mid-block's attention, which reads every pixel, and
* run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no
* tail. */
int band_from = -1;
int64_t halo = 0;
std::vector<rad_buf> whole;
int64_t px_at(int lvl) const {
int64_t p = base_px;
for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4;
return p;
}
VImg img(int64_t ch, int lvl) {
VImg v;
v.ch = ch;
v.lvl = lvl;
v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch });
return v;
}
rad_weight wt(const char* name, const char* src, std::initializer_list<int64_t> shape) {
if (map_copy(b, name, src) < 0) return 0;
return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE,
grp_layer(first_group));
}
/* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */
VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad,
const char* ckpt) {
VOp o;
o.kind = VOp::CONV;
o.x = x;
o.up = up;
o.stride = stride;
int lvl = x.lvl;
if (up == 2) lvl = down ? lvl - 1 : lvl + 1;
if (stride == 2) lvl = down ? lvl + 1 : lvl - 1;
o.y = img(cout, lvl);
o.k = k;
o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k });
o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout });
o.op = RAD_OP(b, "conv2d_nhwc",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", cout), RAD_INT("k", k),
RAD_INT("stride", stride), RAD_STR("pad", pad),
RAD_INT("up", up), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w, o.b));
/* An input with no buffer is the picture the pass staged, read where it lies. */
if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf });
else rw(b, o.op, {}, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */
VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) {
VOp o;
o.kind = VOp::NORM;
o.x = x;
o.y = img(x.ch, x.lvl);
const char* dn = nm->f("%s.gamma", ckpt);
if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{};
o.w = gamma_rank == 4
? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group))
: decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group));
o.op = rw(b, RAD_OP(b, "l2norm_chan",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("act", silu ? "silu" : "none"),
RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(o.w)),
{ x.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
VImg add(const VImg& x, const VImg& z) {
VOp o;
o.kind = VOp::ADD;
o.x = x;
o.z = z;
o.y = img(x.ch, x.lvl);
o.op = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, z.buf }, { o.y.buf });
ops.push_back(o);
return o.y;
}
/* y += the resampling shortcut of x (in place on y). */
void shortcut(const VImg& x, const VImg& y, int ft) {
VOp o;
o.kind = down ? VOp::S2D : VOp::D2S;
o.x = x;
o.y = y;
o.up = ft;
o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch),
RAD_INT("cout", y.ch), RAD_INT("ft", ft),
RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS),
{ x.buf, y.buf }, { y.buf });
ops.push_back(o);
}
/* A residual block, in -> out channels. */
VImg resblock(const VImg& x, int64_t out, const char* ckpt) {
VImg h = x;
if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt));
VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt));
t = norm(t, true, nm->f("%s.norm2", ckpt), 4);
t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt));
return add(t, h);
}
/* The mid-block's single-head attention over every pixel. */
VImg attention(const VImg& x, const char* ckpt) {
const int64_t C = x.ch;
VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3);
VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt));
VOp o;
o.kind = VOp::ATTN;
o.x = qkv;
o.y = img(C, x.lvl);
o.qkv_ch = 3 * C;
o.op = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)C))),
RAD_NOWEIGHTS),
{ qkv.buf }, { o.y.buf });
ops.push_back(o);
VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt));
return add(p, x);
}
/* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens,
* for the decoder), in the op's schema order, and its ranged value. */
static int64_t side(int64_t s0, int lvl, bool dn) {
int64_t s = s0;
for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2;
return s;
}
/* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the
* level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with
* `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */
void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input,
size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const;
bool is_whole(rad_buf v) const {
for (rad_buf w : whole) if (w == v) return true;
return false;
}
/* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most
* any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x
* upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail
* holds an op that is not row-local, or reads a whole buffer above level 0. */
int64_t band_halo() const {
if (band_from < 0 || ops.empty()) return -1;
std::vector<std::pair<rad_buf, int64_t>> need{ { ops.back().y.buf, 0 } };
auto get = [&](rad_buf v) -> int64_t {
for (const auto& e : need) if (e.first == v) return e.second;
return 0;
};
auto want = [&](rad_buf v, int64_t m) {
for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; }
need.push_back({ v, m });
};
for (size_t i = ops.size(); i-- > (size_t)band_from;) {
const VOp& o = ops[i];
const int64_t my = get(o.y.buf);
switch (o.kind) {
case VOp::CONV: {
if (o.stride != 1) return -1;
const int64_t m = my + o.k / 2;
want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m);
break;
}
case VOp::NORM: want(o.x.buf, my); break;
case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break;
case VOp::D2S: want(o.x.buf, (my + 1) / 2); break;
default: return -1;
}
}
int64_t h = 0;
for (size_t i = (size_t)band_from; i < ops.size(); ++i) {
const VOp& o = ops[i];
for (const VImg* v : { &o.x, &o.z })
if (v->buf && is_whole(v->buf)) {
if (v->lvl != 0) return -1;
h = std::max(h, get(v->buf));
}
}
return h;
}
};
inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu,
const void* input, size_t from, size_t to, int64_t row0) const {
auto ptr = [&](const VImg& v) -> const void* {
if (!v.buf) return input;
const char* p = (const char*)rad_buf_ptr(c, v.buf);
return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p;
};
auto view = [&](const VImg& v, int64_t* H, int64_t* W) {
*H = side(H0, v.lvl, down);
*W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch);
};
auto rows = [&](const VImg& v, int64_t cols) {
const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down);
return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols);
};
for (size_t i = from; i < to && i < ops.size(); ++i) {
const VOp& o = ops[i];
int64_t Hx, Wx, Hy, Wy;
switch (o.kind) {
case VOp::CONV: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y);
break;
}
case VOp::NORM: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch));
break;
}
case VOp::ADD: {
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch));
break;
}
case VOp::D2S:
case VOp::S2D: {
const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy);
RAD_ISSUE_N(c, o.op, Hy * Wy, x, y);
break;
}
case VOp::ATTN: {
/* q, k and v are column slices of the qkv rows, at its 3C pitch. */
const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down);
const int64_t C = o.y.ch, n = H * W;
RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n),
bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n));
break;
}
}
}
}
/* ================================================================== the model */
struct TeLayer {
@@ -1195,6 +911,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* (Vae says why the order matters.) */
m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpVision, true));
/* ---- adapter key names. The DiT's LoRA files use the checkpoint's own names, or
* ComfyUI's, which join the SwiGLU's gate and up projections as `img_mlp.gate_up` [gate; up]
* (comfy/ldm/qwen_image21). */
{
const int64_t F = gd.n_ff_all;
RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings,
{ { "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.gate_layer", 0, F, 0 },
{ "transformer_blocks.#.img_mlp.gate_up",
"transformer_blocks.#.img_mlp.proj", F, 2 * F, 0 } }));
}
RAD_ARCH_TRY(declare_te(b, meta, m));
RAD_ARCH_TRY(declare_encoder(b, meta, m));
RAD_ARCH_TRY(declare_dit(b, meta, m));
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/sdxl -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(sdxl LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(sdxl architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/sdxl.cpp)
+1236
View File
File diff suppressed because it is too large. Load diff