Archived
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:
commit
a1a75da7e9
415 files changed
+78837
-5310
No files matched your search
+109
-11
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 */
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
@@ -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 */
|
||||
Reference in new issue
Block a user