Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+144
-216
@@ -1,30 +1,25 @@
|
||||
/* rad_block_mtp_hc.h -- the multi-token-prediction head of a model whose residual stream is `hc`
|
||||
* times the model width.
|
||||
*
|
||||
* ============================== WHY THIS IS NOT rad_block_mtp_fp8.h ==============================
|
||||
* ============================== DIFFERENCES FROM rad_block_mtp_fp8.h ==============================
|
||||
*
|
||||
* That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, where the head is a PRE-NORM transformer layer
|
||||
* that reads the trunk's [n_embd] hidden state. It is the same idea, the same indexing and the
|
||||
* same two kinds of pass -- and almost none of the same parts, because Qwen4-Exp's head lives in
|
||||
* the WIDE stream:
|
||||
* That file serves Qwen3.5 / Qwen3-Next / Qwen3.6, whose head is a pre-norm layer reading the
|
||||
* trunk's [n_embd] hidden state. Qwen4-Exp's head has the same indexing and passes but lives in
|
||||
* the wide stream:
|
||||
*
|
||||
* ITS INPUT IS 10240 WIDE `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd], so the hidden
|
||||
* state this head continues from is the trunk's wide stream BEFORE
|
||||
* the output mixer collapses it, not `last_hidden_state`.
|
||||
* THERE ARE TWO fc MATRICES `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd].
|
||||
* So there is no concatenation and no concat-ORDER question: the
|
||||
* hidden half is one square matrix applied to EACH sub-stream and
|
||||
* the embedding half is one product broadcast into all of them.
|
||||
* docs/OPS.md's `mtp_enter` row is that arithmetic.
|
||||
* ITS LAYER HAS TWO GATED `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
|
||||
* RESIDUALS, NOT TWO NORMS exactly as a trunk layer does. There is no `input_layernorm` and
|
||||
* no `post_attention_layernorm` in this checkpoint at all.
|
||||
* AND A MIXER OF ITS OWN `mtp.hyper_connection_mixer` -- a connection with no write half,
|
||||
* which is what collapses the head's wide stream for the lm_head.
|
||||
* It is the 98th connection in the model and the trunk's 97th has
|
||||
* the same shape and the same absent `block_inject_weight`.
|
||||
*
|
||||
* What is NOT different is the part that is easy to get wrong, so it is restated here in full.
|
||||
* 10240-wide input `mtp.pre_fc_norm_hidden.weight` is [hc * n_embd]: the head
|
||||
* continues from the trunk's wide stream before the output mixer,
|
||||
* not `last_hidden_state`.
|
||||
* two fc matrices `mtp.fc_hidden` and `mtp.fc_embedding`, both [n_embd, n_embd], so
|
||||
* no concatenation: the hidden matrix is applied to each
|
||||
* sub-stream and the embedding product broadcast into all of them
|
||||
* (docs/OPS.md's `mtp_enter` row).
|
||||
* gated residuals, no norms `mtp.layers.0.attn_hyper_connection` and `.mlp_hyper_connection`,
|
||||
* as in a trunk layer; no `input_layernorm` or
|
||||
* `post_attention_layernorm`.
|
||||
* its own mixer `mtp.hyper_connection_mixer`, a connection with no write half
|
||||
* that collapses the wide stream for the lm_head (the model's 98th
|
||||
* connection, shaped like the trunk's final one).
|
||||
*
|
||||
* ============================== THE INDEXING ==============================
|
||||
*
|
||||
@@ -32,62 +27,44 @@
|
||||
* writes its K and V at KV position i, with rope position i
|
||||
* predicts the token at i + 2
|
||||
*
|
||||
* DeepSeek-V3's MTP layout, which this family follows: the head's transformer block runs over the
|
||||
* SAME position indices as the trunk and the shift lives entirely in which token gets embedded.
|
||||
* Getting it off by one costs nothing visible -- the drafts are simply wrong, acceptance collapses,
|
||||
* and the model's own output stays exactly correct.
|
||||
* DeepSeek-V3's layout: the head runs over the trunk's position indices and the shift is only in
|
||||
* which token is embedded. An off-by-one shows only as collapsed acceptance.
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* `RadBatch::draft_pass` says which and the SIGN is the whole distinction:
|
||||
* By the sign of `RadBatch::draft_pass` (details in rad_block_mtp_fp8.h):
|
||||
*
|
||||
* < 0 A HISTORY PASS, one row a token, continuing from the trunk's own wide stream. The
|
||||
* head's attention reads its OWN K and V for every earlier position and nothing else in
|
||||
* the engine writes those -- the trunk's prefill fills layers 0..n-1 and leaves the head's
|
||||
* untouched. Without it the head attends to whatever the pool last held, which is not
|
||||
* wrong output (a bad draft is only a rejected draft) but is a drafter that proposes noise.
|
||||
* It is also DRAFT ROUND 1 for the sequences that draft: each one's last history row is
|
||||
* the committed position with the token the trunk chose after it, which is round 1's
|
||||
* whole input, so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
|
||||
* and hands their wide state on as the carry.
|
||||
* > 1 A DRAFT ROUND, one row a sequence, continuing from the head's own stream. There is no
|
||||
* round-1 pass; the history pass is it.
|
||||
* < 0 History pass, one row per token, continuing from the trunk's wide stream. It writes the
|
||||
* head's own K and V, which nothing else writes. It is also draft round 1 for drafting
|
||||
* sequences: it ends in the lm_head over their rows (RadBatch::draft_out_ids) and hands
|
||||
* their wide state on as the carry.
|
||||
* > 1 Draft round, one row per sequence, continuing from the head's own stream.
|
||||
*
|
||||
* ============================== THE CARRY, AND WHY IT IS A COPY ==============================
|
||||
* ============================== THE CARRY ==============================
|
||||
*
|
||||
* `hin` is what a round continues FROM and `hw` is the head's own stream. They cannot be one
|
||||
* buffer: `mtp_enter` reads the whole wide row to produce every channel of its output, so a
|
||||
* workgroup writing channels 0..31 would clobber input another workgroup has not read yet. The
|
||||
* pre-norm head has no such problem because its carry is written by a DIFFERENT op at the end of
|
||||
* the round (`mtp.norm`), and here the end of the round is the mlp connection's write, in place.
|
||||
*
|
||||
* So one `cast` copies `hw` back to `hin` between rounds -- a 20 KB row copy at decode, whose cost
|
||||
* is its launch -- and it is SKIPPED on the last round because nothing reads it there. A history
|
||||
* pass that drafts takes its carry with a `gather_rows` instead, of the round-1 rows alone, and
|
||||
* copies them back to the front of `hw`, where the mixer reads a round's rows.
|
||||
* `hin` is what a round continues from and `hw` the head's own stream. They cannot share a buffer:
|
||||
* `mtp_enter` reads the whole wide row for every output channel, so in-place writes would clobber
|
||||
* unread input. (The pre-norm head's carry is written by a different op, `mtp.norm`; here the
|
||||
* round ends with the mlp connection's in-place write.) A `cast` copies `hw` to `hin` between
|
||||
* rounds (a 20 KB row at decode), skipped on the last round. A drafting history pass instead
|
||||
* gathers its round-1 rows and copies them back to the front of `hw`, where the mixer reads them.
|
||||
*
|
||||
* ============================== THE KV CACHE ==============================
|
||||
*
|
||||
* The head's attention layer is bound to the TRUNK'S full-attention group as one more layer, at
|
||||
* absolute index n_layer. The slot mapping and the block table are the trunk's, so the head writes
|
||||
* its K and V at the slot the trunk's token for that position occupies and A REJECTED DRAFT'S
|
||||
* ENTRY IS OVERWRITTEN BY THE NEXT STEP'S CORRECT TOKEN AT THE SAME ADDRESS. Draft rounds run in
|
||||
* position order and each writes its own position before attending to it, so there is no rollback
|
||||
* to get wrong. The cost is that the group's page grows from 12 layers to 13 -- 8% more attention
|
||||
* KV -- and it is paid only when the deployment declares speculation.
|
||||
* The head's attention is bound to the trunk's full-attention group as one more layer, at
|
||||
* absolute index n_layer, sharing its slot mapping and block table; a rejected draft's entry is
|
||||
* overwritten by the next step's token at the same address (see rad_block_mtp_fp8.h). The group's
|
||||
* page grows from 12 layers to 13 (8% more attention KV), only when speculation is declared.
|
||||
*
|
||||
* ============================== WHAT IS AND IS NOT DECLARED ==============================
|
||||
* ============================== BUFFERS ==============================
|
||||
*
|
||||
* The head reuses the TRUNK'S working buffers for its layer -- `attn_qg`, the expert planes, the
|
||||
* narrow block input. Every one of them is dead by the time a draft round runs (the trunk step has
|
||||
* been sampled and committed) and a second set would be 150 MiB of activation planes for one
|
||||
* layer. Only the wide stream, the carry, the embedding and the head's own logits path are its
|
||||
* own, because those must survive the round that produced them.
|
||||
* The layer reuses the trunk's working buffers (`attn_qg`, the expert planes, the narrow block
|
||||
* input), which are dead once the trunk step is committed; a second set would be 150 MiB. Only
|
||||
* the wide stream, the carry, the embedding and the logits path are its own.
|
||||
*
|
||||
* THIS BLOCK MUST THEREFORE BE DECLARED AFTER THE TRUNK'S LAST OP. Declaration order IS the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp) and a drafter declared mid-trunk shares bytes
|
||||
* with buffers the trunk still has live. The signature of getting it wrong is fluent output with
|
||||
* acceptance EXACTLY zero.
|
||||
* Invariant: declare this block after the trunk's last op. Declaration order is the buffer
|
||||
* planner's liveness (core/build/rad_bufplan.cpp); declared mid-trunk, the head would share bytes
|
||||
* with live trunk buffers (symptom: correct output, zero acceptance).
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MTP_HC_H
|
||||
#define RAD_BLOCK_MTP_HC_H
|
||||
@@ -99,32 +76,24 @@
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* HOW MANY CANDIDATES THE COARSE HEAD PROPOSES, and it is 8 because they are RESCORED.
|
||||
/* Candidates the coarse 2-bit head proposes for exact rescoring (`logit_rerank` against the
|
||||
* full-precision head) before column 0 is read. The 2-bit head's top-1 differs from the exact one
|
||||
* often enough to cost acceptance; 8 is the reference implementation's value, which recovered
|
||||
* 99.63% agreement with the exact argmax, at R rows of the weight per draft row (40 KB against
|
||||
* 318 MB).
|
||||
*
|
||||
* A draft needs one token. The 2-bit head picks a different top-1 than the exact head often enough
|
||||
* to cost several points of acceptance, so the coarse head proposes R candidates and
|
||||
* `logit_rerank` scores those R against the full-precision head before column 0 is read. 8 is the
|
||||
* reference implementation's number, which recovered a coarse head to 99.63% agreement with the
|
||||
* exact argmax; the cost is R rows of the weight a draft row, 40 KB against 318 MB. */
|
||||
/* AND R HAS AN OPTIMUM, which is not the obvious thing. A wider candidate set can only raise the
|
||||
* EXACT score the rescore selects, so more candidates ought to be free -- and both sixteen and
|
||||
* four are reproducibly worse than eight on draft acceptance.
|
||||
*
|
||||
* Because acceptance is agreement with the TRUNK and the rescore maximises the MTP HEAD's own
|
||||
* preference over the candidate set. Past some width, taking that preference more seriously walks
|
||||
* away from the trunk's argmax -- so the coarse head's ranking is a useful restriction and not
|
||||
* just noise to be corrected. */
|
||||
* Both 4 and 16 give lower acceptance than 8: acceptance is agreement with the trunk, while the
|
||||
* rescore maximises the head's own preference, so beyond some width the coarse ranking is a useful
|
||||
* restriction. */
|
||||
static constexpr int64_t kDraftTopR = 8;
|
||||
|
||||
struct MtpHcBlock {
|
||||
struct Wire {
|
||||
/* [max_tok, hc * n_embd] the TRUNK's wide stream for the step just run. A pass names the
|
||||
* rows it wants through out_ids and never has to know how they were laid out. */
|
||||
/* [max_tok, hc * n_embd] the trunk's wide stream for the step just run; a pass names the
|
||||
* rows it wants through out_ids. */
|
||||
rad_buf src = 0;
|
||||
rad_buf hin = 0; /* [max_tok, hc * n_embd] what this round continues from */
|
||||
rad_buf hw = 0; /* [max_tok, hc * n_embd] the head's own wide stream */
|
||||
@@ -132,12 +101,12 @@ struct MtpHcBlock {
|
||||
rad_buf inj = 0; /* [max_tok, hc] both connections' write gains */
|
||||
rad_buf hout = 0; /* [max_logit_rows, n_embd] the mixer's output, the lm_head's input */
|
||||
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
|
||||
ActFP8 x{}; /* the narrow block input -- the TRUNK's */
|
||||
/* THE 2-BIT DRAFT HEAD's working set. Every one of these is a draft round's, so they are
|
||||
* sized at max_logit_rows: a history pass never reaches any of them. */
|
||||
ActFP8 x{}; /* the narrow block input, the trunk's */
|
||||
/* The 2-bit draft head's working set, sized at max_logit_rows (only drafting rows reach
|
||||
* it). */
|
||||
rad_buf dq = 0, ds = 0, dsum = 0, dlog = 0, didx = 0, dval = 0;
|
||||
/* The vocab-parallel pair, declared only when the head is SHARDED. Both are (int32 id,
|
||||
* float value) pairs read as f32: this rank's top-1, and the all-gathered world * 1. */
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
@@ -160,12 +129,11 @@ struct MtpHcBlock {
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
int64_t rows = 0;
|
||||
int depth = 0; /* rounds this deployment will run -- the carry's last-round test */
|
||||
int64_t ngroup = 0; /* the pre-fc norm's groups: hc, one rsqrt a sub-stream */
|
||||
int depth = 0; /* rounds this deployment runs; decides whether the carry is needed */
|
||||
int64_t ngroup = 0; /* the pre-fc norm's groups: hc, one rsqrt per sub-stream */
|
||||
bool q2 = false;
|
||||
/* The 2-bit draft head's logical weight: the checkpoint's lm_head under a name of its own,
|
||||
* which a recipe stores as 2-bit codes. The plugin asks mtp_draft_head_q2 about this name --
|
||||
* which also declares its map -- and declares the head's buffers when the answer is yes. */
|
||||
/* The 2-bit draft head's name. The plugin passes it to mtp_draft_head_q2 (which declares the
|
||||
* map) and declares the head's buffers if that returns true. */
|
||||
static const char* head_name(Names& nm) { return nm.f("mtp.draft_head.weight"); }
|
||||
|
||||
rad_weight w_tok = 0, w_lm = 0, w_fc_h = 0, w_fc_e = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
@@ -174,13 +142,15 @@ struct MtpHcBlock {
|
||||
HyperConn hc_attn{}, hc_mlp{}, mixer{};
|
||||
AttnGatedFP8 attn{};
|
||||
QsaIndexer qsa{};
|
||||
/* The indexer's window bounds for a pass wider than its score plane (QsaIndexer::step), set by
|
||||
* the caller before step(); null where no pass is. */
|
||||
const int32_t* qsa_win_cu = nullptr;
|
||||
MoeFP8 mlp{};
|
||||
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_enter = 0, op_carry = 0;
|
||||
|
||||
/* THE PROMPT'S MEDIA ROWS over the head's own embedding: its history pass embeds the prompt
|
||||
* too, one position on, and an image token's embedding is the encoder's there as well. Set
|
||||
* `media` before declare when the program has an encoder. */
|
||||
/* Media rows over the head's embedding (see MtpBlockFP8::media). Set before declare when the
|
||||
* program has an encoder. */
|
||||
|
||||
bool media = false;
|
||||
|
||||
@@ -189,8 +159,8 @@ struct MtpHcBlock {
|
||||
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0;
|
||||
|
||||
/* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
|
||||
* re-derive the rule. */
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
|
||||
|
||||
@@ -206,19 +176,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
const Wire& wire, const Src& src) {
|
||||
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
|
||||
rows = g.max_tok; depth = draft_depth;
|
||||
/* The pre-fc norm over the wide stream is GROUPED, one rsqrt a sub-stream, which is what every
|
||||
* gated residual in this architecture does. A flat norm fits the same [hc*n] gain and no
|
||||
* per-op oracle can tell the two apart; the acceptance rate can -- docs/OPS.md's `mtp_enter`
|
||||
* row. */
|
||||
/* The pre-fc norm over the wide stream is grouped, one rsqrt per sub-stream, like every gated
|
||||
* residual here. A flat norm fits the same [hc*n] gain and passes per-op checks; only the
|
||||
* acceptance rate tells them apart (docs/OPS.md's `mtp_enter` row). */
|
||||
ngroup = hc.hc;
|
||||
if (rows <= 0 || !w_tok || !w_lm || hc.hc <= 1) return RAD_E_INVAL;
|
||||
if (!w.src || !w.hin || !w.hw || !w.e || !w.hout) return RAD_E_INVAL;
|
||||
const int64_t HN = hc.hc * g.n_embd;
|
||||
|
||||
/* ---- the entry's four weights. SHARD_NONE on all of them: two are per-channel gains over a
|
||||
* replicated stream and the two fc matrices read and write that same stream, so a column shard
|
||||
* would need an all-reduce to save 13 MB a rank -- the wrong side of the trade at one launch
|
||||
* per draft round. */
|
||||
/* ---- the entry's four weights, all replicated: two gains over the replicated stream, and two
|
||||
* fc matrices whose column shard would save 13 MB per rank at an all-reduce per round. */
|
||||
const char* nph = nm.f("mtp.pre_fc_norm_hidden.weight");
|
||||
const char* npe = nm.f("mtp.pre_fc_norm_embedding.weight");
|
||||
const char* nfh = nm.f("mtp.fc_hidden.weight");
|
||||
@@ -227,9 +194,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_ARCH_TRY(map_copy(b, npe, src.pre_norm_embedding));
|
||||
RAD_ARCH_TRY(map_copy(b, nfh, src.fc_hidden));
|
||||
RAD_ARCH_TRY(map_copy(b, nfe, src.fc_embedding));
|
||||
/* THE TWO ENTRY MATRICES ARE WHATEVER THEIR ENCODING IS -- bf16, or E4M3 rows with a scale a
|
||||
* group of each row (OPS.md's `fc` on mtp_enter) -- declared over every plane at the codes'
|
||||
* dtype. It only ever changes the DRAFTS: the head proposes and the trunk verifies. */
|
||||
/* The entry matrices are bf16 or E4M3 rows with a per-group scale (OPS.md's `fc` on
|
||||
* mtp_enter), declared over all planes at the codes' dtype; both must match. */
|
||||
const uint32_t fdt = weight_codes_dtype(b, nfh, RAD_BF16);
|
||||
if (weight_codes_dtype(b, nfe, RAD_BF16) != fdt || (fdt != RAD_BF16 && fdt != RAD_F8E4M3)) {
|
||||
fprintf(stderr, "radiance: the MTP head's fc_hidden is %s and fc_embedding %s; the entry "
|
||||
@@ -246,9 +212,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
grp_layer(l));
|
||||
if (!w_pre_h || !w_pre_e || !w_fc_h || !w_fc_e) return RAD_E_INVAL;
|
||||
|
||||
/* A SECOND gather_rows and a SECOND embed_lookup over the trunk's own buffers and weights.
|
||||
* They are separate ops rather than re-issues of the trunk's because an op's read and write
|
||||
* sets are what the buffer planner reads for liveness, and these write somewhere else. */
|
||||
/* Separate gather_rows and embed_lookup ops over the trunk's buffers and weights, because
|
||||
* they write different buffers and liveness comes from each op's read/write sets. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
@@ -261,8 +226,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.e});
|
||||
if (media) RAD_ARCH_TRY(mrows.declare(b, rows, g.n_embd, w.e));
|
||||
/* The trunk's table is vocab-sharded, so this gather is a partial one and needs the same exact
|
||||
* reduction the trunk's does. Its own op because it writes a different buffer. */
|
||||
/* The trunk's table is vocab-sharded, so the lookup is partial and needs an exact
|
||||
* all-reduce. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -281,9 +246,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{w.hin, w.e}, {w.hw});
|
||||
if (!op_gather || !op_embed || !op_enter) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the layer. One gated residual, a gated full-attention block with its indexer, a second
|
||||
* gated residual and the routed feed-forward -- a trunk full-attention layer, at layer index
|
||||
* n_layer, and declared in exactly the order step() issues it in. */
|
||||
/* ---- the layer, as a trunk full-attention layer at index n_layer: gated residual, gated
|
||||
* attention with its indexer, gated residual, routed feed-forward. Declared in step()'s issue
|
||||
* order. */
|
||||
RAD_ARCH_TRY(hc_attn.declare(b, nm, g, nm.f("mtp.attn_hc"), hc, HyperConn::Wire{w.hw, w.x, w.inj},
|
||||
src.hc_attn));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv));
|
||||
@@ -292,10 +257,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
false, false, kArNone, hc_attn.op_ar_write != 0));
|
||||
if (src.qsa.qk_proj)
|
||||
RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
|
||||
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids), before the
|
||||
* feed-forward, which then runs over them alone: gathered into `hin`, one row a drafting
|
||||
* sequence in round order, and copied back to the front of `hw`. Two ops and not one because a
|
||||
* gather in place could overwrite a row another sequence has yet to read. */
|
||||
/* ---- round 1's rows of a history pass (RadBatch::draft_out_ids), moved before the
|
||||
* feed-forward, which then runs on them only: gathered into `hin` and copied back to the
|
||||
* front of `hw` (an in-place gather could overwrite unread rows). */
|
||||
op_dsel = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
@@ -308,7 +272,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{w.hin}, {w.hw});
|
||||
if (!op_dsel || !op_dback) return RAD_E_INVAL;
|
||||
|
||||
/* The rotated expert input rides in this read, as it does on the trunk. */
|
||||
/* The connection's read also writes the rotated expert input, as on the trunk. */
|
||||
HyperConn::Config mcfg = hc;
|
||||
HyperConn::Wire mwire{w.hw, w.x, w.inj};
|
||||
if (src.mlp.cfg.expert_rot) { mcfg.rotate = 1; mwire.rq = w.mlp.hr.q; mwire.rs = w.mlp.hr.s; }
|
||||
@@ -317,7 +281,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
mlp.hr_in = mcfg.rotate != 0;
|
||||
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp, false, false, kArNone,
|
||||
hc_mlp.op_ar_write != 0));
|
||||
/* The write behind the block takes its gather where it can, as on the trunk. */
|
||||
/* The following write takes the MoE gather where it can, as on the trunk. */
|
||||
{
|
||||
HyperConn::GatherSrc gs{};
|
||||
gs.ye = mlp.w.edn;
|
||||
@@ -331,15 +295,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
mlp.gather_out_rows6 = hc_mlp.gather_rows6;
|
||||
}
|
||||
|
||||
/* ---- the carry. See the header: `mtp_enter` cannot be issued in place. */
|
||||
/* ---- the carry (see the header: `mtp_enter` cannot run in place). */
|
||||
op_carry = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", HN),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hw}, {w.hin});
|
||||
|
||||
/* ---- the head's own mixer: the connection with no write half, which collapses its wide
|
||||
* stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
|
||||
/* ---- the head's mixer: a connection with no write half that collapses the wide stream for
|
||||
* the lm_head, which reads bf16, so no fp8 codes. */
|
||||
{
|
||||
HyperConn::Config mc = hc;
|
||||
mc.inject = 0;
|
||||
@@ -349,8 +313,8 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_ARCH_TRY(mixer.declare(b, nm, g, nm.f("mtp.output_hc"), mc, mixw, src.hc_mix));
|
||||
}
|
||||
|
||||
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's own extent:
|
||||
* only a DRAFT round reaches this and a draft round is one row a sequence. */
|
||||
/* The trunk's lm_head over the head's hidden state, banded at the logits buffer's extent (one
|
||||
* row per drafting sequence). */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
@@ -359,33 +323,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{w.hout}, {w.logits});
|
||||
if (!op_carry || !op_logits) return RAD_E_INVAL;
|
||||
|
||||
/* ---- THE 2-BIT DRAFT HEAD. rad_block_mtp_fp8.h argues it in full; the short version is that
|
||||
* `logits_gemm` is already at the memory roofline, so its only lever is FEWER BYTES -- and
|
||||
* a speculative step runs the projection once to verify and once PER DRAFT ROUND. A draft is a
|
||||
* proposal the target verifies with its own head, so a worse draft costs acceptance and
|
||||
* cannot change a token the model emits. */
|
||||
/* ---- The 2-bit draft head (rationale in rad_block_mtp_fp8.h): fewer bytes per draft round,
|
||||
* at the cost of acceptance only. */
|
||||
enum { MTP_W2_GROUP = 128 };
|
||||
/* A DRAFT NEEDS ONE TOKEN AND THE TOP-R IS WIDER THAN THAT; kDraftTopR says why. There is also
|
||||
* a HARD LOWER BOUND of 2 from the all-gather: `ar_gather_2rank` places rank r's contribution
|
||||
* row-interleaved and requires the row to be a whole number of 16-byte words, and a pair is
|
||||
* (int32 id, float value) -- so R = 1 is an 8-byte row and is refused, while R = 2 is 16. The
|
||||
* engine reads column 0 through `proposal_pitch`, which is what that field is for. */
|
||||
/* R is kDraftTopR. It must also be at least 2: `ar_gather_2rank` needs rows of whole 16-byte
|
||||
* words and a pair is 8 bytes. The engine reads column 0 through `proposal_pitch`. */
|
||||
q2 = w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
|
||||
if (q2) {
|
||||
/* AND IT IS VOCAB-PARALLEL, which is 159 MB a round rather than 318. The head does not go
|
||||
* through the sampler, so its argmax is a `row_topk` over one rank's plane -- and a
|
||||
* sharded plane alone would make every rank propose only tokens from its own half. That
|
||||
* is what `row_topk`'s `vocab_off` and `row_topk_merge` are for, and they are the same
|
||||
* three ops arch/common/rad_block_dspark.h already drives: a top-R reporting GLOBAL ids,
|
||||
* an all_gather of (id, value) pairs, and a merge that finds exactly the top-R an
|
||||
* unsharded head would have. */
|
||||
/* Vocab-parallel when possible (159 MB a round instead of 318). Bypassing the sampler, it
|
||||
* uses the same three ops as rad_block_dspark.h: a top-R reporting global ids, an
|
||||
* all_gather of (id, value) pairs, and a merge giving exactly the unsharded top-R. */
|
||||
const bool dh_shard = head_sharded(g) && w.dpair && w.dgath;
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const int64_t hrows = dh_shard ? g.n_vocab : g.n_vocab_all;
|
||||
/* ITS OWN STORED WEIGHT, MADE FROM THE TRUNK'S lm_head by the recipe: two-bit codes with
|
||||
* an f16 scale and a u8 zero point a group of 128 (`u2*f16+u8[1x128]`), its name map
|
||||
* declared by mtp_draft_head_q2. The GEMM takes the codes as one operand and the scale
|
||||
* and zero planes as the other. */
|
||||
/* Its own stored weight made from the trunk's lm_head by the recipe (`u2*f16+u8[1x128]`),
|
||||
* name map declared by mtp_draft_head_q2. The GEMM takes codes as one operand and the
|
||||
* scale/zero planes as the other. */
|
||||
const char* dhn = head_name(nm);
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {hrows, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
|
||||
@@ -405,10 +358,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_INT("group", MTP_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 and reports GLOBAL ids, and it also
|
||||
* writes the pair plane the gather moves. `vocab_off` is omitted entirely when the head is
|
||||
* replicated: an optional parameter present with the value 0 is not the same declaration
|
||||
* as an absent one. */
|
||||
/* 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. */
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
|
||||
@@ -421,29 +373,18 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_INT("R", kDraftTopR), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval});
|
||||
/* ---- THE COARSE HEAD'S CANDIDATES, RESCORED EXACTLY.
|
||||
/* ---- Exact rescoring of the coarse candidates against `w_lm`, the trunk's lm_head
|
||||
* (already resident; the fallback `op_logits` reads it). It reads R rows per draft row in
|
||||
* the trunk's stored layout, which libr4d's rerank shares with its fp8 logits GEMM.
|
||||
*
|
||||
* `w_lm` is the trunk's lm_head: already declared, already resident, already this
|
||||
* block's (it is what the fallback's `op_logits` reads), so the rerank costs no weight.
|
||||
* It reads R rows of it a draft row, in the stored form the trunk's logits_gemm reads:
|
||||
* libr4d's rerank takes the same layout as its fp8 logits GEMM, so one stored head serves
|
||||
* both, and a kernel that reads neither form is not selected for either.
|
||||
* No extra collective: sharded, every candidate is one this rank owns, and the existing
|
||||
* gather and merge then rank exact values. It overwrites `didx`/`dval`/`dpair` in place.
|
||||
*
|
||||
* IT NEEDS NO COLLECTIVE OF ITS OWN. Sharded, `row_topk` picked from THIS RANK'S plane and
|
||||
* reported global ids, so every candidate it hands over is one this rank owns and can
|
||||
* score; the existing all_gather and merge then find the global winner over exact values
|
||||
* instead of coarse ones. The op writes back over `didx`/`dval`/`dpair` in place, which is
|
||||
* what keeps that chain unchanged.
|
||||
* Skipped for a replicated draft head above one rank: the vocabulary did not shard cleanly
|
||||
* (vocab_head_sharded) while the trunk's lm_head stays row-sharded, so candidates include
|
||||
* ids this rank cannot score.
|
||||
*
|
||||
* AND THAT OWNERSHIP IS WHY A REPLICATED DRAFT HEAD ABOVE ONE RANK SKIPS IT. A vocabulary
|
||||
* that does not shard cleanly (vocab_head_sharded) replicates the DRAFT head while the
|
||||
* trunk's lm_head stays row-sharded, so `row_topk` then reports ids from the whole
|
||||
* vocabulary and half of them are not this rank's to score. The coarse head's own answer
|
||||
* stands, unreranked, and the rerank sits out.
|
||||
*
|
||||
* `vocab_off` is passed always and not only when sharded: unlike `row_topk`, this op has
|
||||
* one form, and at world 1 the offset is 0 and `n_vocab` is the whole vocabulary, which is
|
||||
* the same declaration either way. */
|
||||
* `vocab_off` is always passed: this op has one form, and at world 1 it is 0. */
|
||||
const bool rerank = dh_shard || g.world <= 1;
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
@@ -454,16 +395,16 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm));
|
||||
if (!op_drerank) return RAD_E_INVAL;
|
||||
/* Arrays and not rw()'s braced lists: the write set is conditional and a braced list
|
||||
* inside a ternary is a temporary -- rad_fp8.h's NormQuantFP8 records the same. */
|
||||
/* Arrays rather than rw(): the write set is conditional (see rad_fp8.h:
|
||||
* NormQuantFP8). */
|
||||
rad_buf rd[2] = { w.hout, w.didx };
|
||||
rad_buf wr[3] = { w.didx, w.dval, w.dpair };
|
||||
rad_op_reads (b, op_drerank, rd, 2);
|
||||
rad_op_writes(b, op_drerank, wr, dh_shard ? 3 : 2);
|
||||
}
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft row's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride. */
|
||||
/* Row-interleaved, so one draft row's pairs from every rank are adjacent for
|
||||
* `row_topk_merge`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", g.max_logit_rows * kDraftTopR * 2),
|
||||
@@ -482,11 +423,9 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
}
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
}
|
||||
/* THE CARRY STAYS LIVE THROUGH THE WHOLE HEAD. A pass writes `hin` for the round after it
|
||||
* before its mixer and lm_head run; declared as used by the carry alone, the buffer planner
|
||||
* would let the ops after it take its bytes, and the next round would continue from what they
|
||||
* wrote. Nothing fails: acceptance falls. Read by the head's last op as well, it survives
|
||||
* every pass of the step. */
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
* acceptance). */
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
@@ -495,16 +434,15 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One pass of the head. The batch is the one the scheduler built for it: n_tok rows, `token_ids`
|
||||
* already shifted one position on (sched/batch.cpp, token_at), `positions` the head's own indices,
|
||||
* and the KV group batch carrying the slot each row writes at -- so every op below runs at n_tok
|
||||
* rows and the attention layer needs no special case at all. */
|
||||
/* One pass of the head over the scheduler's batch for it: n_tok rows, `token_ids` already shifted
|
||||
* one position on (sched/batch.cpp, token_at), `positions` the head's indices, and the KV group
|
||||
* batch carrying each row's slot, so the attention layer needs no special case. */
|
||||
inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
|
||||
/* The history pass continues from the TRUNK's wide stream; the rounds after it continue from
|
||||
* the head's, which the carry left in the same buffer. */
|
||||
/* The history pass continues from the trunk's wide stream; later rounds from the head's,
|
||||
* which the carry left in the same buffer. */
|
||||
if (r == 1) {
|
||||
rad_step_fail(c, "the MTP head was handed a draft-round-1 pass: that round is carried by "
|
||||
"the history pass (RadBatch::draft_out_ids) and has no pass of its own");
|
||||
@@ -523,34 +461,26 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE(c, op_enter, brows(w.hin, T), brows(w.e, T), RAD_W(w_pre_h), RAD_W(w_pre_e),
|
||||
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
|
||||
|
||||
hc_attn.read(c, T, 0, T);
|
||||
hc_attn.read_pieces(c, T);
|
||||
|
||||
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES THE HEAD'S STATE BEHIND: the K and V of its
|
||||
* rows and the indexer's block keys and tail, all of which come from the block's input. The
|
||||
* query, the indexer's scores and selection, the attention, its output and everything after
|
||||
* compute the head's stream, which only a drafting row reads. Every prefill chunk but a
|
||||
* prompt's last is such a pass. `n_draft_out` is the batch's and the same on every rank, so
|
||||
* the collectives skipped here are skipped on all of them. */
|
||||
/* A history pass with no drafting rows (every prefill chunk but a prompt's last) only stores
|
||||
* the head's state: K and V, and the indexer's block keys and tail. `n_draft_out` is the same
|
||||
* on every rank, so skipped collectives match. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) {
|
||||
qsa.store(c, attn.w.h, batch);
|
||||
attn.store_kv(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
/* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
|
||||
* input is normed and quantised by the connection above, so `w.h` is already what it will be
|
||||
* when the attention runs. */
|
||||
qsa.step(c, attn.w.h, batch);
|
||||
/* The indexer runs first because the attention reads its selection; `w.h` is already final,
|
||||
* written by the connection above. */
|
||||
qsa.step(c, attn.w.h, batch, qsa_win_cu);
|
||||
attn.step(c, batch);
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
|
||||
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
|
||||
* nothing reads the head's stream at any other row: the experts, their connection and the
|
||||
* lm_head would run over a whole prompt chunk for a handful of rows. So round 1's rows come out
|
||||
* of `hw` first -- gathered into `hin` and copied back to its front, two ops because a gather
|
||||
* in place could overwrite a row another sequence has yet to read -- and everything after runs
|
||||
* as a pass of those rows. */
|
||||
/* A history pass with drafting rows continues on those rows alone (round 1): they are moved
|
||||
* to the front of `hw` and the rest of the head runs over them. */
|
||||
int64_t L = T; /* the rows the stream goes on with */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
@@ -559,31 +489,29 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
}
|
||||
|
||||
hc_mlp.read(c, L, 0, L);
|
||||
hc_mlp.read_pieces(c, L);
|
||||
mlp.step_rows(c, L);
|
||||
hc_mlp.write(c, L, 0, L);
|
||||
|
||||
/* THE CARRY, and only where a round after this one will read it. The last round of a group
|
||||
* is followed by a trunk step; a history pass is round 1, followed by round 2 when the
|
||||
* deployment drafts deeper. */
|
||||
/* The carry, only if a later round reads it: a history pass is round 1, followed by round 2
|
||||
* when depth > 1; the last round is followed by a trunk step. */
|
||||
if (r < 0 ? depth > 1 : r < depth)
|
||||
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
|
||||
|
||||
mixer.read(c, L, 0, L);
|
||||
if (q2) {
|
||||
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
|
||||
* whole: there is no row slice of it that means anything. */
|
||||
/* `dsum` is group-major [n_embd/group][ceil(L/16)*16], so it has no row slice; pass it
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, L, brows(w.hout, L), brows(w.dq, L), brows(w.ds, L),
|
||||
RAD_B(w.dsum));
|
||||
/* The trailing `b_ref` is mxfp4's and absent here; an absent optional operand is a null
|
||||
* tensor in a full-length list, not a shorter list (rad_fp8.h says why). */
|
||||
/* The trailing `b_ref` is mxfp4's and absent; operands are positional, so pass RAD_NONE
|
||||
* (rad_fp8.h). */
|
||||
RAD_ISSUE_N(c, op_dlogits, L, brows(w.dq, L), brows(w.ds, L), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, L), RAD_B(w.dsum), RAD_NONE);
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
brows(w.dpair, L));
|
||||
/* In place over all three, so the gather and the merge below are unchanged and now
|
||||
* carry EXACT values instead of the coarse head's. */
|
||||
/* In place over all three, so the gather and merge carry exact values. */
|
||||
if (op_drerank)
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), brows(w.dpair, L));
|
||||
|
||||
Reference in new issue
Block a user