Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,225 @@
|
||||
/* rad_block_attn_fp8.h -- the PLAIN GQA attention block with block-scaled FP8 projections.
|
||||
*
|
||||
* rmsnorm -> quant_act_fp8 -> fused q|k|v gemm_nt_q -> rope -> kv_store -> attn_paged
|
||||
* -> quant_act_fp8 -> o gemm_nt_q -> [all_reduce] -> residual add
|
||||
*
|
||||
* IT IS rad_block_attn_gated_fp8.h WITHOUT THE TWO THINGS THAT MAKE THAT ONE GATED, and those two
|
||||
* are what a family answers differently rather than what a model tunes:
|
||||
*
|
||||
* - NO PER-HEAD Q/K NORM. Qwen3.5 norms each head against its own gain before rotating; LLaMA
|
||||
* and MiniCPM5 rotate the projection as it comes out of the GEMM. A block that normed anyway
|
||||
* against an absent gain would be a different model, and one that normed against a gain of
|
||||
* ones would be a wasted launch a layer.
|
||||
* - NO OUTPUT GATE. There is no second half of the query projection and no sigmoid: the
|
||||
* attention output goes straight into the out-projection.
|
||||
*
|
||||
* WHAT THAT BUYS is the fused q|k|v, which the gated block cannot have: its query projection is
|
||||
* [q|gate] interleaved per head and k and v are separate tensors, so there are three GEMMs a layer.
|
||||
* Here the three weights concatenate along dim 0 into one [q_dim + 2*kv_dim, n_embd] and `rope`
|
||||
* takes exactly that row -- q heads then k heads, v left alone, which is the operand shape the op
|
||||
* was written for (docs/OPS.md). One GEMM, one rope, one quantise in front of all of it.
|
||||
*
|
||||
* THE ROW PARTS ARE NOT DECORATION. A tensor-parallel rank owns a slice of EACH of the three
|
||||
* projections, not a contiguous slice of the stack; without `row_parts` rank 0 gets the whole query
|
||||
* and rank 1 the whole key and value, and both ranks then compute a perfectly well-formed wrong
|
||||
* thing. LinearFP8 also checks that each part is a whole number of 128-row scale blocks, which is
|
||||
* what makes a block-scaled fusion expressible at all.
|
||||
*
|
||||
* Everything else -- the fused norm/quantise/residual/all-reduce op at the front, the KV group's
|
||||
* own dtype, the fold flags -- is rad_fp8.h's and rad_block_attn_gated_fp8.h's and is documented
|
||||
* there.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_FP8_H
|
||||
#define RAD_BLOCK_ATTN_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf qkv = 0; /* [max_tok, q_dim + 2*kv_dim] the fused projection */
|
||||
rad_buf q = 0; /* [max_tok, q_dim] the query, CONTIGUOUS */
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output */
|
||||
};
|
||||
|
||||
/* The checkpoint's tensor names. Whether they hold block fp8 already or a dense tensor the
|
||||
* recipe quantises is the container's business; the declaration is the same either way. */
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
int64_t n_rot = 0;
|
||||
/* The rotation pairs HALVES (NeoX), which is what HF's rotate_half does and what every LLaMA
|
||||
* derivative ships. GPT-J's adjacent pairs would be arithmetically silent too -- no per-op
|
||||
* check tells the two apart -- so this is stated rather than inferred. */
|
||||
const char* mode = "neox";
|
||||
|
||||
rad_weight w_norm = 0;
|
||||
LinearFP8 qkv{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_attn{};
|
||||
rad_op op_rope = 0, op_qlift = 0, op_attn = 0, op_kv_store = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
bool ar_out = false;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold, bool add_out, int ar_in, bool ar_out_) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* One norm, one quantise, one consumer -- and one op, see rad_fp8.h's NormQuantFP8. */
|
||||
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));
|
||||
RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), 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("scale", g.rope_scale),
|
||||
RAD_STR("mode", mode), RAD_INT("rotary_dim", n_rot)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {w.qkv});
|
||||
|
||||
/* THE QUERY IS LIFTED OUT OF THE FUSED ROW, and this op is here because libr4d's paged
|
||||
* attention indexes `q` as one dense [total_q, n_head, head_dim] block and has no pitch
|
||||
* argument for it (r4d_attn_args.h, fill_paged). A column slice of the fused projection has a
|
||||
* row pitch of q_dim + 2*kv_dim, so passing it is refused at issue -- correctly, and loudly.
|
||||
*
|
||||
* The gated block beside this one never needs it: its q comes out of a q|gate de-interleave
|
||||
* that writes a buffer of its own. A plain LLaMA attention has no de-interleave, so the choice
|
||||
* is one `cast` a layer (this) or splitting the projection into q and kv (two more launches a
|
||||
* layer, one GEMM and one rope). The copy is the cheaper of the two at decode, which is the
|
||||
* step that matters, and it is one line to delete if the kernels ever take a q pitch.
|
||||
*
|
||||
* `from` and `to` are the same dtype: `cast` with no conversion is this tree's row copy, and
|
||||
* the drafter tap uses it the same way. */
|
||||
op_qlift = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {w.q});
|
||||
|
||||
/* Declared before kv_store because `block_size` is RAD_DERIVED and kv_store reads the resolved
|
||||
* kernel's value back; see rad_block_attn_gated.h on why the declared order differs from the
|
||||
* issue order. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn.x});
|
||||
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {});
|
||||
|
||||
/* The out-projection's input quantiser. The gated block folds this into its gate pass; there
|
||||
* is no gate here, so it is the plain `quant_act_fp8` over the attention output. */
|
||||
RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim));
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim();
|
||||
|
||||
nq_h.step(c, T);
|
||||
qkv.step(c, w.h, w.qkv, T);
|
||||
/* IN PLACE OVER THE FUSED ROW, which is what makes one launch do both halves: `rope` rotates
|
||||
* `n_head` query heads then `n_head_kv` key heads and leaves the value heads alone. */
|
||||
RAD_ISSUE(c, op_rope, brows(w.qkv, T), praw(batch->positions, RAD_I32, T));
|
||||
|
||||
/* k and v are COLUMN SLICES of the same row, at q_dim and q_dim + kv_dim. */
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
bcol(w.qkv, q_dim, kv_dim, T), bcol(w.qkv, q_dim + kv_dim, kv_dim, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
RAD_ISSUE(c, op_qlift, bcol(w.qkv, 0, q_dim, T), brows(w.q, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
|
||||
q_attn.step(c, T);
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, T)))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_FP8_H */
|
||||
@@ -0,0 +1,369 @@
|
||||
/* rad_block_attn_gated.h -- one GATED grouped-query attention block, bf16 operands, paged KV.
|
||||
*
|
||||
* rmsnorm -> q|gate gemm, k gemm, v gemm -> qk-norm + rope + gate extraction
|
||||
* -> kv_store -> paged attention -> attn * sigmoid(gate) -> o gemm -> [all_reduce] -> residual
|
||||
*
|
||||
* This is Qwen3.5's attention and not Qwen3's, and the difference is not a flag:
|
||||
*
|
||||
* * `q_proj` emits the query AND a per-head output gate INTERLEAVED at a pitch of 2*head_dim.
|
||||
* Head h's query is at h*2*head_dim and its gate at h*2*head_dim + head_dim, so neither is a
|
||||
* contiguous half of the projection and both are strided views of one buffer. libr4d's
|
||||
* `qk_norm_rope_gate` splits [q|gate] per head and takes the stride off the `qg` OPERAND's own
|
||||
* row pitch, so the interleaved layout is the one to declare rather than to convert away at
|
||||
* load. There is no `qg_pitch` PARAMETER to pass -- see pQkNormRopeGate in
|
||||
* libr4d/r4d_rows.cpp -- the stride comes from the operand.
|
||||
* * The gate multiplies the attention OUTPUT -- `out = attn * sigmoid(gate)` -- so it is
|
||||
* extracted before attention and consumed after it. `output_gate_type: "swish"` in the config
|
||||
* names the GDN block's gate, not this one; llama.cpp uses sigmoid here and it is ground truth
|
||||
* (../llama.cpp/src/models/qwen35.cpp, build_layer_attn).
|
||||
* * RoPE is PARTIAL -- `partial_rotary_factor` 0.25 rotates the first 64 of 256 head dims -- and
|
||||
* it is MROPE. See the note on `mode` in declare(): with one position component per token,
|
||||
* which is all RadBatch carries, mrope and neox are the same arithmetic, and that equality is
|
||||
* what makes this declaration honest for text and wrong for an image span.
|
||||
*
|
||||
* K AND V ARE NOT FUSED INTO ONE PROJECTION, and that is a decision with a cost: two GEMM launches
|
||||
* a layer instead of one, and two movement units instead of one. It buys every consumer a
|
||||
* CONTIGUOUS operand. A fused [k|v] row makes the per-head k norm a rank-2 column slice whose last
|
||||
* dimension is kv_dim while the norm's width is head_dim, and a kernel that reads extents off its
|
||||
* operands -- libref does, by rule -- then walks it as if it were contiguous and normalises
|
||||
* across the k/v seam. The fused form is expressible the moment the slice carries the head
|
||||
* dimension in its own right; until then this is correct and slightly slow rather than fast and
|
||||
* silently wrong. libr4d's kernel takes a `k_pitch` for the fused form, so the w8a8 sibling can
|
||||
* make the other choice without changing this block's shape.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_H
|
||||
#define RAD_BLOCK_ATTN_GATED_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnGatedBF16 {
|
||||
/* The activation buffers this block reads and writes. Declared once by the plugin and shared
|
||||
* by every layer of this kind: layers that share a geometry share the buffer (spec §8), and
|
||||
* the liveness analysis over the declared read and write sets is what makes that safe. */
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf qg = 0; /* [max_tok, n_head, 2*head_dim] query and gate, interleaved */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf q = 0; /* [max_tok, q_dim] de-interleaved, normed, rotated */
|
||||
rad_buf gate = 0; /* [max_tok, q_dim] de-interleaved, then sigmoid in place */
|
||||
rad_buf attn = 0; /* [max_tok, q_dim] attention output, then gated in place */
|
||||
};
|
||||
|
||||
/* The checkpoint-side names for one layer. The plugin owns both sides of the map and is the
|
||||
* only component that knows both (spec §2.4), so the block takes the spelling rather than
|
||||
* inventing one -- this architecture arrives as `model.language_model.layers.N.*` from the
|
||||
* safetensors checkpoint and as `blk.N.*` from a GGUF. */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
int64_t n_rot = 0; /* partial rotary: the leading n_rot of head_dim */
|
||||
const char* mode = "mrope";
|
||||
|
||||
rad_weight w_norm = 0, w_qg = 0, w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0, w_o = 0;
|
||||
|
||||
rad_op op_norm = 0, op_qg = 0, op_kp = 0, op_vp = 0;
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0; /* the fallback */
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_sigmoid = 0, op_gate = 0;
|
||||
rad_op op_o = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
const int64_t qg_dim = 2 * q_dim; /* query and gate, one per head, interleaved */
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- weights. Shapes are [out, in]: gemm_nt is A[M,K] times B transposed [N,K], the layout
|
||||
* every transformer weight already has, so nothing is transposed at load.
|
||||
*
|
||||
* The q|gate projection row-shards by HEAD, and that works only because each head's query and
|
||||
* gate are adjacent: rows [h*2*head_dim, (h+1)*2*head_dim) are one head's pair, so a rank's
|
||||
* slice of the head range is a contiguous row range. A projection that put all queries before
|
||||
* all gates would not shard this way. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_qg.weight", l), src.qg));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), src.k));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), src.v));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_qg = decl_w(b, nm.f("blk.%d.attn_qg.weight", l), RAD_BF16, {qg_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
/* One gain vector shared by every head, so it is replicated across ranks even though the heads
|
||||
* are not. */
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
/* ---- ops, in the order they run, with the one exception noted at attn_paged. Each states the
|
||||
* buffers it reads and writes, because that is what the buffer planner computes liveness
|
||||
* from -- and a gated attention layer has six activation buffers where a plain one has three,
|
||||
* so an undeclared use here costs an arena, not a rounding error. */
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
op_qg = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", qg_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qg)),
|
||||
{w.h}, {w.qg});
|
||||
op_kp = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_k)),
|
||||
{w.h}, {w.k});
|
||||
op_vp = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_v)),
|
||||
{w.h}, {w.v});
|
||||
|
||||
/* Fusion is a selection, not a compiler pass (spec §2.3): ask for the fused op, and emit the
|
||||
* sequence it stands for when nothing in the hierarchy serves it.
|
||||
*
|
||||
* THE PROBE IS NOT MADE, because this block cannot fill the fused op's schema. libr4d's
|
||||
* r4d_qk_norm_rope_gate (libr4d/r4d_rows.cpp, pQkNormRopeGate) names the rotary width `rot`,
|
||||
* takes `q_dtype`, and -- the part that matters -- takes a PRECOMPUTED COS/SIN TABLE as a
|
||||
* required input operand instead of `theta`. Nothing in arch/ or core/ builds such a table.
|
||||
* Declaring the op with parameters the schema does not have is a STRUCTURAL error and fails
|
||||
* declare outright; it is not a miss that falls through to the sequence below, because an
|
||||
* unknown parameter is a caller bug and the builder is right to say so.
|
||||
*
|
||||
* What making the probe needs, precisely: a PERSIST buffer of [max_ctx, rot] filled once from
|
||||
* theta, and a way for a plugin to fill a declared buffer at load -- which the ABI has no hook
|
||||
* for, since buffers are arena storage and weights come from the container. Both are real work
|
||||
* and neither belongs in a probe. Until then this model runs the unfused sequence, which is
|
||||
* correct everywhere and is what makes it run on an install with no libr4d at all.
|
||||
*
|
||||
* `mode` would be "mrope" because that is what the model does: mrope_section [11,11,10] over
|
||||
* an interleaved layout. TWO THINGS ABOUT THAT ARE NOT EXPRESSIBLE and both stay true of the
|
||||
* unfused path. The sections have no parameter in any op schema, and RadBatch carries ONE
|
||||
* position component per token, so all three sections would receive the same position. For
|
||||
* text that is not an approximation: every rotary dimension has its own frequency and the
|
||||
* section only decides which position component feeds it, so mrope over equal components is
|
||||
* bit-identical to neox. It stops being identical the moment an image span gives the
|
||||
* components different values, which is why the vision tower needs both a sections parameter
|
||||
* and a 3-row position array before it can be correct. */
|
||||
op_fused = RAD_NULL_HANDLE;
|
||||
{
|
||||
|
||||
/* Per-head RMS norm is an ordinary rmsnorm with M = tokens x heads and n = head_dim. The q
|
||||
* one reads the STRIDED view of the interleaved projection and writes the contiguous q
|
||||
* buffer, so it de-interleaves and normalises in one pass: the copy llama.cpp spends a
|
||||
* ggml_cont on is this op's output operand. The k one runs in place, which is safe for any
|
||||
* implementation that computes a row's scale before writing the row -- and none can do
|
||||
* otherwise. */
|
||||
op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_q_norm)),
|
||||
{w.qg}, {w.q});
|
||||
op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_k_norm)),
|
||||
{w.k}, {w.k});
|
||||
/* Two rope calls rather than one, because q and k are two buffers here. `rope` describes a
|
||||
* fused [q|k|v] row through n_head and n_head_kv; a call that names only q heads is that
|
||||
* row with an empty k and v, which is what a separate q buffer is. */
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
|
||||
{w.k}, {w.k});
|
||||
}
|
||||
|
||||
/* attn_paged is declared BEFORE kv_store even though it runs after it. block_size is
|
||||
* RAD_DERIVED -- the KV block size is a property of the resolved attention kernel and not a
|
||||
* number anyone gets to choose (spec §7.2) -- so it is OMITTED here, the selector skips
|
||||
* constraints on it while matching, writes the winner's value into the resolved geometry, and
|
||||
* kv_store reads it back with rad_kv_block_size(). The two ops touch disjoint buffers, so the
|
||||
* declared order differing from the issue order costs the buffer planner nothing.
|
||||
*
|
||||
* The ranged parameter is q_len, not M: one query row at decode, up to n_spec+1 at a
|
||||
* speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each
|
||||
* band. `scale` is left off: 1/sqrt(head_dim) is the default and is what this model uses. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
/* n_head, max_seqs and max_ctx are what the resolved kernel's SCRATCH HOOK
|
||||
* needs at declare: libr4d sizes a split-KV partial buffer of
|
||||
* num_seqs * q_len * q_heads * splits rows, and gqa gives the head
|
||||
* ratio rather than the count. All three are bounds, which is the
|
||||
* right kind of number for an arena sized once for the worst step. */
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* kv_store writes the group's pool, which is not a declared buffer -- so its write set is
|
||||
* empty and its read set is the two projections it stores. */
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* The gate. Two ops rather than one fused `mul(attn, sigmoid(gate))`, because the vocabulary
|
||||
* has no gated multiply for a bf16 output -- `gated_had_quant_i8` is the same arithmetic with
|
||||
* an int8 epilogue and is what the w8a8 sibling will use instead of this pair.
|
||||
*
|
||||
* The sigmoid's INPUT differs between the two paths and its output does not: the fused kernel
|
||||
* has already written a contiguous gate, and the fallback reads the strided view of the
|
||||
* interleaved projection. Same op, same geometry, one operand spelled two ways -- which is why
|
||||
* there is no second declaration and no branch after this point. */
|
||||
op_sigmoid = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.gate}, {w.gate});
|
||||
|
||||
op_gate = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn, w.gate}, {w.attn});
|
||||
|
||||
op_o = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_o)),
|
||||
{w.attn}, {w.h});
|
||||
|
||||
/* The output projection is column-sharded, so each rank holds a partial sum of the residual
|
||||
* update and the ranks must agree before the add. The core inserts nothing: this collective is
|
||||
* here because the plugin put it here, and --debug-graph shows it exactly here (spec §9).
|
||||
* `exact` is stated rather than defaulted -- a caller that does not say it will accept a
|
||||
* quantised wire gets the exact kernel or no kernel. `hops` is not stated: one-shot against
|
||||
* two-shot is the kernel's business. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* rad_issue records its own failure and the core aborts the step and fails the requests in it,
|
||||
* naming the kernel and the geometry (spec §17). There is nothing a plugin can usefully do
|
||||
* with the status, and ignoring it is what keeps the run phase a flat readable list. */
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_qg, brows(w.h, T), RAD_W(w_qg), brows(w.qg, T));
|
||||
RAD_ISSUE(c, op_kp, brows(w.h, T), RAD_W(w_k), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_vp, brows(w.h, T), RAD_W(w_v), brows(w.v, T));
|
||||
|
||||
if (op_fused) {
|
||||
RAD_ISSUE(c, op_fused,
|
||||
brows(w.qg, T), brows(w.k, T), praw(batch->positions, RAD_I32, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
brows(w.q, T), brows(w.gate, T));
|
||||
} else {
|
||||
/* The q view of the interleaved projection: head_dim columns out of every 2*head_dim, the
|
||||
* declared width kept as the stride. */
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
|
||||
bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
/* The actual query length, not the batch's token count: it is what selects the attention band,
|
||||
* and a verify step and a prefill chunk can carry the same token count at very different
|
||||
* q_len. */
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens. The batch may be ragged -- one prefill chunk beside other
|
||||
* sequences one decode row each -- and without it the kernel has to
|
||||
* assume a single q_len for the whole step, which it cannot. */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
/* out = attn * sigmoid(gate). The fused kernel wrote the gate contiguously; the fallback left
|
||||
* it interleaved and this is where it is read out. */
|
||||
if (op_fused) RAD_ISSUE_N(c, op_sigmoid, T * g.n_head, brows(w.gate, T), brows(w.gate, T));
|
||||
else RAD_ISSUE_N(c, op_sigmoid, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
|
||||
RAD_ISSUE(c, op_gate, brows(w.attn, T), brows(w.gate, T), brows(w.attn, T));
|
||||
|
||||
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_GATED_H */
|
||||
@@ -0,0 +1,550 @@
|
||||
/* rad_block_attn_gated_fp8.h -- the gated GQA block with block-scaled FP8 projections.
|
||||
*
|
||||
* THE ARCHITECTURE IS rad_block_attn_gated.h's AND IS DOCUMENTED THERE: the interleaved query/gate
|
||||
* projection and why it is declared rank 3, the partial mrope and what is not expressible about it,
|
||||
* why k and v are not fused, why the fused qk_norm_rope_gate probe is withdrawn, and why the gate
|
||||
* is a sigmoid. None of that changes with the weight format and none of it is repeated here.
|
||||
*
|
||||
* What differs:
|
||||
*
|
||||
* - q|gate, k, v and o are LinearFP8 -- an E4M3 weight with a bf16 [N/128][K/128] scale plane
|
||||
* declared as a weight of its own, through `gemm_nt_q` at dtype fp8a8.
|
||||
* - two `quant_act_fp8` launches a layer, not four: the three input projections all read the
|
||||
* post-norm hidden state, so one quantise feeds all three, and the output projection gets its
|
||||
* own because it reads the gated attention output.
|
||||
* - everything between the GEMMs -- the per-head norms, rope, kv_store, attn_paged, the sigmoid
|
||||
* and the gate multiply -- is UNCHANGED and still bf16.
|
||||
* - THE KV CACHE'S WIDTH IS `g.kv_dtype` AND NOT `g.dtype`. `dtype` follows the WEIGHTS;
|
||||
* "the cache is bf16 because the weights are fp8" is true of this checkpoint and is not a
|
||||
* rule. `kv_dtype` follows the CACHE, which is a deployment choice: the fp8kv attention family
|
||||
* and its descale operands are in libr4d, and the cache dtype is what selects them.
|
||||
* Both the attention op and kv_store take it, so the two cannot disagree about the width of
|
||||
* the thing one writes and the other reads.
|
||||
*
|
||||
* The q|gate projection is [2*n_head*head_dim, n_embd] = [12288, 5120] at 27B, and its scale plane
|
||||
* is [96, 40]. Row-sharding by head keeps whole 128-row scale blocks together only because
|
||||
* 2*head_dim is 512, a multiple of 128 -- so a rank's slice of the head range is a whole number of
|
||||
* scale rows. LinearFP8 checks that rather than trusting it.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
#define RAD_BLOCK_ATTN_GATED_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnGatedFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf qg = 0; /* [max_tok, n_head, 2*head_dim] query and gate, interleaved */
|
||||
rad_buf k = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf v = 0; /* [max_tok, kv_dim] */
|
||||
rad_buf q = 0; /* [max_tok, q_dim] de-interleaved, normed, rotated */
|
||||
/* [rope_table_rows, rot] f32, the model's, shared by every layer and filled once a step.
|
||||
* Zero means the plugin has not been taught to build one, and then the fused prologue is
|
||||
* not asked for at all. */
|
||||
rad_buf cos_sin = 0;
|
||||
ActFP8 attn{}; /* [max_tok, q_dim] attention output, then gated in place */
|
||||
/* [max_tok, q_dim] the de-interleaved sigmoid gate, in a model whose linears are bf16
|
||||
* (Geom::w_bf16) only: there the gate is `sigmoid` then `mul`, rad_block_attn_gated.h's
|
||||
* pair, and the fp8 path's fused gate-and-quantiser has no form that skips its codes. */
|
||||
rad_buf gate = 0;
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* qg = nullptr; /* self_attn.q_proj.weight -- query AND gate */
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
int64_t n_rot = 0;
|
||||
/* THE KV PAGE, IN TOKENS. 0 means RAD_KV_BLOCK, which is 16 and is what every geometry in
|
||||
* this tree has wanted. It is a field rather than that constant because Qwen4-Exp's QSA
|
||||
* selects 4-TOKEN BLOCKS, and a page of 4 makes the selected set a paged block table instead
|
||||
* of a new attention kernel -- see docs/QSA.md. The attention kernel's own rows must carry a
|
||||
* matching C_EQ("block_size", ...) or nothing resolves, which is the check that keeps this
|
||||
* from being a number anyone can set. */
|
||||
int64_t kv_block = 0;
|
||||
/* THE QSA SELECTION, when this layer has an indexer. Set, and on a step where one query a
|
||||
* sequence makes the selection per-SEQUENCE, the attention is issued with these in place of
|
||||
* the sequence's own block table and context length -- which is the whole of what makes it
|
||||
* sparse. Both are ordinary operands (the block table has always been one), so this is the
|
||||
* SAME op and the SAME kernel reading a different list.
|
||||
*
|
||||
* `sel` is `topk + 1` wide and the kernel takes its block-table pitch from the operand, so
|
||||
* nothing else has to be told. See docs/QSA.md; arch/common/rad_qsa.h produces them. */
|
||||
rad_buf qsa_sel = 0;
|
||||
rad_buf qsa_sequ = 0;
|
||||
/* THE CONTEXT UP TO WHICH THE DENSE PATH IS THE SAME ANSWER, `budget + ratio - 1`. Below it
|
||||
* every complete block is selected and the two paths agree to the bit, and the dense one is
|
||||
* cheaper at prefill -- it reads each key once a query TILE where the sparse one reads a
|
||||
* table a query. Above it the dense path is a different model. Zero means "always sparse",
|
||||
* which is what a caller that has not been told the bound should get. */
|
||||
int64_t qsa_exact_to = 0;
|
||||
/* `sel`'s row pitch, `topk + 1`. The extra slot is the partial page and is not spare --
|
||||
* r4d_qsa_select_bf16.hip says why. */
|
||||
int64_t qsa_topk = 0;
|
||||
/* HOW MANY QUERY ROWS ONE SPARSE ATTENTION LAUNCH CARRIES, and it is a scratch budget rather
|
||||
* than a preference. The decode kernel's split-KV partials are sized AT DECLARE from the
|
||||
* `max_seqs` and `q_len` parameters, so the only way to issue more rows than `max_seqs` is to
|
||||
* declare a larger one -- which grows the scratch arena by `rows * q_len_band * n_head *
|
||||
* (head_dim + 2) * 4`, about 32 MiB at 256 rows on this model, ONCE for the whole program
|
||||
* because the arena is the maximum over ops.
|
||||
*
|
||||
* It matters because the alternative is `max_seqs` itself. At `--max-num-seqs 4` a 2048-token
|
||||
* prefill chunk would be 512 launches a layer, and the dispatch cost of that dominates what
|
||||
* the sparse path saves. 256 makes it 8.
|
||||
*
|
||||
* Raising it further is pure scratch: 512 rows is 63 MiB, 2048 is 253. 256 is the point at
|
||||
* which the launch cost has stopped mattering. */
|
||||
static constexpr int64_t kQsaRows = 256;
|
||||
int64_t qsa_rows() const { return g.max_seqs > kQsaRows ? g.max_seqs : kQsaRows; }
|
||||
/* THE GATED FORM TAKES THE WHOLE STEP IN ONE LAUNCH, because its band is q_len 1 and so its
|
||||
* partials are only `rows * n_head * (2 * head_dim + 8)` bytes -- 12.8 MiB at a 2048-row step
|
||||
* on this model, where the ungated op's q_len band makes the same rows cost the figures
|
||||
* above. Fewer launches still pay here: one 2048-row launch takes about 2.16 ms a layer
|
||||
* against about 3.0 ms for eight 256-row ones, each of which is 256 one-wave workgroups -- two
|
||||
* waves a SIMD -- with its own tail. */
|
||||
int64_t qsa_gq_rows() const { return g.max_tok > qsa_rows() ? g.max_tok : qsa_rows(); }
|
||||
/* THE ROTATION'S PAIRING, a question the checkpoint cannot answer by inspection and that no
|
||||
* per-op check can reach, because both readings -- halves (NeoX, what HF's rotate_half does
|
||||
* over the partial rotary width) and adjacent pairs (GPT-J) -- are self-consistent and libref
|
||||
* shares whichever one the graph picks. Either answer is a DIFFERENT MODEL. "mrope" is what the
|
||||
* model does, and over one position component a token it is NeoX (rad_block_attn_gated.h).
|
||||
*
|
||||
* THE q|gate ORDER IS FIXED TOO. q is the FIRST half of each head's pair and the gate the
|
||||
* second, which is how vLLM chunks q_gate, and every consumer of the projection has to agree
|
||||
* on it: the unfused q norm reads column 0 of each head, the gate quantiser column head_dim,
|
||||
* and the fused prologue splits the pair the same way inside its kernel. A swap would be
|
||||
* arithmetically silent -- q_norm renormalises either half and the sigmoid accepts either --
|
||||
* so an order that only some of them followed would be fluent and wrong. */
|
||||
const char* mode = "mrope";
|
||||
|
||||
rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0;
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
LinearFP8 qg{}, kp{}, vp{}, o{};
|
||||
NormQuantFP8 nq_h{};
|
||||
|
||||
rad_op op_fused = 0; /* qk_norm_rope_gate, if it resolves */
|
||||
rad_op op_fused_kv = 0; /* ...with kv_store folded on, likewise */
|
||||
int64_t fused_rows = 0; /* ...and the widest T it is issued at */
|
||||
rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_gq = 0;
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_sig = 0, op_mul = 0; /* the bf16 gate, Geom::w_bf16 */
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
|
||||
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
|
||||
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
|
||||
* fold's two flags again, one boundary later, and they are separate for the same reason: a
|
||||
* block is declared without knowing what follows it. On EITHER wire -- the fused kernel
|
||||
* carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
|
||||
* about whether the collective has already been issued. */
|
||||
bool ar_out = false;
|
||||
/* ...and WHICH WIRES that consumer takes (ArOut, rad_fp8.h): the norm's by default, and a gated
|
||||
* residual's write says its own (HyperConn::ar_take). Set before declare; both sides then ask
|
||||
* ar_taken(g, T, ar_out, ar_out_take). */
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
/* `fold` says the PREVIOUS block left its delta in `w.h.x` for this norm to add; `add_out`
|
||||
* says the NEXT one will not, so this block issues the trailing add itself. See rad_fp8.h. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
|
||||
const Src& src, bool fold, bool add_out,
|
||||
int ar_in, bool ar_out_) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
const int64_t qg_dim = 2 * q_dim;
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
|
||||
*
|
||||
* A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
|
||||
* the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
|
||||
* RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
|
||||
* from a stream four times as wide, with a data-dependent mix the block has no way to compute,
|
||||
* and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
|
||||
* normed and quantised and declares no norm weight at all.
|
||||
*
|
||||
* `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
|
||||
* norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
|
||||
* an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
|
||||
ext_in = (src.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
if (g.w_bf16 && !w.gate) return RAD_E_INVAL;
|
||||
} else {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
}
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm));
|
||||
w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* One norm, one quantise, three consumers -- and one op, see rad_fp8.h's NormQuantFP8. */
|
||||
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));
|
||||
RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg));
|
||||
RAD_ARCH_TRY(kp.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k));
|
||||
RAD_ARCH_TRY(vp.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v));
|
||||
|
||||
/* THE FUSED PROLOGUE, AND IT IS A PROBE: the four ops below are declared either way and are
|
||||
* what runs when nothing serves this one. rad_block_attn_gated.h does not make the probe,
|
||||
* because the schema takes a PRECOMPUTED cos/sin table rather than `theta` and that block has
|
||||
* none; `rope_table` builds one here, once a step for every layer, and `w.cos_sin` is where
|
||||
* the model puts it. A block handed no table cannot ask for the fusion, which is what keeps a
|
||||
* plugin that does not build the table on the unfused path.
|
||||
*
|
||||
* NEOX ONLY. The fused kernel rotates NeoX pairs and has no `mode`, so the probe is made only
|
||||
* where mrope reduces to neox -- one position component a token, which is every text batch and
|
||||
* is argued in rad_block_attn_gated.h. A vision span would need the sections first.
|
||||
*
|
||||
* NO `gate_out`. `gate_quant_fp8` below already reads the gate at its column offset inside the
|
||||
* interleaved projection, so a contiguous copy would be q_dim of bf16 a layer written for
|
||||
* nothing. The operand is optional and this passes none.
|
||||
*
|
||||
* IT IS BIT-IDENTICAL TO THE FOUR, checked in r4d_selftest (`qk_norm_rope_gate ... matches the
|
||||
* unfused pair`) rather than argued: the kernel rounds its norm output to bf16 before rotating
|
||||
* because that is what a norm that stores a tensor and a rope that reads it back do. It
|
||||
* reproduces `r4d_rmsnorm_bf16`'s sum-of-squares fold element by element rather than folding
|
||||
* eight elements a lane, and r4d_selftest asserts byte equality. A merely RELATIVE bound is
|
||||
* not enough here: a fold order that agrees to a ULP and not to the last bit moves the
|
||||
* engine's transcript within a few dozen steps. */
|
||||
/* M-RoPE qualifies too: the table is filled at one component a token, which is exact on every
|
||||
* pass whose tokens' components agree, and the step takes the fused path only then. */
|
||||
const bool rope_neox = !std::strcmp(mode, "neox") || !std::strcmp(mode, "mrope") || g.rope_mc;
|
||||
fused_rows = qk_fuse_rows(g);
|
||||
if (w.cos_sin && rope_neox && fused_rows > 0)
|
||||
op_fused = rw(b, RAD_OP(b, "qk_norm_rope_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{w.qg, w.k, w.cos_sin}, {w.q, w.k});
|
||||
|
||||
op_q_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_q_norm)),
|
||||
{w.qg}, {w.q});
|
||||
op_k_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_k_norm)),
|
||||
{w.k}, {w.k});
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, mode),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, mode),
|
||||
{w.k}, {w.k});
|
||||
|
||||
/* Declared before kv_store because block_size is RAD_DERIVED and kv_store reads it back --
|
||||
* rad_block_attn_gated.h explains why the declared order differs from the issue order. */
|
||||
op_attn = RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", kv_block > 0 ? kv_block : (int64_t)RAD_KV_BLOCK),
|
||||
/* The sparse path issues one row a QUERY, so the bound the split-KV
|
||||
* scratch is sized from is the widest such launch and not the
|
||||
* sequence count -- see kQsaRows. */
|
||||
RAD_INT("max_seqs", (qsa_sel && qsa_sequ) ? qsa_rows()
|
||||
: g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS);
|
||||
/* THE QSA SELECTION IS A READ OF THIS OP AND HAS TO BE DECLARED AS ONE. The block table has
|
||||
* always been a raw batch pointer, so `attn_paged`'s read set was just the query -- and
|
||||
* `sel`/`seqused` are BUFFERS, whose lifetimes the Builder plans from exactly these lists. Left
|
||||
* out, their last use is `qsa_select` and the arena is free to lay another buffer over them;
|
||||
* anything written between the selection and the attention then arrives as a page id, and a
|
||||
* garbage page id is an address far outside the cache -- an aperture violation at the first
|
||||
* step whose plan happens to overlap them, which need not be a step that ran before. Spelled
|
||||
* with rad_op_reads rather than rw() because the list is conditional -- a layer with no
|
||||
* indexer has no such read.
|
||||
*
|
||||
* THE DECLARATION ORDER IS THE BUFFER PLAN, and this is one of the shapes that rule takes. */
|
||||
if (op_attn) {
|
||||
const rad_buf rd[3] = { w.q, qsa_sel, qsa_sequ };
|
||||
rad_op_reads(b, op_attn, rd, (qsa_sel && qsa_sequ) ? 3 : 1);
|
||||
rad_op_writes(b, op_attn, &w.attn.x, 1);
|
||||
}
|
||||
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
/* THE PROLOGUE AND THE CACHE STORE AS ONE LAUNCH, wherever the fused prologue is taken: a k
|
||||
* head's block already holds its token's rotated k, one element a lane, so it writes that and
|
||||
* the head's v into the cache too, byte-for-byte what kv_store would (the fold's row says why).
|
||||
* Declared here and not beside op_fused because the cache's block size is read back from the
|
||||
* attention op above. It resolves for an E4M3 and a bf16 cache alike. */
|
||||
if (op_fused)
|
||||
op_fused_kv = rw(b, RAD_OP(b, "qk_norm_rope_gate_kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, fused_rows),
|
||||
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("n_head_kv", g.n_head_kv), RAD_INT("rot", n_rot),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_WEIGHTS(w_q_norm, w_k_norm)),
|
||||
{w.qg, w.k, w.cos_sin, w.v}, {w.q, w.k});
|
||||
|
||||
/* THE OUTPUT GATE, THE MULTIPLY AND THE QUANTISER ARE ONE PASS. Unfused they are three --
|
||||
* sigmoid into a de-interleaved buffer, a multiply in place, then quant_act_fp8 -- and at
|
||||
* decode each is small enough that the dispatch gap between them is comparable to the work
|
||||
* itself, once per layer. THE ROW IS A (token, head) PAIR, which is what makes the fusion
|
||||
* expressible: at that shape the gate is a fixed stride inside the [q|gate] projection, the
|
||||
* attention output is contiguous, and the fp8 scale plane of [T * n_head, head_dim / 128] is
|
||||
* byte-for-byte the [T, q_dim / 128] the out projection reads. No separate gate buffer is
|
||||
* declared, because nothing reads one.
|
||||
*
|
||||
* The bf16 product is still written, because that is what the unfused pair left in `w.attn.x`
|
||||
* and the codes are taken over it -- see r4d_fused_quant_fp8.hip on why that is a requirement.
|
||||
* The codes are the int8 pair when the model feeds the out projection int8 (ActFP8::q8_fed),
|
||||
* and the same op writes them: the codes operand's dtype picks the quantiser.
|
||||
* PREFILL AND DECODE BOTH TAKE IT: unlike the gdn fold this one has no reduction across the
|
||||
* row, so there is no shape it cannot serve. */
|
||||
if (g.w_bf16) {
|
||||
op_sig = rw(b, RAD_OP(b, "sigmoid",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg}, {w.gate});
|
||||
op_mul = rw(b, RAD_OP(b, "mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x, w.gate}, {w.attn.x});
|
||||
if (!op_sig || !op_mul) return RAD_E_INVAL;
|
||||
} else
|
||||
op_gq = rw(b, RAD_OP(b, "gate_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head),
|
||||
RAD_INT("n", g.head_dim), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qg, w.attn.x}, {w.attn.cq(), w.attn.cs(), w.attn.x});
|
||||
|
||||
/* AND ON THE SPARSE PATH THE GATE RIDES IN THE ATTENTION'S OWN MERGE. There every launch is
|
||||
* one query row a (token, head) pair at q_len 1, and the split-KV merge that closes each row
|
||||
* holds exactly the 256 values the gate and the quantiser read next -- so the fused op merges,
|
||||
* gates, rounds and quantises the row where it is, byte-for-byte the pair (its row says how),
|
||||
* and the launch between them is gone. Declared only beside a selection: the dense path's
|
||||
* query rows are the band the prefill kernel serves as well, and that kernel has no merge. */
|
||||
if (op_attn && qsa_sel && qsa_sequ && !g.w_bf16) {
|
||||
op_attn_gq = RAD_OP(b, "attn_paged_gate_quant",
|
||||
RAD_PARAMS(RAD_INT("q_len", 1), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_INT("max_seqs", qsa_gq_rows()),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype),
|
||||
RAD_STR("kv_dtype", g.kv_dtype),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("act", "sigmoid")),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_attn_gq) {
|
||||
const rad_buf rd[4] = { w.q, qsa_sel, qsa_sequ, w.qg };
|
||||
const rad_buf wr[3] = { w.attn.x, w.attn.cq(), w.attn.cs() };
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_attn_gq, rd, 4));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_attn_gq, wr, 3));
|
||||
}
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
|
||||
/* Four launches or one. The fused kernel takes the [q|gate] projection WHOLE and splits it
|
||||
* itself -- so `w.qg` goes in as it stands and not as the column slice the unfused norm needs
|
||||
* -- and it rotates k in place, which is what the unfused pair does too. */
|
||||
/* THE FUSED PATH READS ONE COMPONENT A TOKEN, so a pass carrying media tokens -- whose
|
||||
* components differ -- takes the unfused pair with the whole [3, T] instead. */
|
||||
const bool fuse_ok = T <= fused_rows && !rope_mixed(batch);
|
||||
const bool fused_kv = op_fused_kv && fuse_ok;
|
||||
if (fused_kv) {
|
||||
RAD_ISSUE_N(c, op_fused_kv, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
brows(w.q, T), brows(w.k, T), RAD_NONE,
|
||||
brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
} else if (op_fused && fuse_ok) {
|
||||
RAD_ISSUE_N(c, op_fused, T,
|
||||
brows(w.qg, T), brows(w.k, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_W(w_q_norm), RAD_W(w_k_norm),
|
||||
brows(w.q, T), brows(w.k, T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_q_norm, T * g.n_head,
|
||||
bcol(w.qg, 0, g.head_dim, T), RAD_W(w_q_norm), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
|
||||
RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
if (!fused_kv)
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
/* ONE ROW A QUERY IS WHAT MAKES THE SPARSE PATH WORK AT PREFILL, and it needs no new kernel
|
||||
* for the same reason the decode path needed none: `attn_paged` indexes its block table and
|
||||
* its length by the ROW, and nothing says a row has to be a sequence. A chunk of T queries
|
||||
* issued as T rows of q_len 1, each with its own selection and its own `seqused`, is exactly
|
||||
* per-query sparse attention -- and at decode, where T is the sequence count, it is the same
|
||||
* issue it has always been.
|
||||
*
|
||||
* DENSE BELOW THE BOUND, because there the two are the same answer and dense is cheaper: it
|
||||
* reads each key once a query TILE where this reads a table a query. `max_ctx_len` is the
|
||||
* host-side bound the batch already carries, so the test costs nothing.
|
||||
*
|
||||
* CHUNKED AT max_seqs, and that is not tidiness. The decode kernel's split-KV scratch is
|
||||
* sized AT DECLARE from the `max_seqs` and `q_len` parameters -- max_seqs * q_len_max * heads
|
||||
* rows -- and handing it T rows past that is refused as RAD_E_SCRATCH at issue. max_seqs rows
|
||||
* of q_len 1 is strictly inside what q_len_max >= 1 already bought, so the bound holds
|
||||
* whatever the kernel's band turns out to be. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->max_q_len;
|
||||
const bool sparse = qsa_sel && qsa_sequ &&
|
||||
(T == batch->n_seq || qsa_exact_to <= 0 || reach > qsa_exact_to);
|
||||
const bool gated = sparse && op_attn_gq;
|
||||
if (gated) {
|
||||
const int64_t chunk = qsa_gq_rows();
|
||||
const int64_t qw = g.q_dim(), hd = g.head_dim;
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
RAD_ISSUE_N(c, op_attn_gq, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw),
|
||||
bcol_at(w.qg, off, g.n_head * 2 * hd, hd, hd, rows),
|
||||
brow_slice(w.attn.cq(), off, rows, qw),
|
||||
brow_slice(w.attn.cs(), off, rows, fp8_blocks(qw)));
|
||||
}
|
||||
} else if (sparse) {
|
||||
const int64_t chunk = qsa_rows();
|
||||
const int64_t qw = g.q_dim();
|
||||
for (int64_t off = 0; off < T; off += chunk) {
|
||||
const int64_t rows = (T - off) < chunk ? (T - off) : chunk;
|
||||
RAD_ISSUE_N(c, op_attn, 1,
|
||||
brow_slice(w.q, off, rows, qw),
|
||||
kv_cache(kv, layer),
|
||||
brow_slice(qsa_sel, off, rows, qsa_topk + 1),
|
||||
brow_slice(qsa_sequ, off, rows, 1),
|
||||
RAD_NONE, RAD_NONE, RAD_NONE,
|
||||
brow_slice(w.attn.x, off, rows, qw));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq,
|
||||
kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
/* cu_seqlens. The batch may be ragged -- one prefill chunk beside other
|
||||
* sequences one decode row each -- and without it the kernel has to
|
||||
* assume a single q_len for the whole step, which it cannot. */
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
}
|
||||
|
||||
if (op_sig) {
|
||||
/* The gate is the strided second half of each head's [q|gate] pair. */
|
||||
RAD_ISSUE_N(c, op_sig, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.gate, T));
|
||||
RAD_ISSUE(c, op_mul, brows(w.attn.x, T), brows(w.gate, T), brows(w.attn.x, T));
|
||||
} else if (!gated)
|
||||
RAD_ISSUE_N(c, op_gq, T * g.n_head,
|
||||
bcol(w.qg, g.head_dim, g.head_dim, T), brows(w.attn.x, T),
|
||||
brows(w.attn.cq(), T), brows(w.attn.cs(), T), brows(w.attn.x, T));
|
||||
|
||||
o.step(c, w.attn, w.h.x, T);
|
||||
if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_ATTN_GATED_FP8_H */
|
||||
@@ -0,0 +1,999 @@
|
||||
/* rad_block_dflash2.h -- the DFlash2 block-diffusion drafter, bf16.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* A SECOND, SMALLER TRANSFORMER that proposes a whole block of tokens in ONE forward pass. It is
|
||||
* the other drafter this engine serves, and it is a different shape of thing from the MTP head
|
||||
* beside it (rad_block_mtp_fp8.h):
|
||||
*
|
||||
* MTP depth d costs d CHAINED forwards. Round i+1 cannot start until round i has
|
||||
* produced a token, because the token is what it embeds.
|
||||
* DFlash2 depth d costs ONE forward over d+1 positions. The block is denoised together --
|
||||
* the anchor token plus d mask tokens go in, d+1 hidden states come out.
|
||||
*
|
||||
* That is why depth is nearly free here and expensive there, and it is why this file has no
|
||||
* `draft_pass`: there are no rounds. Published acceptance for this drafter is 4.10-5.46 against
|
||||
* MTP's 3.74-5.02 at 7 drafts.
|
||||
*
|
||||
* The price of proposing the positions together is that position l+1 was computed WITHOUT KNOWING
|
||||
* what position l would choose. The candidate selector is what puts that dependence back: each
|
||||
* position keeps the draft head's top K, a low-rank bilinear form scores the edge between
|
||||
* consecutive positions, and a greedy walk picks one path. `dflash_select` is that kernel.
|
||||
*
|
||||
* ============================== THE TWO PASSES ==============================
|
||||
*
|
||||
* THE CONTEXT PASS, one row a committed token. The drafter never runs its layers over the context
|
||||
* -- it reads the TARGET's hidden states instead, at five intermediate layers, and turns them
|
||||
* straight into its own K and V:
|
||||
*
|
||||
* c = fc(concat of the trunk's residual stream at layers 5, 19, 33, 47, 61) [n_taps*n_embd]
|
||||
* c = hidden_norm(c)
|
||||
* for each draft layer: k|v = kv_proj(c); k = k_norm(k) then rope; kv_store(k, v)
|
||||
*
|
||||
* The trunk's side of that -- the taps, and the `dflash_src` buffer they land in -- is in
|
||||
* qwen35_fp8.cpp. This file reads the buffer and never asks where the rows came from.
|
||||
*
|
||||
* THE QUERY PASS, one row a draft position, `block` = 1 + n_spec of them a sequence:
|
||||
*
|
||||
* x = embed(anchor, mask, mask, ...)
|
||||
* for each layer:
|
||||
* h = attn_norm(x); coef = attn_conv_proj(h)
|
||||
* h = dflash_conv(h, coef[0:taps*NG], attn_conv_base[0]) <- prepare
|
||||
* h = o_proj(attention(q_proj(h), kv_proj(h))) <- non-causal, windowed
|
||||
* h = dflash_conv(h, coef[taps*NG:], attn_conv_base[1]); x += h <- finish
|
||||
* h = ffn_norm(x); coef = ffn_conv_proj(h)
|
||||
* h = dflash_conv(h, coef[0:taps*NG], ffn_conv_base[0])
|
||||
* h = down(silu_mul(gate_up(h)))
|
||||
* h = dflash_conv(h, coef[taps*NG:], ffn_conv_base[1]); x += h
|
||||
* x = norm(x)
|
||||
*
|
||||
* and then, over the MASK rows of each sequence's block -- offsets 1..block-1, NOT 0..steps-1.
|
||||
* The anchor at offset 0 is a token the target has already chosen, so its row predicts nothing and
|
||||
* is there to condition the rest; each mask row predicts the token AT ITS OWN POSITION:
|
||||
*
|
||||
* cand, unary = top_k(draft_head(x)) the candidates and their logits
|
||||
* hp = hidden_projection(x) the selector's query, rank 256
|
||||
* tokens = dflash_select(cand, unary, hp, anchor, predecessor, successor)
|
||||
*
|
||||
* ============================== WHAT IS SHARED WITH THE TARGET ==============================
|
||||
*
|
||||
* The embedding table and the lm_head, both. The checkpoint ships neither -- 81 tensors, no
|
||||
* `embed_tokens` and no `lm_head` -- so a drafter without a target is not a model. `mask_token_id`
|
||||
* is an ordinary id in the target's vocabulary (248070 here), which is why there is no separate
|
||||
* mask embedding to load.
|
||||
*
|
||||
* The head reads the 2-BIT copy of the lm_head, exactly as the MTP head does and for exactly the
|
||||
* reason rad_block_mtp_fp8.h gives at op_dlogits: a draft is a proposal, the target verifies every
|
||||
* one of them with its own untouched head, and speculative decoding is distribution-preserving --
|
||||
* so a coarser draft costs acceptance and cannot change a token the model emits. Here it also buys
|
||||
* something MTP does not need: the head stays a SINGLE-RANK computation, so the candidate ids are
|
||||
* global without an all-gather and the selector's codebooks can be indexed directly.
|
||||
*
|
||||
* ============================== THE NORMS ARE PLAIN ==============================
|
||||
*
|
||||
* `w`, not `1 + w`, unlike every norm in the trunk this drafter is bolted to. vLLM says so by
|
||||
* using the ordinary RMSNorm rather than the family's GemmaRMSNorm, and the checkpoint agrees:
|
||||
* hidden_norm sits at 0.11..1.24 (mean 0.82), input_layernorm at 0.05..1.70, k_norm at 0.32..2.53
|
||||
* and the final norm at 2.45..5.25. All positive, all centred near one -- which is a plain gain
|
||||
* and is not what a `1 + w` tensor looks like. So `Geom::wadd` and `wadd_qk` are ZERO here while
|
||||
* the trunk's are one, and the two geometries are separate structs for this reason among others.
|
||||
*
|
||||
* ============================== SHARDING ==============================
|
||||
*
|
||||
* The layers shard the way any transformer's do: q/kv and gate_up by row, o and down by column
|
||||
* with an all-reduce. Ten collectives a draft pass, each 5120 * block * 2 bytes -- 80 KiB at the
|
||||
* shipped block of 8 -- which is below the lossy wire's floor and is served exactly.
|
||||
*
|
||||
* THREE THINGS ARE REPLICATED AND EACH IS A DECISION:
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB. It could be COLUMN-sharded, since its input
|
||||
* is the replicated residual stream and its output would then be a partial sum:
|
||||
* 131 MiB a rank and half the read bytes on the context pass's widest GEMM. Not
|
||||
* done, because it puts an all-reduce on the PREFILL path to save a small
|
||||
* fraction of it, and the real fix for the context pass's cost is not to run it
|
||||
* over the whole prompt at all (see below).
|
||||
* conv weights the projection and the base kernel, 26 MiB a layer. The convolution is over
|
||||
* the whole replicated hidden row and every rank needs every coefficient; a row
|
||||
* shard would give each rank a fraction of the groups.
|
||||
* the codebooks [n_vocab, 256] each, 127 MiB each. They are gathered by GLOBAL token id and
|
||||
* the ids come out of a whole-vocabulary draft head, so a vocabulary shard would
|
||||
* let a rank score only the candidates that happened to land in its own slice.
|
||||
* The gather is 128 rows a pass, so the bytes READ are nothing; it is the
|
||||
* residency that costs.
|
||||
*
|
||||
* ============================== THE CONTEXT PASS IS THE EXPENSIVE HALF ==============================
|
||||
*
|
||||
* In bytes: `fc` is 262 MiB and the five KV projections read 3.4 GB over a 2048-token prefill
|
||||
* chunk, which is a real fraction of what the chunk costs.
|
||||
*
|
||||
* THE FIX IS NOT A FASTER GEMM. The drafter's attention has a 2048-token window, so a context
|
||||
* position more than 2048 before the query is never read: for a prompt of any real length, all but
|
||||
* the last 2048 rows of the context pass are computed and thrown away. The scheduler can simply
|
||||
* not run it over them. That is scheduler work and it is noted here rather than done here.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DFLASH2_H
|
||||
#define RAD_BLOCK_DFLASH2_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* A row slice of a WEIGHT, the same thing brow_slice() is for a buffer. The conv's base kernel is
|
||||
* [2, taps, n_embd] and the two sides are the prepare tap set and the finish tap set; there is one
|
||||
* checkpoint tensor and the op takes one side at a time. */
|
||||
inline RadOperand wrow_slice(rad_weight h, int64_t first, int64_t n, int64_t pitch) {
|
||||
RadOperand o = RAD_W(h);
|
||||
o.offset = first * pitch;
|
||||
o.rows = n;
|
||||
return o;
|
||||
}
|
||||
|
||||
struct Dflash2 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
/* Everything the drafter's own config.json says that its geometry does not. Read by the
|
||||
* plugin from `draft.*` metadata keys and handed in whole, so this file reads no environment
|
||||
* and no container. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows a sequence: the anchor plus n_spec mask tokens */
|
||||
int64_t taps = 2; /* the convolution's */
|
||||
int64_t group = 16;
|
||||
int64_t sel_rank = 256; /* the codebooks' width */
|
||||
int64_t sel_topk = 16; /* candidates kept per position */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 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 -- one coefficient set for `prepare`
|
||||
* and one for `finish` -- and `dflash_conv` reads a slice of it at the FULL row pitch. */
|
||||
int64_t coef_dim(int64_t n_embd) const { return 2 * taps * ng(n_embd); }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* 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 */
|
||||
/* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
|
||||
* halves are written by one projection and read by one kv_store, so fusing them is the
|
||||
* obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
|
||||
* takes one row pitch. K inside a fused row is `head_dim` apart within a token and
|
||||
* `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
|
||||
* between-tokens stride normalises every eighth head against the wrong numbers. libr4d
|
||||
* refuses that operand (libr4d/r4d_model.cpp, rows_pitch), and the drafter gives it rows
|
||||
* that are what they claim to be. The trunk's attention block splits
|
||||
* k and v for the same reason -- see rad_block_attn_gated.h. */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] ONE layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] ONE layer's V, reused across layers */
|
||||
/* the query pass */
|
||||
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
|
||||
rad_buf h = 0; /* [qrows, n_embd] normed input, o/down output, and the final norm */
|
||||
rad_buf h2 = 0; /* [qrows, n_embd] the convolution's output -- it may not alias x */
|
||||
rad_buf coef = 0; /* [qrows, coef_dim] */
|
||||
rad_buf q = 0; /* [qrows, q_dim] */
|
||||
rad_buf k = 0; /* [qrows, kv_dim] -- two buffers, and `ck` above says why */
|
||||
rad_buf v = 0; /* [qrows, kv_dim] */
|
||||
rad_buf attn = 0; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0;/* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [qrows, n_ff] */
|
||||
/* THE FP8 TWINS OF THE FOUR ACTIVATIONS A LINEAR READS. `quant_act_fp8` writes them and
|
||||
* the six `gemm_nt_q` linears read them; nothing else touches them, and the bf16 buffer
|
||||
* beside each stays the thing the rest of the graph reads and writes.
|
||||
*
|
||||
* ONE PAIR PER ACTIVATION, NOT PER LINEAR. q and k|v both read h2, so quantising it once
|
||||
* is the difference between two launches a layer and three -- the same argument rad_fp8.h
|
||||
* makes for keeping QuantFP8 a separate struct from LinearFP8. h2 is quantised twice a
|
||||
* layer all the same, because the convolution rewrites it between the attention half and
|
||||
* the feed-forward half. */
|
||||
rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] e4m3 | [.., /128] f32 */
|
||||
rad_buf cq = 0, cs = 0; /* [max_tok, n_embd] */
|
||||
rad_buf h2q = 0, h2s = 0; /* [qrows, n_embd] */
|
||||
rad_buf atq = 0, ats = 0; /* [qrows, q_dim] */
|
||||
rad_buf ffq = 0, ffs = 0; /* [qrows, n_ff] */
|
||||
/* the head and the selector, at one row per DRAFT POSITION (block - 1 a sequence) */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
|
||||
rad_buf hp = 0; /* [srows, sel_rank] hidden_projection of them */
|
||||
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
|
||||
rad_buf ds = 0; /* [srows, 1] f32 one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/128, pad] f32 GROUP-major, quant_act_i8's asum plane */
|
||||
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
|
||||
rad_buf cand = 0; /* [srows, sel_topk] i32 candidate token ids, global */
|
||||
rad_buf unary = 0; /* [srows, sel_topk] f32 and their logits */
|
||||
/* The vocab-parallel pair, declared only when head_sharded(g). Both are f32 (int32 id,
|
||||
* float value) pairs: this rank's top-R, and the all-gathered world_size * R of them. */
|
||||
rad_buf dpair = 0; /* [srows, sel_topk, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * sel_topk, 2] f32 */
|
||||
rad_buf tokens = 0; /* [max_seqs, steps] i32 THE DRAFT -- the engine reads this by name */
|
||||
};
|
||||
|
||||
/* WHETHER THE 2-BIT DRAFT HEAD IS VOCAB-SHARDED. The test itself is rad_arch.h's
|
||||
* `vocab_head_sharded` -- shared, because the second block-diffusion drafter in this library
|
||||
* asks it too and both the op and the buffer under it have to agree. These two names stay so
|
||||
* that whoever declares Dflash2's buffers can ask the BLOCK rather than re-derive the rule.
|
||||
*
|
||||
* Sharding halves the widest read on the draft path -- 341 MiB of codes and scales at 248320
|
||||
* rows when it is replicated -- at the price of one all_gather of R pairs a row. At 248320
|
||||
* over two ranks the shard is 124160, which is 7760 whole 16-row blocks. */
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
/* Rows of the draft head, and therefore the width of `dlog`, on THIS rank. */
|
||||
static int64_t head_rows(const Geom& g) { return vocab_head_rows(g); }
|
||||
|
||||
Geom g{}; /* the DRAFTER's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, so the KV group's layer_slot lookup finds these five */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* model-scope weights.
|
||||
*
|
||||
* THE SIX LINEARS ARE FP8 AND THE CHECKPOINT IS BF16. rad_fp8.h's DenseFP8 declares each as
|
||||
* block fp8 and the recipe makes it so -- and the reason is bytes: the drafter is read WHOLE on
|
||||
* every decode step, which makes it one of the largest single items in the decode budget
|
||||
* after the trunk's own GEMMs.
|
||||
* Nothing it computes can change an emitted token, because every draft is verified against the
|
||||
* trunk exactly; the only thing quantising it can move is acceptance. */
|
||||
DenseFP8 w_fc{};
|
||||
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 */
|
||||
|
||||
/* per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
/* K AND V ARE TWO WEIGHTS, and the fp8 layout hook is why. One fused [2*kv_dim, n_embd]
|
||||
* tensor issued a half at a time through wrow_slice would cost a launch and no bytes -- and a
|
||||
* block-scaled weight cannot be used that way. The layout of an operand is a function of the
|
||||
* OP's N, and this op's N is kv_dim because it computes one half; the hook would be handed a
|
||||
* [2*kv_dim/128][K/128] plane for a [kv_dim, K] op and refuse it. Two weights make the op's N
|
||||
* and the planes' rows the same number again, shard independently at kv_dim, and issue the
|
||||
* same two launches. */
|
||||
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
|
||||
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
rad_weight w_acp[MAX_LAYERS] = {}, w_acb[MAX_LAYERS] = {};
|
||||
rad_weight w_fcp[MAX_LAYERS] = {}, w_fcb[MAX_LAYERS] = {};
|
||||
|
||||
/* context-pass ops */
|
||||
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
|
||||
/* THE ACTIVATION QUANTISERS, one per activation that feeds a linear. Weightless and shape-only,
|
||||
* so one declaration each serves every layer -- the per-layer ops above are per-layer only
|
||||
* because a weight's prefetch interval comes from the op that declares it. */
|
||||
rad_op op_qsrc = 0, op_qc = 0; /* the context pass's two */
|
||||
rad_op op_qh2 = 0, op_qat = 0, op_qff = 0; /* the query pass's three */
|
||||
|
||||
/* query-pass ops. The weightless ones are declared once and issued per layer: an op's declared
|
||||
* read and write sets are what the buffer planner reads, and they are the same every layer. */
|
||||
rad_op op_embed = 0, op_embed_ar = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
|
||||
rad_op op_acoef[MAX_LAYERS] = {}, op_fcoef[MAX_LAYERS] = {};
|
||||
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] = {};
|
||||
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;
|
||||
|
||||
/* head and selector */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const Wire& wire);
|
||||
/* The context pass, one row a committed token. `batch` carries those rows and the draft KV
|
||||
* group's slot mapping; nothing about the query block is read. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass and the selector, one call, `block` rows a sequence. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
private:
|
||||
int64_t q_dim() const { return g.n_head * g.head_dim; }
|
||||
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
int base_layer, rad_kvgroup group, rad_weight tok_embd,
|
||||
const char* ck, const char* ck_lm, const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !ck_lm || !w_tok) return RAD_E_INVAL;
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: dflash2 has %lld layers; this block carries at most %d\n",
|
||||
(long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.sel_rank <= 0 || cfg.sel_topk <= 0)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t CD = cfg.coef_dim(g.n_embd);
|
||||
const int64_t qd = q_dim(), kvd = kv_dim();
|
||||
|
||||
crows = g.max_tok;
|
||||
qrows = g.max_seqs * cfg.block;
|
||||
if (qrows > g.max_tok) qrows = g.max_tok;
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
nm.ckpt("%s.candidate_selector.hidden_projection.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_pred"),
|
||||
nm.ckpt("%s.candidate_selector.predecessor_codebook", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_succ"),
|
||||
nm.ckpt("%s.candidate_selector.successor_codebook", ck)));
|
||||
|
||||
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_selp = decl_w(b, nm.f("dflash.sel_proj.weight"), RAD_BF16, {cfg.sel_rank, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_pred = decl_w(b, nm.f("dflash.sel_pred"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_succ = decl_w(b, nm.f("dflash.sel_succ"), RAD_BF16, {g.n_vocab_all, cfg.sel_rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* THE 2-BIT DRAFT HEAD. The same declaration the MTP head makes, for the same reasons, argued
|
||||
* at length in rad_block_mtp_fp8.h: `dflash.draft_head.weight` is the target's lm_head under a
|
||||
* name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16 scale and a
|
||||
* u8 zero a group of 128) -- one checkpoint tensor, two logical weights. The GEMM takes the
|
||||
* codes as one operand and the scale and zero planes, interleaved by its relayout, as the
|
||||
* other.
|
||||
*
|
||||
* IT IS SHARDED, AND THE MERGE IS WHAT MAKES THAT SAFE. The draft path never goes through the
|
||||
* sampler, so its argmax is a `row_topk` over one rank's plane -- and a sharded plane on its
|
||||
* own would let each rank propose only from its own half, while the selector's codebooks are
|
||||
* gathered by GLOBAL token id and would then see only the candidates that landed locally. The
|
||||
* merge runs BEFORE the selector: each rank's top-R comes back as global ids, an all_gather
|
||||
* moves R pairs a row, and `row_topk_merge` reduces them to the same global top-R an unsharded
|
||||
* head would have found -- exactly, ties included (docs/OPS.md). Both ranks then hold the same
|
||||
* candidate set and the codebooks are replicated, so everything downstream is unchanged.
|
||||
*
|
||||
* What it buys is the widest read on the draft path halved -- 341 MiB of codes and scales at
|
||||
* the whole vocabulary -- and that much device memory given back per rank. What it costs is
|
||||
* one all_gather of `world * R` pairs a row, which at R = 16 is 2 KiB: the link's latency and
|
||||
* essentially no bytes. */
|
||||
enum { DF_W2_GROUP = 128 };
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_conv_proj.weight", i),
|
||||
nm.ckpt("%s.layers.%d.attention_conv.kernel_projection.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_conv_base", i),
|
||||
nm.ckpt("%s.layers.%d.attention_conv.base_kernel", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_conv_proj.weight", i),
|
||||
nm.ckpt("%s.layers.%d.mlp_conv.kernel_projection.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_conv_base", i),
|
||||
nm.ckpt("%s.layers.%d.mlp_conv.base_kernel", ck, i)));
|
||||
|
||||
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
|
||||
/* K, V AND Q ARE THREE WEIGHTS, which is not the fusion every other attention block in
|
||||
* this library makes. Q is separate because of the context pass: it needs k and v over the
|
||||
* trunk's projected hidden state and has no use for q at all, so a fused qkv would make it
|
||||
* compute and discard a q_dim-wide GEMM per layer per context token. K and V are separate
|
||||
* because a block-scaled weight's layout follows its op's N, and both passes take one of
|
||||
* them at a time -- see the note beside the declarations. */
|
||||
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
|
||||
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(first_layer + i));
|
||||
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i),
|
||||
2 * g.n_ff, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
|
||||
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
|
||||
{ g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(first_layer + i),
|
||||
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
|
||||
w_acp[i] = decl_w(b, nm.f("dflash.blk.%d.attn_conv_proj.weight", i), RAD_BF16,
|
||||
{CD, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
w_acb[i] = decl_w(b, nm.f("dflash.blk.%d.attn_conv_base", i), RAD_BF16,
|
||||
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
w_fcp[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_proj.weight", i), RAD_BF16,
|
||||
{CD, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
w_fcb[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_conv_base", i), RAD_BF16,
|
||||
{2, cfg.taps, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(first_layer + i));
|
||||
|
||||
}
|
||||
|
||||
/* NON-CAUSAL, WINDOWED. The block is denoised as a whole, so every query row sees every other
|
||||
* row of its own block as well as the context -- `causal` 0 is the drafter's own config
|
||||
* (`is_causal: false`) and not a default. The window is the checkpoint's `sliding_window`, and
|
||||
* it is the reason the context pass has a bounded amount of real work in it.
|
||||
*
|
||||
* DECLARED FIRST, before either kv_store, even though it runs long after both. `block_size` is
|
||||
* RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
|
||||
* anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for the
|
||||
* two stores, which need it as a parameter. Ask before the attention op is declared and the
|
||||
* answer is zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
/* EVERY LINEAR HERE IS `fp8a8`, and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. The weights are E4M3 with a 128x128 scale plane (rad_fp8.h's DenseFP8 says
|
||||
* why), and there is no `fp8a16` band anywhere in this block: that kernel is M <= 1, and
|
||||
* neither pass here ever runs at one row -- a context pass is a committed chunk and a query
|
||||
* pass is `block` rows by construction.
|
||||
*
|
||||
* AND NOTHING HERE IS ROW-SLICED. The fp8a8 pair covers every M (narrow to 16, tiled above),
|
||||
* so a context pass over a 2048-token prefill chunk is one launch a layer rather than one per
|
||||
* 64 rows.
|
||||
*
|
||||
* The convolutions' coefficient projections and the selector's hidden projection are still
|
||||
* bf16, and they are not sliced either: libr4d's bf16 GEMM row is C_LE("M", 65536), and all
|
||||
* three of these carry K = n_embd, a multiple of 16, so the wide row serves them whole. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
|
||||
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
|
||||
* layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* TWO OPS OF THE SAME SHAPE, one per weight. An op's declared weight list is what gives a
|
||||
* weight its prefetch interval and its residency class, so two weights want two ops even
|
||||
* where one would issue both. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ck});
|
||||
}
|
||||
/* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck}, {w.ck});
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck, w.cv}, {});
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.x});
|
||||
/* The trunk's embedding is vocab-sharded, so this gather is partial and takes the same exact
|
||||
* reduction. It is on the DRAFT path, which runs once a step ahead of the trunk: a second
|
||||
* small collective. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x}, {w.x});
|
||||
/* The query pass's three quantisers, declared once and issued per layer -- weightless ops with
|
||||
* the same shape every layer, exactly like the ropes and the residual add below. h2 is
|
||||
* quantised TWICE a layer because the convolution rewrites it between the two halves; attn and
|
||||
* ffn once each. */
|
||||
op_qh2 = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h2}, {w.h2q, w.h2s});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_acoef[i] = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", CD),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h2q, w.h2s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h2q, w.h2s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h2q, w.h2s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.q});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.atq, w.ats}, {w.h});
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_fcoef[i] = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", CD),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcp[i])),
|
||||
{w.h}, {w.coef});
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h2q, w.h2s}, {w.gate_up});
|
||||
/* THE SAME FOLD THE TRUNK'S MLP HAS, over the same weights and into the same activation;
|
||||
* rad_block_mlp_fp8.h declares it beside the pair for the same reason. Unfused, a layer
|
||||
* runs gate_up -> silu_mul -> quant, which is two extra launches and two extra passes over
|
||||
* the [T, n_ff] product. The gated kernel is also the faster of the two on the SAME shape,
|
||||
* because the fold saves the bf16 round trip.
|
||||
*
|
||||
* NOT RAD_ARCH_TRY: a kernel set without the row is the ordinary case and the pair below
|
||||
* still runs. `gated_rows` is the band it was declared over and the issue site checks it,
|
||||
* because M > 64 is a refusal in the kernel and not a slower path. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0) {
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h2q, w.h2s}, {w.ffq, w.ffs});
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
|
||||
/* The convolutions. `block_size` is the QUERY BLOCK -- the mask that kills the shifted tap at
|
||||
* the first row of each block is what keeps one sequence's block from convolving with the
|
||||
* previous sequence's, so it is the batch's per-sequence row count and not a tuning number.
|
||||
*
|
||||
* ONE OP PER (LAYER, CONVOLUTION) even though every one of them is the same shape, because the
|
||||
* base kernel is a WEIGHT and an op's declared weight list is what gives a weight its prefetch
|
||||
* interval and its residency class. A single shared declaration would leave ten weights that
|
||||
* no op admits to using. Each is issued twice -- `prepare` and `finish` -- against the two
|
||||
* halves of one [2, taps, n_embd] tensor. */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", cfg.block),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
op_fconv[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", cfg.block),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k}, {w.k});
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h2}, {w.x});
|
||||
op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the selector
|
||||
*
|
||||
* THE MASK ROWS, offsets 1..block-1 of each sequence's block. Offset 0 is the ANCHOR -- the
|
||||
* token the target has already chosen -- and its row predicts nothing: it is there so the mask
|
||||
* rows have something to attend to. Each mask row predicts the token at ITS OWN position, so
|
||||
* the head runs over `steps` rows a sequence and not `block`. Getting this off by one is the
|
||||
* kind of mistake that costs nothing visible: the drafts are simply wrong, acceptance
|
||||
* collapses, and the model's own output stays exactly correct.
|
||||
*
|
||||
* The gather is what makes those rows contiguous, and it is also what fixes the head's row
|
||||
* numbering at s * steps + l -- which is the numbering `dflash_select` reads. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.sel_h});
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
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});
|
||||
/* 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, so that graph is the one it always was -- an optional parameter present with
|
||||
* the value 0 is not the same declaration as an absent one. */
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.sel_topk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride, the same reason the sampler's own
|
||||
* candidate gather carries `row`. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.sel_topk * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", cfg.sel_topk * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.sel_topk),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dgath}, {w.cand, w.unary});
|
||||
}
|
||||
op_hp = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", cfg.sel_rank),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_selp)),
|
||||
{w.sel_h}, {w.hp});
|
||||
/* `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
|
||||
* carries `block` ids a sequence and the anchor is the first of them. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
|
||||
|
||||
/* NOT SLICED. A context pass is one row a committed token, so it is as wide as the prefill
|
||||
* chunk; the fp8a8 pair covers every M, so each op here is one launch and not one per 64
|
||||
* rows. */
|
||||
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, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
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, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
|
||||
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
|
||||
/* ---- 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));
|
||||
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));
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
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, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv,
|
||||
brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
/* BEFORE the closing convolution, not after. The convolution is linear in its input and
|
||||
* its coefficients come from the replicated pre-attention norm, so either order is the
|
||||
* same arithmetic -- and reducing first keeps the residual stream's contract ("what the
|
||||
* ranks add to x has already been agreed") in one place. */
|
||||
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));
|
||||
|
||||
/* ---- 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));
|
||||
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));
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gug[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h2q, T), brows(w.h2s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, RAD_NONE);
|
||||
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));
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
/* The rows that predict something: `steps` of every sequence's `block`. The scheduler names
|
||||
* them through out_ids, the same field the trunk's own logits gather reads. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
|
||||
|
||||
/* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
|
||||
* whole: there is no row slice of it that means anything. */
|
||||
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 and is absent here; an absent optional
|
||||
* operand is a null tensor in a full-length list, not a shorter list. */
|
||||
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);
|
||||
/* RAD_NONE is the `pairs` slot: operands are POSITIONAL, so an optional one that the graph
|
||||
* does not use is still passed, absent. Omitting it is a miscount and the engine refuses the
|
||||
* op rather than guessing which of the four was left out.
|
||||
*
|
||||
* SHARDED, the top-R over this rank's plane is not the answer -- it is this rank's CANDIDATES,
|
||||
* and `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
|
||||
* costs nothing (they are the same R entries the pairs plane holds) and keeps one issue site
|
||||
* for both paths. */
|
||||
if (op_dmerge) {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_DFLASH2_H */
|
||||
@@ -0,0 +1,926 @@
|
||||
/* rad_block_dspark.h -- the DSpark block-diffusion drafter, fp8 weights over a bf16 checkpoint.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* The THIRD drafter this engine serves, and the second block-diffusion one. It is
|
||||
* `openbmb/MiniCPM5-2B-DSpark`: five plain Qwen3 attention layers that propose a whole block of
|
||||
* tokens in ONE forward pass, conditioned on the target trunk's residual stream at five
|
||||
* intermediate layers. Published acceptance length 5.52 at T = 0 (math 6.05 / code 6.11 /
|
||||
* general 4.16) against MTP's 3.74-5.02.
|
||||
*
|
||||
* IT IS NOT rad_block_dflash2.h, and the name is the trap. DSpark subclasses SpecForge's
|
||||
* `DFlashDraftModel`, which is PLAIN QWEN3 ATTENTION LAYERS; this library's `Dflash2` is the
|
||||
* conv-based drafter (`dflash_conv`, `attn_conv_base`, `sel_rank`/`sel_topk`) from a different
|
||||
* checkpoint of the same family. Same lineage, same word in the name, different architecture --
|
||||
* and the checkpoint settles it: 5 layers of q/k/v/o + q_norm/k_norm + gate/up/down and not one
|
||||
* conv or selection tensor. What IS taken from that file is its shape (Config / Wire / declare /
|
||||
* context / step), its two rules, and -- see THE MARKOV HEAD below -- its selector.
|
||||
*
|
||||
* ============================== THE FORWARD PASS, PINNED ==============================
|
||||
*
|
||||
* The reference is NOT in the published repo: `config.json` says `auto_map: dspark.DSparkDraftModel`
|
||||
* and the repo holds only config / README / safetensors. `RadixArk/Qwen3.8-27B-DSpark` ships
|
||||
* `dspark.py` and `dflash.py`, and that pair is the spec this block implements. The composition is
|
||||
* not recoverable from the tensor list alone, so it is written out here:
|
||||
*
|
||||
* target_hidden = hidden_norm(fc(concat of the trunk's residual stream after layers
|
||||
* 1, 10, 20, 30, 39)) [n_taps * n_embd] -> [n_embd]
|
||||
* h = target.embed_tokens([anchor, MASK, MASK, ...]) `block` noise rows
|
||||
* per layer (x5):
|
||||
* h_n = input_layernorm(h)
|
||||
* q = q_norm(q_proj(h_n)) Q FROM THE NOISE ROWS ONLY
|
||||
* k = k_norm(concat(k_proj(target_hidden), k_proj(h_n))) context first, then noise
|
||||
* v = concat(v_proj(target_hidden), v_proj(h_n))
|
||||
* rope(q, k); attention is NON-CAUSAL, mask None at inference
|
||||
* h += o_proj(attn); h += mlp(post_attention_layernorm(h))
|
||||
* logits = target.lm_head(norm(h)) + markov_w2 @ markov_w1[prev_token]
|
||||
*
|
||||
* `fc` THEN `hidden_norm`, in that order, and `target_hidden` is computed ONCE and fed to EVERY
|
||||
* layer, which projects it with its OWN k_proj and v_proj. The drafter ships no embedding table
|
||||
* and no lm_head; it reads the target's, which is why a vocabulary that disagrees is not a drafter
|
||||
* for this target at all.
|
||||
*
|
||||
* ============================== THE DUAL-SOURCE K/V IS AN ORDINARY KV CACHE ==============================
|
||||
*
|
||||
* `concat(proj(target_hidden), proj(noise))` needs no new kernel and no fused-operand games. The
|
||||
* reference's own cache says why: `past_key_values.update` appends the context rows and the noise
|
||||
* rows, the block attends over the whole thing, and then `crop(start)` throws the noise away. That
|
||||
* is a paged KV group with the context written per COMMITTED TOKEN and the noise rows written into
|
||||
* slots past `seqused` -- which the next context pass overwrites, so the crop is free.
|
||||
*
|
||||
* So the split is the same two passes Dflash2 has, for the same reason:
|
||||
*
|
||||
* THE CONTEXT PASS, one row a committed token. It runs the five k/v projections over the
|
||||
* projected trunk taps and stores them. The drafter's own layers never run over the context.
|
||||
*
|
||||
* THE QUERY PASS, `block` rows a sequence, over the drafter's five layers, attending to the
|
||||
* context rows AND to each other.
|
||||
*
|
||||
* AND THE PER-HEAD NORM OVER THE CONCAT IS THE SAME NUMBER EITHER WAY. `k_norm` is an RMS norm
|
||||
* over each head's own `head_dim` row, so norming the context half in one pass and the noise half
|
||||
* in the other is bit-for-bit what norming the concatenation would have been. Nothing about the
|
||||
* split is an approximation.
|
||||
*
|
||||
* `attn_paged` ALREADY TAKES `causal`, so `causal = 0` serves the non-causal block: every noise
|
||||
* row sees every other row of its own block as well as the whole context. This drafter is
|
||||
* 16 head / 2 kv / head_dim 128 = GQA 8, the same shape as its target, so the attention and the
|
||||
* norm/rope rows the trunk resolves serve it unchanged.
|
||||
*
|
||||
* ============================== THE ROW ALIGNMENT, WHICH IS THE WHOLE GAME ==============================
|
||||
*
|
||||
* `block_size` IS THE NUMBER OF NOISE ROWS AND ALSO THE NUMBER OF DRAFTS. Seven rows in, seven
|
||||
* tokens out, verify width eight. The noise stream is [anchor, MASK x (block-1)] and ROW j
|
||||
* PREDICTS THE TOKEN AT POSITION start + j + 1 -- the ordinary next-token relation, anchor row
|
||||
* included, which is why `steps() == block` here and `steps() == block - 1` in Dflash2.
|
||||
*
|
||||
* THAT IS THE OPPOSITE CONVENTION TO Dflash2 AND IT IS INVISIBLE IF YOU GET IT WRONG. Dflash2's
|
||||
* anchor row predicts nothing and each MASK row predicts the token at ITS OWN position; DSpark's
|
||||
* anchor row is a real prediction and no row is wasted. Both run, both produce `depth` tokens, and
|
||||
* the model's own output stays exactly correct either way because every draft is verified against
|
||||
* the trunk -- what happens instead is that the proposals are shifted one position and acceptance
|
||||
* falls to roughly chance. The core stages the block against `RadDrafterDecl::block` and runs the
|
||||
* head over the LAST `depth` rows, which is the one rule both conventions reduce to; rad_builder.h
|
||||
* argues it, and this file is the reason that field exists.
|
||||
*
|
||||
* ============================== THE MARKOV HEAD IS Dflash2'S SELECTOR ==============================
|
||||
*
|
||||
* DSpark adds a rank-256 learned bigram bias to the draft logits:
|
||||
*
|
||||
* logits[l] += markov_w2 @ markov_w1[prev(l)] prev(0) = the anchor,
|
||||
* prev(l) = the token chosen at l - 1
|
||||
*
|
||||
* which is SERIAL in l for exactly the reason a block-diffusion drafter needs a selector at all:
|
||||
* the positions were computed together and the bias at l depends on the token chosen at l - 1.
|
||||
* Written literally it is seven full-vocabulary [rank, n_vocab] GEMMs with an argmax between each
|
||||
* -- 66 MiB of `markov_w2` read seven times a step to use seven of its rows.
|
||||
*
|
||||
* `dflash_select` ALREADY COMPUTES THIS. Its edge score is
|
||||
*
|
||||
* unary[l][c] + sum_r pred[prev][r] * hp[l][r] * succ[cand[l][c]][r]
|
||||
*
|
||||
* over the base head's top K candidates, with the predecessor read after the previous step's
|
||||
* argmax inside one workgroup and no launch between steps. Set `hp` ABSENT -- it is optional, and
|
||||
* absent it is ones -- and the trilinear form drops to the plain bigram
|
||||
* `<pred[prev], succ[cand]>`; pass `markov_w1` as `pred` and `markov_w2` as `succ` and the walk IS
|
||||
* the Markov head, greedily decoded. The codebook gather is K * rank * 2 bytes a position, 8 KiB
|
||||
* at K = 16, against 466 MiB for the literal form.
|
||||
*
|
||||
* WHAT IS APPROXIMATED IS THE CANDIDATE SET AND NOTHING ELSE: the bias can only re-rank the base
|
||||
* head's top K, where the reference could promote any of 130560. That is the same trade the 2-bit
|
||||
* draft head makes and it is sound for the same reason -- a draft is a proposal, the target
|
||||
* verifies every one of them with its own untouched head, and speculative decoding is
|
||||
* distribution-preserving, so a coarser draft costs acceptance and CANNOT change an emitted token.
|
||||
* `RADIANCE_DRAFT_RAW=dspark_cand` proposes column 0 of the candidate plane instead, which is the
|
||||
* base head's own argmax with the Markov walk thrown away: it isolates what the walk contributes,
|
||||
* and it needs no rebuild.
|
||||
*
|
||||
* THE CONFIDENCE HEAD IS NOT IMPLEMENTED AND THAT IS NOT A GAP. `AcceptRatePredictor` predicts a
|
||||
* per-position acceptance probability so a serving loop can shorten the block adaptively; this
|
||||
* engine's depth is fixed at declare time and only 1, 3 and 7 are legal. It changes nothing the
|
||||
* drafter proposes, so ignoring it is exactly correct -- unlike the input/output scalars Dflash2
|
||||
* refuses, which would silently move every logit.
|
||||
*
|
||||
* ============================== THE NORMS ARE PLAIN ==============================
|
||||
*
|
||||
* `w`, not `1 + w`: the reference norms with `Qwen3RMSNorm` and the config says `model_type:
|
||||
* qwen3`. `Geom::wadd` and `wadd_qk` are therefore ZERO for this block, which happens to agree
|
||||
* with its MiniCPM5 target -- but it is the drafter's own answer and not inherited, and the two
|
||||
* geometries are separate structs partly for this.
|
||||
*
|
||||
* ============================== WHAT IS FP8 AND WHAT IS NOT ==============================
|
||||
*
|
||||
* E4M3 + a bf16 [N/128][K/128] plane fc, q/k/v/o, gate_up, down -- every linear
|
||||
* BF16, no plane every norm, and both Markov codebooks
|
||||
*
|
||||
* The checkpoint is dense bf16 throughout, so the first row is rad_fp8.h's DenseFP8 over a weight
|
||||
* the recipe quantises to block fp8. The reason is bytes -- the drafter is read WHOLE on every
|
||||
* decode step, so 324M parameters at bf16 is 648 MB a step and at fp8 is 324 MB. Nothing it
|
||||
* computes can change an emitted token; the only thing quantising it can move is acceptance.
|
||||
*
|
||||
* The codebooks stay bf16 and REPLICATED because they are gathered by GLOBAL token id out of a
|
||||
* merged candidate set: a vocabulary shard would let a rank score only the candidates that
|
||||
* happened to land in its own slice. 66.8 MiB each, and the gather is K rows a position, so what
|
||||
* costs is the residency and not the reads.
|
||||
*
|
||||
* ============================== WHAT IS LEFT ON THE TABLE ==============================
|
||||
*
|
||||
* Two things this block does not do, and what each would be worth:
|
||||
*
|
||||
* THE Q/K NORM AND ROPE ARE FOUR LAUNCHES A LAYER where `qk_norm_rope` would be one. That op
|
||||
* takes a FUSED [q|k] row and this block keeps q, k and v in three buffers -- which the context
|
||||
* pass forces for k and v (it computes them with no q at all, and a block-scaled weight's layout
|
||||
* follows its op's N) but does not force for the query pass. Fusing would want a [q_dim + kv_dim]
|
||||
* buffer, a column-slice store, and a contiguous q lift for the attention, which is the trunk's
|
||||
* own arrangement (rad_block_attn_fp8.h). It is worth twenty launches a step.
|
||||
*
|
||||
* THE ALL-REDUCE IS NOT FOLDED INTO THE FOLLOWING NORM. NormQuantFP8 has the fused form and this
|
||||
* block passes kArNone, so a tp2 query pass issues ten collectives of its own. At `block` rows a
|
||||
* sequence the message is 28 KiB at one sequence -- under the lossy wire's floor and served
|
||||
* exactly -- so what a fold saves is launches, not bytes.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_DSPARK_H
|
||||
#define RAD_BLOCK_DSPARK_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct Dspark {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
/* The 2-bit draft head's scale group, which is the w2a8 row's own and not a choice. */
|
||||
enum { DS_W2_GROUP = 128 };
|
||||
|
||||
/* Everything the drafter's own config.json says that its geometry does not. Read by the plugin
|
||||
* from `draft.*` metadata keys and handed in whole, so this file reads no environment and no
|
||||
* container. */
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* NOISE ROWS a sequence -- and drafts, one per row */
|
||||
int64_t rank = 0; /* markov_rank: the codebooks' width */
|
||||
int64_t top_k = 0; /* candidates the Markov walk re-ranks */
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* EVERY ROW PREDICTS, so this is `block` and not `block - 1`. See THE ROW ALIGNMENT. */
|
||||
int64_t steps() const { return block; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* ---- the context pass, one row a COMMITTED TOKEN */
|
||||
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 */
|
||||
/* K AND V ARE TWO BUFFERS, not one [max_tok, 2*kv_dim] with K in its left half. Both
|
||||
* halves are written by one projection and read by one kv_store, so fusing them is the
|
||||
* obvious thing -- and it is wrong, because of the PER-HEAD NORM in between. `rmsnorm`
|
||||
* takes ONE row pitch. K inside a fused row is `head_dim` apart within a token and
|
||||
* `2*kv_dim` apart between tokens, and no single pitch is both; answering with the
|
||||
* between-tokens stride normalises every eighth head against the wrong numbers, which is
|
||||
* a drafter that runs and barely proposes anything the trunk accepts. libr4d refuses that
|
||||
* operand (libr4d/r4d_model.cpp, rows_pitch). */
|
||||
rad_buf ck = 0; /* [max_tok, kv_dim] ONE layer's K, reused across layers */
|
||||
rad_buf cv = 0; /* [max_tok, kv_dim] ONE layer's V, reused across layers */
|
||||
rad_buf srcq = 0, srcs = 0; /* the fp8 twins: e4m3 | f32 [.., /128] */
|
||||
rad_buf cq = 0, cs = 0;
|
||||
|
||||
/* ---- the query pass, `block` rows a sequence */
|
||||
rad_buf x = 0; /* [qrows, n_embd] the drafter's residual stream */
|
||||
/* THE NORMED INPUT AND THE BLOCK'S DELTA ARE ONE ACTIVATION, which is the trunk's own
|
||||
* arrangement (rad_block_attn_fp8.h): o_proj and down_proj write `h.x`, and the NEXT
|
||||
* norm reads it as the delta to fold into the stream before norming. One buffer, and the
|
||||
* op that reads it also writes it. */
|
||||
ActFP8 h{}; /* [qrows, n_embd] */
|
||||
rad_buf q = 0; /* [qrows, q_dim] */
|
||||
rad_buf k = 0; /* [qrows, kv_dim] -- two buffers, and `ck` above says why */
|
||||
rad_buf v = 0; /* [qrows, kv_dim] */
|
||||
ActFP8 attn{}; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
|
||||
ActFP8 ffn{}; /* [qrows, n_ff] */
|
||||
|
||||
/* ---- the head and the Markov walk, one row a DRAFT POSITION */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] the gathered final hidden states */
|
||||
rad_buf dq = 0; /* [srows, n_embd] i8 the 2-bit head's quantised activation */
|
||||
rad_buf ds = 0; /* [srows, 1] f32 one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/128, pad] f32 GROUP-major, quant_act_i8's asum plane */
|
||||
rad_buf dlog = 0; /* [srows, head_rows(g)] bf16 the coarse logits */
|
||||
rad_buf cand = 0; /* [srows, top_k] i32 candidate token ids, GLOBAL */
|
||||
rad_buf unary = 0; /* [srows, top_k] f32 and their logits */
|
||||
/* 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-R, and the all-gathered world * R. */
|
||||
rad_buf dpair = 0; /* [srows, top_k, 2] f32 */
|
||||
rad_buf dgath = 0; /* [srows, world * top_k, 2] f32 */
|
||||
rad_buf tokens = 0;/* [max_seqs, steps] i32 THE DRAFT -- the engine reads this by name */
|
||||
};
|
||||
|
||||
/* rad_arch.h's, asked through the block so whoever sizes `dlog` and the pair planes does not
|
||||
* re-derive the rule. */
|
||||
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); }
|
||||
|
||||
Geom g{}; /* the DRAFTER's geometry, not the trunk's */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0; /* absolute, so the KV group's layer_slot lookup finds these five */
|
||||
int64_t qrows = 0, crows = 0, srows = 0;
|
||||
int64_t gated_rows = 0; /* the band op_gug was declared over; 0 when there is no fold */
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* ---- model-scope weights */
|
||||
DenseFP8 w_fc{};
|
||||
rad_weight w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */
|
||||
rad_weight w_tok = 0; /* the TARGET's embedding table */
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the TARGET's lm_head */
|
||||
|
||||
/* ---- per-layer weights. Q, K AND V ARE THREE WEIGHTS and not the trunk's fused one: the
|
||||
* context pass wants k and v over the projected taps and has no use for q at all, so a fusion
|
||||
* would make it compute and discard a q_dim-wide GEMM per layer per context token. K and V are
|
||||
* apart from each other because a block-scaled weight's layout is a function of its OP's N and
|
||||
* both passes take one of them at a time. */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
|
||||
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
|
||||
/* ---- context-pass ops */
|
||||
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
|
||||
/* ---- query-pass ops. The weightless ones are declared once and issued per layer: an op's
|
||||
* declared read and write sets are what the buffer planner reads, and they are the same every
|
||||
* layer. The per-layer ones are per-layer because a weight's prefetch interval and residency
|
||||
* class come from the op that declares it. */
|
||||
rad_op op_embed = 0, op_embed_ar = 0;
|
||||
/* THE FUSED NORM / RESIDUAL-ADD / QUANTISE, declared by hand rather than through rad_fp8.h's
|
||||
* NormQuantFP8. The wrapper's extra machinery is its FUSED-COLLECTIVE forms, which this block
|
||||
* does not take (see WHAT IS LEFT ON THE TABLE), so what is left of it is one op -- and an
|
||||
* ARRAY of the wrapper is not compilable: it nests a Geom, and g++ 16.1 ICEs in build_vec_init
|
||||
* value-initialising an array of that inside an enclosing aggregate assignment (`m = Model{}`
|
||||
* in the plugin). Handles are what every other member here is anyway. */
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0;
|
||||
rad_op op_qat = 0;
|
||||
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] = {};
|
||||
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_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_act = 0, op_qff = 0, op_ar = 0;
|
||||
|
||||
/* ---- the head and the Markov walk */
|
||||
rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0; /* the vocab-parallel pair; 0 when the head is whole */
|
||||
rad_op op_sel = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
const char* ck_lm, const char* ck_lm_alt, const Wire& wire);
|
||||
/* The context pass, one row a committed token. `batch` carries those rows and the draft KV
|
||||
* group's slot mapping; nothing about the query block is read. */
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
/* The query pass, the head and the Markov walk: one call, `block` rows a sequence. */
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
private:
|
||||
int64_t q_dim() const { return g.n_head * g.head_dim; }
|
||||
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
int base_layer, rad_kvgroup group, rad_weight tok_embd,
|
||||
const char* ck, const char* ck_lm, const char* ck_lm_alt,
|
||||
const Wire& wire) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !ck_lm || !w_tok) return RAD_E_INVAL;
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: dspark has %lld layers; this block carries at most %d\n",
|
||||
(long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0 || cfg.rank <= 0 || cfg.top_k <= 0) return RAD_E_INVAL;
|
||||
|
||||
const int64_t qd = q_dim(), kvd = kv_dim();
|
||||
|
||||
crows = g.max_tok;
|
||||
qrows = g.max_seqs * cfg.block;
|
||||
if (qrows > g.max_tok) qrows = g.max_tok;
|
||||
/* EVERY QUERY ROW PREDICTS, so the head runs over as many rows as the block has. They are the
|
||||
* same number and they are kept apart anyway: one is a pass's rows and the other is what the
|
||||
* head was declared over, and Dflash2 -- the same struct shape over the other convention --
|
||||
* has them differ by one sequence's worth. */
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"),
|
||||
nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
|
||||
w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* THE TWO MARKOV CODEBOOKS, replicated at the WHOLE vocabulary and bf16. `markov_w1` is an
|
||||
* nn.Embedding and `markov_w2` an nn.Linear, and both store [vocab, rank] -- so the bigram
|
||||
* bias `w2 @ w1[prev]` is `<w1[prev], w2[cand]>` and the two go straight into the selector's
|
||||
* `pred` and `succ` slots in that order. RAD_ACCESS_VOCAB because the reads are a gather of K
|
||||
* rows a position and not a pass over the plane. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"),
|
||||
nm.ckpt("%s.markov_head.markov_w1.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"),
|
||||
nm.ckpt("%s.markov_head.markov_w2.weight", ck)));
|
||||
|
||||
w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* THE 2-BIT DRAFT HEAD, over the TARGET's lm_head. `dspark.draft_head.weight` is that tensor
|
||||
* under a name of its own, which the recipe quantises to the 2-bit grid (u2 codes, an f16
|
||||
* scale and a u8 zero a group of 128): one checkpoint tensor, two logical weights. The
|
||||
* argument is rad_block_mtp_fp8.h's and it is the same one the Markov walk's top-K rests on: a
|
||||
* draft is verified, so a coarser head costs acceptance and cannot move an emitted token.
|
||||
*
|
||||
* A TIED HEAD IS THE ALTERNATIVE SOURCE. Small LLaMA derivatives ship no `lm_head.weight` and
|
||||
* read the embedding table as both; the trunk's own head is declared that way and the
|
||||
* drafter's copy has to agree with it or the two would disagree about what the model's
|
||||
* vocabulary projection IS. */
|
||||
const bool dh_shard = head_sharded(g);
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dspark.draft_head.weight");
|
||||
if (ck_lm_alt && *ck_lm_alt) RAD_ARCH_TRY(map_copy_alt(b, dhn, ck_lm, ck_lm_alt));
|
||||
else 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("dspark.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup grp = grp_layer(first_layer + i);
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.ffn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_q_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dspark.blk.%d.attn_k_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
|
||||
|
||||
w_anorm[i] = decl_w(b, nm.f("dspark.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
w_fnorm[i] = decl_w(b, nm.f("dspark.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dspark.blk.%d.attn_q", i), qd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dspark.blk.%d.attn_k", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dspark.blk.%d.attn_v", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
|
||||
w_qn[i] = decl_w(b, nm.f("dspark.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
w_kn[i] = decl_w(b, nm.f("dspark.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp);
|
||||
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dspark.blk.%d.attn_output", i), g.n_embd, qd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dspark.blk.%d.ffn_gate_up", i),
|
||||
2 * g.n_ff, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp,
|
||||
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
|
||||
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
|
||||
{ g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dspark.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp,
|
||||
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
|
||||
}
|
||||
|
||||
/* NON-CAUSAL. The block is denoised as a whole, so every query row sees every other row of its
|
||||
* own block as well as the context -- `causal` 0 is the drafter's own `is_causal: false` and
|
||||
* not a default.
|
||||
*
|
||||
* DECLARED FIRST, before either kv_store, even though it runs after both. `block_size` is
|
||||
* RAD_DERIVED -- the KV block is a property of the resolved attention kernel and not a number
|
||||
* anyone gets to choose -- so it is omitted here and READ BACK with rad_kv_block_size() for
|
||||
* the two stores, which need it as a parameter. Ask before the attention op is declared and
|
||||
* the answer is zero. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal),
|
||||
RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn.x});
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass
|
||||
*
|
||||
* EVERY LINEAR HERE IS `fp8a8` and every activation that feeds one gets a `quant_act_fp8` in
|
||||
* front of it. There is no `fp8a16` band anywhere in this block: that kernel is M <= 1 and
|
||||
* neither pass ever runs at one row -- a context pass is a committed chunk and a query pass is
|
||||
* `block` rows by construction. */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_fc.w, w_fc.s)),
|
||||
{w.srcq, w.srcs}, {w.c});
|
||||
/* IN PLACE. Safe for any implementation that computes a row's scale before writing the row,
|
||||
* which none can avoid doing; the per-head q/k norms below run in place for the same reason. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
/* ONE QUANTISE FOR ALL FIVE LAYERS. `c` is the normed projection of the trunk's taps and every
|
||||
* layer's k|v reads that same buffer, so this is one launch a context pass and not five. */
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
/* TWO OPS OF THE SAME SHAPE, one per weight: an op's declared weight list is what gives a
|
||||
* weight its prefetch interval and its residency class. */
|
||||
op_ck[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ck});
|
||||
}
|
||||
/* K-ONLY ROPE. `rope` rotates the first n_head + n_head_kv heads of its operand and leaves the
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer.
|
||||
*
|
||||
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
|
||||
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
|
||||
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck}, {w.ck});
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck, w.cv}, {});
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.x});
|
||||
/* The target's embedding is vocab-sharded, so this gather is partial and takes the same EXACT
|
||||
* reduction the trunk's does: each token's row comes from one rank and every other contributes
|
||||
* a zero, so a lossy wire would be pure loss on a value that is already the answer. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x}, {w.x});
|
||||
|
||||
/* THE NORM, THE RESIDUAL ADD AND THE QUANTISER ARE ONE OP -- `rmsnorm_quant_fp8`, which
|
||||
* rad_fp8.h's NormQuantFP8 wraps. Layer 0 has no delta to fold (its input is the embedding
|
||||
* itself), every layer after it folds the previous feed-forward's, and `nq_out` folds the last
|
||||
* one into the FINAL norm. So there is no `add` op in this block at all and the final norm is
|
||||
* not a separate launch either.
|
||||
*
|
||||
* `nq_out` QUANTISES SOMETHING NOTHING READS. The head after it wants bf16 (it runs its own
|
||||
* i8 quantiser at a different group width), and this op writes the bf16 normed row as well as
|
||||
* the fp8 twin -- so the twin is 14 KiB of waste at a seven-row block, against a launch. The
|
||||
* alternative is `add` + `rmsnorm`, which is two, because libr4d has no plain `rmsnorm_add`
|
||||
* row: `rmsnorm_quant_fp8` IS this library's fused norm-add. */
|
||||
/* `x` IS THE DELTA AND `residual` IS THE STREAM, and the op adds the first into the second
|
||||
* before norming: residual_out = x + residual, y = rmsnorm(residual_out) * w. So a FOLDED
|
||||
* site passes the previous block's output buffer as `x` and the stream as `residual`, and the
|
||||
* UNFOLDED one (layer 0, whose input is the embedding) passes the stream as `x` and no
|
||||
* residual at all. An absent optional operand is a null tensor in a full-length list.
|
||||
*
|
||||
* `residual` is INOUT, so it is in both sets: the buffer planner reads these for liveness and
|
||||
* an INOUT that claimed only one of them is a plan free to reorder a reader in front of it. */
|
||||
auto decl_norm = [&](rad_weight gain, bool fold) -> rad_op {
|
||||
rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(gain));
|
||||
if (!h) return 0;
|
||||
rad_buf rd[2] = { fold ? w.h.x : w.x, w.x };
|
||||
rad_buf wr[4] = { w.h.q, w.h.s, w.h.x, w.x };
|
||||
rad_op_reads (b, h, rd, fold ? 2 : 1);
|
||||
rad_op_writes(b, h, wr, fold ? 4 : 3);
|
||||
return h;
|
||||
};
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = decl_norm(w_anorm[i], i != 0);
|
||||
op_fnorm[i] = decl_norm(w_fnorm[i], true);
|
||||
if (!op_anorm[i] || !op_fnorm[i]) return RAD_E_INVAL;
|
||||
}
|
||||
op_outnorm = decl_norm(w_norm, true);
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn.x}, {w.attn.q, w.attn.s});
|
||||
if (!op_outnorm || !op_qat) return RAD_E_INVAL;
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_q[i].w, w_q[i].s)),
|
||||
{w.h.q, w.h.s}, {w.q});
|
||||
op_kp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_k[i].w, w_k[i].s)),
|
||||
{w.h.q, w.h.s}, {w.k});
|
||||
op_vp[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", kvd),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_v[i].w, w_v[i].s)),
|
||||
{w.h.q, w.h.s}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.q});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", qd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_o[i].w, w_o[i].s)),
|
||||
{w.attn.q, w.attn.s}, {w.h.x});
|
||||
op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.gate_up});
|
||||
/* THE GATED FOLD: gate_up, silu_mul and the quantiser in one GEMM epilogue, over the same
|
||||
* weights and into the same activation. NOT RAD_ARCH_TRY -- a kernel set without the row
|
||||
* is the ordinary case and the pair below still runs -- and `gated_rows` is the band it
|
||||
* was declared over, checked at the issue site, because M past the band is a REFUSAL in
|
||||
* the kernel and not a slower path. */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0) {
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.h.q, w.h.s}, {w.ffn.q, w.ffn.s});
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8")),
|
||||
RAD_WEIGHTS(w_dn[i].w, w_dn[i].s)),
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k}, {w.k});
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn.x});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn.x}, {w.ffn.q, w.ffn.s});
|
||||
/* ONE COLLECTIVE DECLARATION, issued after the out projection and after the down projection:
|
||||
* the two have the same shape over the same buffer. It is EXACT or lossy by the deployment's
|
||||
* own setting, exactly as the trunk's is -- the drafter's message is the same residual stream
|
||||
* and there is no reason for it to be held to a different standard than the thing it drafts
|
||||
* for. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* ---------------------------------------------------------------- the head and the walk
|
||||
*
|
||||
* EVERY ROW OF THE BLOCK PREDICTS, so the head runs over all `steps` of them and the anchor is
|
||||
* not skipped -- THE OPPOSITE of Dflash2, and the paragraph at the top of this file is why.
|
||||
* The gather is what makes those rows contiguous, and it is also what fixes the head's row
|
||||
* numbering at s * steps + l, which is the numbering the walk reads. It is the identity map
|
||||
* for this convention as the scheduler emits it; it is issued anyway, because `out_ids` is the
|
||||
* contract and RADIANCE_DFLASH_ANCHOR is allowed to move it. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.sel_h});
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", DS_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", DS_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. */
|
||||
op_dtopk = dh_shard
|
||||
? rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.top_k), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("R", cfg.top_k), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary});
|
||||
if (dh_shard) {
|
||||
/* ROW-INTERLEAVED, so one draft position's pairs from every rank land side by side --
|
||||
* `row_topk_merge` reads one row at one row stride. The merge reduces them to the same
|
||||
* global top-R an unsharded head would have found, exactly, ties included, which is what
|
||||
* lets the codebooks stay replicated and indexed by global id. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * cfg.top_k * 2),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", cfg.top_k * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("R", cfg.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dgath}, {w.cand, w.unary});
|
||||
}
|
||||
/* THE MARKOV WALK. `dflash_select` with the hidden projection ABSENT is the plain bigram
|
||||
* `unary + <markov_w1[prev], markov_w2[cand]>`, decoded greedily with the predecessor read
|
||||
* after the previous step's argmax -- which is the Markov head, and the top of this file
|
||||
* argues both halves of that claim. Operands are POSITIONAL, so the absent `hp` is still
|
||||
* passed, as RAD_NONE, at the issue site.
|
||||
*
|
||||
* `anchor_stride` is `block`, because the operand is the step's own token_ids: a draft pass
|
||||
* carries `block` ids a sequence and the anchor is the first of them. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.top_k), RAD_INT("rank", cfg.rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_mk1, w_mk2)),
|
||||
{w.cand, w.unary}, {w.tokens});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void Dspark::context(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, RAD_NONE);
|
||||
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, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv,
|
||||
brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void Dspark::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
/* The fused norm at its three sites. Folded, `x` is the delta the previous block left in
|
||||
* `h.x` and the stream is added into; unfolded (layer 0), `x` IS the stream and there is no
|
||||
* residual operand -- an absent optional operand is still passed, as RAD_NONE. */
|
||||
auto issue_norm = [&](rad_op op, bool fold, rad_weight gain, int64_t rows) {
|
||||
RAD_ISSUE_N(c, op, rows, brows(fold ? w.h.x : w.x, rows),
|
||||
fold ? brows(w.x, rows) : RAD_NONE, RAD_W(gain),
|
||||
brows(w.h.q, rows), brows(w.h.s, rows), brows(w.h.x, rows));
|
||||
};
|
||||
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok),
|
||||
brows(w.x, T));
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
|
||||
/* ---- attention. The norm folds the previous layer's feed-forward delta into the stream
|
||||
* and quantises, all in one launch; at layer 0 there is no delta and it norms the
|
||||
* embedding itself. */
|
||||
issue_norm(op_anorm[i], i != 0, w_anorm[i], T);
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, RAD_NONE);
|
||||
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));
|
||||
/* THE NOISE ROWS GO INTO THE CACHE, past this sequence's `seqused`, and the next context
|
||||
* pass overwrites them from the trunk's real hidden states. That is the reference's
|
||||
* `crop(start)` and it is why nothing here has to undo anything. */
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn.x, T), brows(w.attn.q, T), brows(w.attn.s, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.attn.q, T), brows(w.attn.s, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
|
||||
/* ---- the feed-forward, behind the same fused norm-add-quantise */
|
||||
issue_norm(op_fnorm[i], true, w_fnorm[i], T);
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gug[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffn.q, T), brows(w.ffn.s, T),
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.h.q, T), brows(w.h.s, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn.x, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn.x, T), brows(w.ffn.q, T), brows(w.ffn.s, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffn.q, T), brows(w.ffn.s, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h.x, T), RAD_NONE, RAD_NONE);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
}
|
||||
|
||||
/* The last layer's delta folds into the FINAL norm rather than into a norm of its own. */
|
||||
issue_norm(op_outnorm, true, w_norm, T);
|
||||
|
||||
/* The rows that predict something, which here is all of them. The scheduler names them
|
||||
* through out_ids, the same field the trunk's own logits gather reads. */
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h.x), praw(batch->out_ids, RAD_I32, S),
|
||||
brows(w.sel_h, S));
|
||||
|
||||
/* `dsum` is quant_act_i8's GROUP-major plane, [n_embd/group][ceil(M/16)*16], so it is passed
|
||||
* whole: there is no row slice of it that means anything. */
|
||||
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 and is absent here; an absent optional
|
||||
* operand is a null tensor in a FULL-LENGTH list, not a shorter list. */
|
||||
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);
|
||||
if (op_dmerge) {
|
||||
/* Sharded, this rank's top-R is not the answer -- it is this rank's CANDIDATES, and
|
||||
* `cand`/`unary` are overwritten by the merge two ops below. Writing them here anyway
|
||||
* costs nothing and keeps one issue site for both paths. */
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_dmerge, S, brows(w.dgath, S), brows(w.cand, S), brows(w.unary, S));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
}
|
||||
/* RAD_NONE in the third slot is the ABSENT hidden projection -- the bigram form. */
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, brows(w.cand, S), brows(w.unary, S), RAD_NONE,
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_DSPARK_H */
|
||||
@@ -0,0 +1,398 @@
|
||||
/* rad_block_gdn.h -- one gated-delta-net (linear attention) block, bf16 operands.
|
||||
*
|
||||
* Hybrid models are the normal case, not an extension (spec §7.2): Qwen3.5-27B is 48 GDN layers to
|
||||
* 16 full-attention ones. This block is the GDN half, and it composes with AttnGatedBF16 and
|
||||
* MlpBF16 in one plugin exactly as they compose with each other.
|
||||
*
|
||||
* rmsnorm -> in gemm ([q|k|v|a|b]) -> z gemm
|
||||
* prefill: gdn_conv_prep -> gdn_kkt_solve -> gdn_chunk_scan -> gdn_gated_rmsnorm
|
||||
* decode: gdn_conv_update -> gdn_recurrent_update (which folds the gated norm)
|
||||
* -> out gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* THE TWO PATHS ARE A BRANCH ON PHASE, WHICH IS NOT THE BRANCH SPEC §2.4 FORBIDS. A quant branch
|
||||
* makes the graph unreadable because it hides which of two op sequences a model uses; this branch
|
||||
* picks between two sequences that are both declared, both resolved, both in the graph dump, and
|
||||
* both run by the same model on different steps. The chunked path amortises across a prefill chunk
|
||||
* and the recurrent path is O(1) per token; there is no single kernel that is right for both.
|
||||
*
|
||||
* Both paths take `num_accepted`, because a linear-attention kernel pair MUST support speculative
|
||||
* rollback: the recurrent state and the conv window have already absorbed rejected tokens, and a
|
||||
* rejection is a change of read offset rather than a recompute (spec §10, OPS.md).
|
||||
*
|
||||
* ============================== TWO CONVENTIONS TO GET RIGHT ==============================
|
||||
*
|
||||
* `A_log` IS A LOG AND THE EXPONENT HAS NOT BEEN TAKEN. The decay is
|
||||
*
|
||||
* g = -exp(A_log) . softplus(a + dt_bias)
|
||||
*
|
||||
* and the kernels -- libr4d's and libref's alike -- take the exponent themselves. The
|
||||
* safetensors checkpoint stores `linear_attn.A_log` in exactly that form, so this block declares
|
||||
* the weight as `ssm_a_log` and maps it straight through. THE GGUF CONVERSION DOES NOT: llama.cpp
|
||||
* writes `ssm_a = -exp(A_log)` at convert time, so a container built from a GGUF must undo that or
|
||||
* the decay becomes -exp(-exp(A_log)), which is a number near -1 for every head and a model that
|
||||
* forgets everything in four tokens. The name carries the convention so the mismatch is visible in
|
||||
* the weight manifest rather than in the perplexity.
|
||||
*
|
||||
* q AND k ARE L2-NORMALISED, NOT RMS-NORMALISED. Different arithmetic -- no division by the head
|
||||
* width and no gain vector -- and it lives inside gdn_conv_prep (prefill) and
|
||||
* gdn_recurrent_update (decode) because both kernels already have the head in registers. There is
|
||||
* no l2_norm op to declare and there should not be one.
|
||||
*
|
||||
* ============================== THE FUSED IN-PROJECTION ==============================
|
||||
*
|
||||
* gdn_conv_prep's `x` is the whole projection row [q | k | v | a | b]: conv_dim convolved channels
|
||||
* followed by one decay input and one beta input per value head. So the three checkpoint tensors
|
||||
* in_proj_qkv, in_proj_a and in_proj_b are ONE declared weight and ONE GEMM, which is also one
|
||||
* movement unit and one launch instead of three. The cost is the ability to place them
|
||||
* separately, which nothing wants.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_GDN_H
|
||||
#define RAD_BLOCK_GDN_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct GdnBF16 {
|
||||
struct Config {
|
||||
int64_t n_head_k = 0; /* per rank -- q and k share these */
|
||||
int64_t head_k = 0; /* the recurrent state's key width */
|
||||
int64_t n_head_v = 0; /* per rank; a multiple of n_head_k, 3x it on this model */
|
||||
int64_t head_v = 0;
|
||||
int64_t conv_width = 4;
|
||||
int64_t chunk = 64; /* the chunked-scan interval, and the checkpoint interval */
|
||||
|
||||
int64_t k_dim() const { return n_head_k * head_k; }
|
||||
int64_t v_dim() const { return n_head_v * head_v; }
|
||||
int64_t conv_dim() const { return 2 * k_dim() + v_dim(); }
|
||||
int64_t in_dim() const { return conv_dim() + 2 * n_head_v; } /* ... + a + b */
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the out projection */
|
||||
rad_buf in = 0; /* [max_tok, in_dim] [q|k|v|a|b], pre-convolution */
|
||||
rad_buf z = 0; /* [max_tok, v_dim] the output gate */
|
||||
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
|
||||
rad_buf k = 0; /* [max_tok, n_head_k, head_k] */
|
||||
rad_buf v = 0; /* [max_tok, n_head_v, head_v] */
|
||||
rad_buf gdec = 0; /* [max_tok, n_head_v] the resolved decay, per-chunk cumsum */
|
||||
rad_buf beta = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] the within-chunk inverse */
|
||||
rad_buf o = 0; /* [max_tok, n_head_v, head_v] */
|
||||
};
|
||||
|
||||
/* Checkpoint-side names for one layer; the plugin owns the spelling (spec §2.4). */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* in_qkv = nullptr; /* linear_attn.in_proj_qkv.weight */
|
||||
const char* in_a = nullptr; /* linear_attn.in_proj_a.weight */
|
||||
const char* in_b = nullptr; /* linear_attn.in_proj_b.weight */
|
||||
const char* in_z = nullptr; /* linear_attn.in_proj_z.weight */
|
||||
const char* conv1d = nullptr; /* linear_attn.conv1d.weight */
|
||||
const char* a_log = nullptr; /* linear_attn.A_log -- a LOG, see the header comment */
|
||||
const char* dt_bias = nullptr; /* linear_attn.dt_bias */
|
||||
const char* out_norm = nullptr; /* linear_attn.norm.weight */
|
||||
const char* out = nullptr; /* linear_attn.out_proj.weight */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
Src src{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv_state = 0, kv_conv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_in = 0, w_z = 0, w_conv = 0;
|
||||
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0, w_out = 0;
|
||||
|
||||
rad_op op_norm = 0, op_in = 0, op_z = 0;
|
||||
rad_op op_conv_prep = 0, op_kkt = 0, op_scan = 0, op_gnorm = 0; /* prefill */
|
||||
rad_op op_conv_update = 0, op_recur = 0; /* decode */
|
||||
rad_op op_out = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int GdnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s) {
|
||||
g = geom; cfg = c; w = wire; src = s; layer = l; kv_state = state; kv_conv = conv;
|
||||
if (cfg.n_head_k <= 0 || cfg.head_k <= 0 || cfg.n_head_v <= 0 || cfg.head_v <= 0 ||
|
||||
cfg.conv_width <= 0 || cfg.chunk <= 0)
|
||||
return RAD_E_INVAL;
|
||||
/* q and k are shared across a group of value heads -- 16 key heads to 48 value heads on this
|
||||
* model. The kernels take H and Hg separately for exactly that; a value head count that is not
|
||||
* a multiple of the key head count is a geometry no GDN kernel serves. */
|
||||
if (cfg.n_head_v % cfg.n_head_k != 0) {
|
||||
fprintf(stderr, "radiance: %lld value heads is not a multiple of %lld key heads\n",
|
||||
(long long)cfg.n_head_v, (long long)cfg.n_head_k);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
|
||||
* carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
|
||||
* 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
|
||||
* that; llama.cpp's fused GDN does the same.
|
||||
*
|
||||
* IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
|
||||
* norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
|
||||
* nothing. That argument is wrong here for one reason: the scan output of this model is around
|
||||
* 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
|
||||
* the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
|
||||
* to the residual stream.
|
||||
*
|
||||
* Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
|
||||
* implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
|
||||
* layers delta net the residual stream then carries a delta-net contribution that many times
|
||||
* too large -- fluent grammar with no content. */
|
||||
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
|
||||
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
const int64_t conv_dim = cfg.conv_dim();
|
||||
const int64_t in_dim = cfg.in_dim();
|
||||
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
/* The fusion: q, k, v, a and b in one row, because that is the row
|
||||
* gdn_conv_prep reads. A row-sharded CONCAT shards each source before concatenating -- and
|
||||
* `in_proj_qkv` is ITSELF three head groups, so the row split declared below is FIVE parts and
|
||||
* not three: q, k and v out of the fused source, then a, then b. The maps come ahead of the
|
||||
* weights they name, since a checkpoint is asked what a weight is through its map. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_in.weight", l),
|
||||
{ src.in_qkv, src.in_a, src.in_b }, 0));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_z.weight", l), src.in_z));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_conv1d.weight", l), src.conv1d));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_a_log", l), src.a_log));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_dt.bias", l), src.dt_bias));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_norm.weight", l), src.out_norm));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_out.weight", l), src.out));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_in = decl_w(b, nm.f("blk.%d.ssm_in.weight", l), RAD_BF16, {in_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.n_head_v, cfg.n_head_v});
|
||||
w_z = decl_w(b, nm.f("blk.%d.ssm_z.weight", l), RAD_BF16, {v_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
/* The depthwise convolution is per channel, so it shards with the channels it convolves. The
|
||||
* checkpoint ships [conv_dim, 1, 4]; the middle extent is the depthwise group and is squeezed
|
||||
* at convert. There is NO conv bias on this architecture -- Qwen3.5's conv1d has bias=False --
|
||||
* so none is declared and the operand is passed absent rather than as a zero vector nobody
|
||||
* loads. */
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
|
||||
{conv_dim, cfg.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim()});
|
||||
w_a_log = decl_w(b, nm.f("blk.%d.ssm_a_log", l), RAD_F32, {cfg.n_head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_dt_bias = decl_w(b, nm.f("blk.%d.ssm_dt.bias", l), RAD_F32, {cfg.n_head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
/* One gain vector over head_v, shared by every head: replicated, like the attention q/k
|
||||
* gains. */
|
||||
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_out = decl_w(b, nm.f("blk.%d.ssm_out.weight", l), RAD_BF16, {g.n_embd, v_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)), {w.x}, {w.h});
|
||||
op_in = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", in_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_in)), {w.h}, {w.in});
|
||||
op_z = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", v_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_z)), {w.h}, {w.z});
|
||||
|
||||
/* ---- the chunked path: a prefill chunk, where the scan amortises over `chunk` tokens.
|
||||
* `chunk` is RAD_DERIVED on gdn_kkt_solve and gdn_chunk_scan for the same reason block_size is
|
||||
* on attn_paged -- the tile length belongs to the kernel -- so it is omitted there and comes
|
||||
* off the resolution. gdn_conv_prep still takes it, because the gate cumsum it writes is per
|
||||
* chunk and has to be cut at the same boundary the scan tiles on. THAT THOSE TWO NUMBERS CAN
|
||||
* DISAGREE IS A HOLE: one is supplied and one is derived, nothing compares them, and a
|
||||
* mismatch is a decay applied over the wrong span rather than a diagnostic. Closing it needs
|
||||
* either a readback for a resolved parameter or conv_prep's chunk made derived too. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
|
||||
RAD_INT("conv_width", cfg.conv_width)),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias)),
|
||||
{w.in}, {w.q, w.k, w.v, w.gdec, w.beta});
|
||||
op_kkt = rw(b, RAD_OP(b, "gdn_kkt_solve",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.beta, w.gdec}, {w.kkt});
|
||||
op_scan = rw(b, RAD_OP(b, "gdn_chunk_scan",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_F64("scale", q_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q, w.k, w.v, w.kkt, w.gdec, w.beta}, {w.o});
|
||||
op_gnorm = rw(b, RAD_OP(b, "gdn_gated_rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", cfg.head_v),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w_out_norm)),
|
||||
{w.o, w.z}, {w.o});
|
||||
|
||||
/* ---- the recurrent path: decode and speculative verify, ranged on q_len because a verify
|
||||
* step carries up to n_spec+1 query rows per sequence. `n_head_v` is stated rather than left
|
||||
* to the value tensor's rank: 48 value heads against 16 key heads is the one geometry where
|
||||
* guessing it from a flattened view gives a plausible wrong answer. */
|
||||
op_conv_update = rw(b, RAD_OP(b, "gdn_conv_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width)),
|
||||
RAD_WEIGHTS(w_conv)),
|
||||
{w.in}, {w.q, w.k, w.v});
|
||||
/* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
|
||||
* update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
|
||||
* needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
|
||||
* the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
|
||||
* Same `o` either way, and a completely different `state` -- so a reference that implements one
|
||||
* of them and is handed the other computes a correct answer to the other question.
|
||||
*
|
||||
* The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
|
||||
* and 1 when it does not, which is exactly this condition. Saying it here is what lets a
|
||||
* reference DECLINE the form it does not implement instead of disagreeing with it, and what
|
||||
* lets the kernel refuse a caller whose pool was sized for the other one. */
|
||||
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("n_head_v", cfg.n_head_v),
|
||||
RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", "silu"),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.q, w.k, w.v, w.in, w.z}, {w.o});
|
||||
|
||||
op_out = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", v_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_out)),
|
||||
{w.o}, {w.h});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void GdnBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* st = kv_batch(batch, kv_state);
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
|
||||
const int32_t* st_idx = st ? st->state_index : nullptr;
|
||||
/* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
|
||||
* asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
|
||||
* The block passes the row through and does not read it. */
|
||||
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
|
||||
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const int64_t conv_dim = cfg.conv_dim();
|
||||
const int64_t H = cfg.n_head_v;
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_in, brows(w.h, T), RAD_W(w_in), brows(w.in, T));
|
||||
RAD_ISSUE(c, op_z, brows(w.h, T), RAD_W(w_z), brows(w.z, T));
|
||||
|
||||
/* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES. rad_block_gdn_fp8.h's step() carries the
|
||||
* long form of why; the short one is that the step is sorted decode-first, every kernel here
|
||||
* derives both its grid and its rows from cu_seqlens, and cu holds ABSOLUTE offsets -- so the
|
||||
* prefill half is addressed by handing it `cu + D` with the token operands left at their
|
||||
* base, and the decode half by narrowing both to DT. The gated norm takes no cu and is per
|
||||
* token, so it takes a row slice instead. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
/* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
|
||||
* over a pure decode step it is already the right number, so a batch that leaves
|
||||
* max_q_len_decode zero still selects correctly there. */
|
||||
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
|
||||
const int64_t P = S - D;
|
||||
const int64_t PT = T - DT;
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
|
||||
if (D > 0) {
|
||||
RAD_ISSUE_N(c, op_conv_update, qd,
|
||||
brows(w.in, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
praw(cv_idx, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT));
|
||||
/* a and b are the last 2*n_head_v columns of the projection row, read in place. The
|
||||
* recurrent kernel folds the gated norm, which is why it takes z and the gain: at one
|
||||
* token a head there is nothing to gain from a second pass over the state. */
|
||||
RAD_ISSUE_N(c, op_recur, qd,
|
||||
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
|
||||
bcol(w.in, conv_dim, H, DT), bcol(w.in, conv_dim + H, H, DT),
|
||||
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.z, DT), RAD_W(w_out_norm), brows(w.o, DT),
|
||||
/* The folded out-projection quantiser, which this block does not want: the
|
||||
* bf16 out projection reads `o` directly. Absent is TWO NULL OPERANDS, not a
|
||||
* shorter list -- operands are positional and the runtime refuses a count
|
||||
* that does not match the schema's sixteen (core/runtime/issue.cpp:111). */
|
||||
RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
if (P > 0) {
|
||||
/* Sixteen operands, inputs before outputs (docs/OPS.md). `a` and `b_gate` are the same
|
||||
* strided views of the projection row the recurrent path builds above; they are optional
|
||||
* in the schema -- ref falls back to the fused `x` tail -- but libr4d's conv_prep
|
||||
* dereferences them and `cache_idx` unconditionally, so omitting them does not select a
|
||||
* cheaper kernel, it silently drops the layer to the reference one.
|
||||
*
|
||||
* `has_init` is ctx_lens, and it is exactly the right array: a zero entry means the slot
|
||||
* holds no history, and a sequence's context length before this step is zero precisely
|
||||
* when it is starting fresh -- a new sequence, or one preempted and replaying, whose conv
|
||||
* slot was recycled and holds another sequence's window. Without it the first chunk of
|
||||
* every prefill convolves against whatever the slot last contained. */
|
||||
RAD_ISSUE(c, op_conv_prep,
|
||||
brows(w.in, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
|
||||
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
bcol(w.in, conv_dim, H, T), bcol(w.in, conv_dim + H, H, T),
|
||||
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE(c, op_kkt,
|
||||
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(w.kkt, T));
|
||||
RAD_ISSUE(c, op_scan,
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
|
||||
brows(w.gdec, T), brows(w.beta, T),
|
||||
kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
brows(w.o, T), kv_cache(kv_state, layer),
|
||||
praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
|
||||
/* PER TOKEN, so a row slice and not a sequence sub-array: over the decode rows the
|
||||
* recurrent kernel has already applied the gate in its own epilogue. */
|
||||
RAD_ISSUE_N(c, op_gnorm, PT,
|
||||
brow_slice(w.o, DT, PT, v_dim), brow_slice(w.z, DT, PT, v_dim),
|
||||
RAD_W(w_out_norm), brow_slice(w.o, DT, PT, v_dim));
|
||||
}
|
||||
RAD_ISSUE(c, op_out, brows(w.o, T), RAD_W(w_out), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GDN_H */
|
||||
@@ -0,0 +1,519 @@
|
||||
/* rad_block_gdn_fp8.h -- the gated-delta-net block with block-scaled FP8 projections.
|
||||
*
|
||||
* THE ARCHITECTURE IS rad_block_gdn.h's AND IS DOCUMENTED THERE: that `A_log` is a log and the
|
||||
* kernels take the exponent themselves, that q and k are L2-normalised rather than RMS-normalised
|
||||
* and that this happens inside the conv/recurrent kernels, why the prefill and decode paths are two
|
||||
* declared sequences and why that is not the branch spec §2.4 forbids, and why both take
|
||||
* `num_accepted`. None of it changes with the weight format.
|
||||
*
|
||||
* ============================== a AND b SPLIT OUT; z DOES NOT ==============================
|
||||
*
|
||||
* rad_block_gdn.h fuses in_proj_qkv, in_proj_a and in_proj_b into ONE weight and one GEMM, because
|
||||
* [q|k|v|a|b] is the row gdn_conv_prep reads. THAT FUSION IS NOT AVAILABLE HERE, and the reason is
|
||||
* the checkpoint rather than a limitation:
|
||||
*
|
||||
* in_proj_qkv.weight F8_E4M3 [10240, 5120] with weight_scale_inv [80, 40]
|
||||
* in_proj_z.weight F8_E4M3 [ 6144, 5120] with weight_scale_inv [48, 40]
|
||||
* in_proj_a.weight BF16 [48, 5120] -- no scale plane
|
||||
* in_proj_b.weight BF16 [48, 5120] -- no scale plane
|
||||
*
|
||||
* a and b emit ONE COLUMN PER VALUE HEAD, 48 of them, and 48 is not a whole 128-row scale block --
|
||||
* so the quantiser that produced this checkpoint left them in bf16, and no concatenation of an
|
||||
* E4M3 tensor with a BF16 one is a tensor. They become a second, tiny bf16 `gemm_nt`: [96, 5120],
|
||||
* 0.5% of the layer's projection bytes, and the price of it is one extra launch.
|
||||
*
|
||||
* a and b are separate operands of gdn_conv_prep and gdn_recurrent_update in both blocks -- the
|
||||
* bf16 block passes them as column views of the fused row, this one as column views of their own
|
||||
* buffer -- so nothing downstream changes shape. Ref sizes its `x` read as
|
||||
* `conv_dim + (a present ? 0 : 2*H)` for precisely this case.
|
||||
*
|
||||
* THE OUTPUT GATE IS THE OPPOSITE CASE and it IS fused, into `ssm_inz`: in_proj_z is E4M3 with its
|
||||
* own scale plane, its rows are a whole number of blocks, and it reads the same normed activation.
|
||||
* So [q|k|v|z] is one weight, one launch and the same bytes -- see declare() for why one call is
|
||||
* cheaper than two. What that costs is that `w.in.x` is conv_dim + v_dim wide, and the convolution
|
||||
* and the gate are COLUMN VIEWS of it rather than buffers of their own: gdn_conv_prep,
|
||||
* gdn_conv_update and gdn_recurrent_update all take a row pitch on the operand concerned.
|
||||
*
|
||||
* ============================== THE OUT-PROJECTION'S INPUT IS RANK 3 ==============================
|
||||
*
|
||||
* `o` is [tokens, value heads, head width] because libr4d's chunk-scan and recurrent kernels
|
||||
* require rank 3 there, and it is the out-projection's activation -- so the quantiser has to accept
|
||||
* it. It does: rows are dim 0 and everything after is the row, which is the reading r4d_row_pitch
|
||||
* already takes and which the consuming GEMM's K forces. Reading it as one row per HEAD would put a
|
||||
* scale on a grid the GEMM does not read.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_GDN_FP8_H
|
||||
#define RAD_BLOCK_GDN_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct GdnFP8 {
|
||||
/* The same geometry the bf16 block takes, with one addition: `ab_dim` is what the split costs
|
||||
* in declared width, and it is 2 * n_head_v. */
|
||||
struct Config {
|
||||
int64_t n_head_k = 0;
|
||||
int64_t head_k = 0;
|
||||
int64_t n_head_v = 0;
|
||||
int64_t head_v = 0;
|
||||
int64_t conv_width = 4;
|
||||
int64_t chunk = 64;
|
||||
/* THE OUTPUT GATE'S ACTIVATION, and it is a CHECKPOINT PROPERTY rather than a family
|
||||
* one. `RMSNormGated` defaults to silu and every Qwen3.5/3.6 release leaves it there,
|
||||
* but Qwen4-Exp states `output_gate_type: "sigmoid"` and means it -- a gate of
|
||||
* sigmoid(z) where this said silu(z) scales every value head's output by roughly z
|
||||
* again. libr4d has compiled both arms all along (r4d_gdn_gated_rmsnorm's `gn_act`) and
|
||||
* `gdn_recurrent_update` composes the same parameter, so this is a string to pass and
|
||||
* not a kernel to write. "silu" or "sigmoid"; anything else is refused below. */
|
||||
const char* act = "silu";
|
||||
|
||||
int64_t k_dim() const { return n_head_k * head_k; }
|
||||
int64_t v_dim() const { return n_head_v * head_v; }
|
||||
int64_t conv_dim() const { return 2 * k_dim() + v_dim(); }
|
||||
int64_t ab_dim() const { return 2 * n_head_v; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the out projection */
|
||||
/* ONE BUFFER, TWO PROJECTIONS: [q|k|v] and the output gate come out of one GEMM (see
|
||||
* ssm_inz in declare()), so the gate is this buffer's right-hand `v_dim` columns and the
|
||||
* convolution reads the left-hand `conv_dim`. Both are `bcol` views, which is why every
|
||||
* consumer of either takes a row pitch. */
|
||||
ActFP8 in{}; /* [max_tok, conv_dim+v_dim] [q|k|v] then the output gate */
|
||||
rad_buf ab = 0; /* [max_tok, 2*n_head_v] the decay and beta inputs, bf16 */
|
||||
rad_buf q = 0; /* [max_tok, n_head_k, head_k] post-convolution, l2-normed */
|
||||
rad_buf k = 0; /* [max_tok, n_head_k, head_k] */
|
||||
rad_buf v = 0; /* [max_tok, n_head_v, head_v] */
|
||||
rad_buf gdec = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf beta = 0; /* [max_tok, n_head_v] */
|
||||
rad_buf kkt = 0; /* [max_tok, n_head_v, chunk] */
|
||||
ActFP8 o{}; /* [max_tok, n_head_v, head_v] -- RANK 3, see the header */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* in_qkv = nullptr; /* fp8 */
|
||||
const char* in_a = nullptr; /* bf16 */
|
||||
const char* in_b = nullptr; /* bf16 */
|
||||
const char* in_z = nullptr; /* fp8 */
|
||||
const char* conv1d = nullptr;
|
||||
const char* a_log = nullptr;
|
||||
const char* dt_bias = nullptr;
|
||||
const char* out_norm = nullptr;
|
||||
const char* out = nullptr; /* fp8 */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv_state = 0, kv_conv = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_ab = 0, w_conv = 0;
|
||||
/* The input was normed and quantised by the caller; this block declares no norm. */
|
||||
bool ext_in = false;
|
||||
rad_weight w_a_log = 0, w_dt_bias = 0, w_out_norm = 0;
|
||||
LinearFP8 in{}, out{};
|
||||
NormQuantFP8 nq_h{};
|
||||
QuantFP8 q_o{};
|
||||
|
||||
rad_op op_ab = 0;
|
||||
rad_op op_conv_prep = 0, op_kkt = 0, op_scan = 0, op_gnorm = 0; /* prefill */
|
||||
rad_op op_conv_update = 0, op_recur = 0; /* decode */
|
||||
/* `gdn_conv_recurrent_update`, if it resolves: the pair above as one launch, the convolution
|
||||
* computed in the recurrent update's prologue. 0 leaves the pair, which is declared either
|
||||
* way; cr_rows is the widest decode window the fold serves. */
|
||||
rad_op op_cr = 0;
|
||||
int64_t cr_rows = 0;
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
|
||||
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
|
||||
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
|
||||
* fold's two flags again, one boundary later, and they are separate for the same reason: a
|
||||
* block is declared without knowing what follows it. On EITHER wire -- the fused kernel
|
||||
* carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
|
||||
* about whether the collective has already been issued. */
|
||||
bool ar_out = false;
|
||||
/* ...and WHICH WIRES that consumer takes (ArOut, rad_fp8.h): the norm's by default, and a gated
|
||||
* residual's write says its own (HyperConn::ar_take). Set before declare; both sides then ask
|
||||
* ar_taken(g, T, ar_out, ar_out_take). */
|
||||
int ar_out_take = kArOutNorm;
|
||||
|
||||
|
||||
/* `fold` says the PREVIOUS block left its delta in `w.h.x` for this norm to add; `add_out`
|
||||
* says the NEXT one will not, so this block issues the trailing add itself. See rad_fp8.h. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
|
||||
bool fold = false, bool add_out = true,
|
||||
int ar_in = kArNone, bool ar_out_ = false);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int l,
|
||||
rad_kvgroup state, rad_kvgroup conv, const Wire& wire, const Src& s,
|
||||
bool fold, bool add_out,
|
||||
int ar_in, bool ar_out_) {
|
||||
g = geom;
|
||||
ar_out = ar_out_; cfg = c; w = wire; layer = l; kv_state = state; kv_conv = conv;
|
||||
if (cfg.n_head_k <= 0 || cfg.head_k <= 0 || cfg.n_head_v <= 0 || cfg.head_v <= 0 ||
|
||||
cfg.conv_width <= 0 || cfg.chunk <= 0)
|
||||
return RAD_E_INVAL;
|
||||
if (cfg.n_head_v % cfg.n_head_k != 0) {
|
||||
fprintf(stderr, "radiance: %lld value heads is not a multiple of %lld key heads\n",
|
||||
(long long)cfg.n_head_v, (long long)cfg.n_head_k);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* THE QUERY SCALE, AND IT IS NOT OPTIONAL. `gdn_chunk_scan` and `gdn_recurrent_update` both
|
||||
* carry a `scale` that multiplies the output -- o = scale * e^g Q S^T + ... -- and it defaults to
|
||||
* 1. FLA's chunk_gated_delta_rule defaults it to head_k^-0.5 and vllm-radiance passes exactly
|
||||
* that; llama.cpp's fused GDN does the same.
|
||||
*
|
||||
* IT LOOKS LIKE IT CANCELS AND IT DOES NOT. The scan's output goes straight into the gated RMS
|
||||
* norm, and an RMS norm divides a constant factor back out -- so scaling `o` by c should change
|
||||
* nothing. That argument is wrong here for one reason: the scan output of this model is around
|
||||
* 1e-6, `mean(o^2)` is then around 1e-12, and the norm's eps is 1e-6. eps DOMINATES the variance,
|
||||
* the norm degenerates into a fixed division by sqrt(eps), and the factor passes straight through
|
||||
* to the residual stream.
|
||||
*
|
||||
* Leaving it at 1 is visible end to end: the scan output comes out larger than the reference
|
||||
* implementations' by exactly sqrt(head_k), and with forty-eight of this model's sixty-four
|
||||
* layers delta net the residual stream then carries a delta-net contribution that many times
|
||||
* too large -- fluent grammar with no content. */
|
||||
const double q_scale = 1.0 / std::sqrt((double)cfg.head_k);
|
||||
|
||||
if (!cfg.act || (std::strcmp(cfg.act, "silu") != 0 && std::strcmp(cfg.act, "sigmoid") != 0)) {
|
||||
fprintf(stderr, "radiance: the delta net's output gate is '%s'; libr4d's gated norm "
|
||||
"implements silu and sigmoid and nothing else\n", cfg.act ? cfg.act : "(null)");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
const int64_t conv_dim = cfg.conv_dim();
|
||||
const int64_t ab_dim = cfg.ab_dim();
|
||||
|
||||
/* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
|
||||
*
|
||||
* A pre-norm model's block owns its own norm: one op that adds the previous block's delta into
|
||||
* the residual stream, normalises it and quantises it (rad_fp8.h's NormQuantFP8). A GATED
|
||||
* RESIDUAL model's does not -- arch/common/rad_block_hc.h's `hc_read` produces the block input
|
||||
* from a stream four times as wide, with a data-dependent mix the block has no way to compute,
|
||||
* and there is nothing left for a norm here to do. So this block takes `wire.h` as ALREADY
|
||||
* normed and quantised and declares no norm weight at all.
|
||||
*
|
||||
* `ar_in` is refused in that mode rather than ignored: the fused all-reduce lives INSIDE the
|
||||
* norm, so with no norm there is nowhere to fold it and a caller that asked would silently get
|
||||
* an unreduced input. It emits a standalone collective instead (`add_out`/`ar_out`). */
|
||||
ext_in = (s.norm == nullptr);
|
||||
if (ext_in) {
|
||||
if (!w.h.x || (!g.w_bf16 && (!w.h.q || !w.h.s)) || ar_in != kArNone) return RAD_E_INVAL;
|
||||
} else {
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), s.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
}
|
||||
/* The name maps ahead of the weights they name: a checkpoint is asked what a weight is
|
||||
* through its map, at the declaration. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ssm_ab.weight", l), { s.in_a, s.in_b }, 0));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_conv1d.weight", l), s.conv1d));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_a_log", l), s.a_log));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_dt.bias", l), s.dt_bias));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ssm_norm.weight", l), s.out_norm));
|
||||
/* The decay and beta projections, kept bf16 because the checkpoint kept them bf16 -- see the
|
||||
* header. Row-sharded with the value heads they belong to: a and b are concatenated along dim 0
|
||||
* so rank r owns rows [r*n_head_v, (r+1)*n_head_v) of EACH half, which is what the two-part
|
||||
* row split says and what a contiguous slice of the concatenation would not give. */
|
||||
w_ab = decl_w(b, nm.f("blk.%d.ssm_ab.weight", l), RAD_BF16, {ab_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{cfg.n_head_v, cfg.n_head_v});
|
||||
/* The depthwise convolution is per channel, so it shards with the channels it convolves --
|
||||
* and those channels are [q|k|v], three groups in one stored tensor, so the split is theirs. */
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ssm_conv1d.weight", l), RAD_BF16,
|
||||
{conv_dim, cfg.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{cfg.k_dim(), cfg.k_dim(), cfg.v_dim()});
|
||||
w_a_log = decl_w(b, nm.f("blk.%d.ssm_a_log", l), RAD_F32, {cfg.n_head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_dt_bias = decl_w(b, nm.f("blk.%d.ssm_dt.bias", l), RAD_F32, {cfg.n_head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l));
|
||||
w_out_norm = decl_w(b, nm.f("blk.%d.ssm_norm.weight", l), RAD_F32, {cfg.head_v},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
|
||||
/* One norm and one quantise of the normed hidden state, in one op; the qkv and z
|
||||
* projections both read it. rad_fp8.h's NormQuantFP8 says why they are not two. */
|
||||
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));
|
||||
/* TWO CHECKPOINT TENSORS, FOUR PROJECTIONS, ONE GEMM. in_proj_qkv is [q|k|v] stacked along
|
||||
* dim 0 and in_proj_z is the output gate; both read the SAME normed, quantised hidden state
|
||||
* and differ only in their rows, so they are one weight here and one launch at step time.
|
||||
*
|
||||
* WHY ONE CALL AND NOT TWO. The decode GEMM is bandwidth-bound but not at small N: two calls
|
||||
* at 5120 and 3072 rows cost more between them than one call at 8192, because each pays its
|
||||
* own ramp and tail on top of its launch. Over this model's delta-net layers that adds up to a
|
||||
* measurable share of a decode step. It is bit-identical: nothing about a row's arithmetic
|
||||
* changes, and both extents are already past the split-K threshold so the summation order does
|
||||
* not move either.
|
||||
*
|
||||
* THE ROW PARTS ARE THE WHOLE POINT. Rank r must own its slice of EACH of q, k, v and z, so
|
||||
* the shard is declared as four parts and not as one contiguous cut -- which would give rank 0
|
||||
* all of q, all of k and a third of v, a well-formed wrong model. */
|
||||
RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
|
||||
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }));
|
||||
/* NOT SLICED, and why it could need to be is worth keeping. This is a 96-column bf16 GEMM --
|
||||
* half a percent of the layer's projection bytes -- and a bf16 kernel for this shape that
|
||||
* stopped at M = 64 would leave a hole in its bucket table above 64. Since every op in a step
|
||||
* is issued at the same token count, that one hole would cap the prefill chunk of the entire
|
||||
* 27B model at 64 tokens, and the workaround is a launch per 64 rows in every GDN layer. The
|
||||
* cap was a launcher guard the kernel does not need: MT row tiles live in a block and grid.y
|
||||
* covers the rest, so M is general, and with the guard raised this is one launch.
|
||||
*
|
||||
* AT DECODE THE COST IS THE LAUNCH COUNT, not the arithmetic. `gemm_nt` is the most-dispatched
|
||||
* kernel in a decode step and it is almost entirely fixed cost, spread over three separate
|
||||
* small per-layer projections that all read the same activation: the MoE router (one a layer),
|
||||
* the shared expert's gate (one a layer, RANK 0 ONLY, so on the rank the all-reduce is already
|
||||
* waiting for) and this a|b (one a GDN layer).
|
||||
*
|
||||
* Fusing them is the lever and it is not a small one: they read the same activation but hold
|
||||
* different weights, so a merge wants either contiguous weights -- a re-convert, which is
|
||||
* ruled out -- or a GROUPED gemm_nt taking a table of weight pointers the way moe_gemm_q
|
||||
* does. */
|
||||
op_ab = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", ab_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_ab)), {w.h.x}, {w.ab});
|
||||
|
||||
/* ---- the chunked path. Unchanged from the bf16 block except that `a` and `b_gate` are views
|
||||
* of `ab` rather than of the projection row's tail. */
|
||||
op_conv_prep = rw(b, RAD_OP(b, "gdn_conv_prep",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_INT("chunk", cfg.chunk),
|
||||
RAD_INT("conv_width", cfg.conv_width)),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias)),
|
||||
{w.in.x, w.ab}, {w.q, w.k, w.v, w.gdec, w.beta});
|
||||
op_kkt = rw(b, RAD_OP(b, "gdn_kkt_solve",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.beta, w.gdec}, {w.kkt});
|
||||
op_scan = rw(b, RAD_OP(b, "gdn_chunk_scan",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v), RAD_F64("scale", q_scale)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q, w.k, w.v, w.kkt, w.gdec, w.beta}, {w.o.x});
|
||||
op_gnorm = rw(b, RAD_OP(b, "gdn_gated_rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", cfg.head_v),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act)),
|
||||
RAD_WEIGHTS(w_out_norm)),
|
||||
{w.o.x, w.in.x}, {w.o.x});
|
||||
|
||||
/* ---- the recurrent path. */
|
||||
op_conv_update = rw(b, RAD_OP(b, "gdn_conv_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width)),
|
||||
RAD_WEIGHTS(w_conv)),
|
||||
{w.in.x}, {w.q, w.k, w.v});
|
||||
/* WHAT THE STATE CACHE MEANS, and it is not derivable from the operands. libr4d's recurrent
|
||||
* update has two state contracts. PER-CANDIDATE writes one full state per candidate token and
|
||||
* needs `1 + n_spec` distinct slots; ANCHOR keeps one committed state a sequence and replays
|
||||
* the accepted prefix onto it out of a scratch slot, which is two slots whatever the depth.
|
||||
* Same `o` either way, and a completely different `state` -- so a reference that implements one
|
||||
* of them and is handed the other computes a correct answer to the other question.
|
||||
*
|
||||
* The engine already chooses: KVGroupPlan::state_copies is 2 when the deployment speculates
|
||||
* and 1 when it does not, which is exactly this condition. Saying it here is what lets a
|
||||
* reference DECLINE the form it does not implement instead of disagreeing with it, and what
|
||||
* lets the kernel refuse a caller whose pool was sized for the other one. */
|
||||
op_recur = rw(b, RAD_OP(b, "gdn_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("n_head_v", cfg.n_head_v),
|
||||
RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.q, w.k, w.v, w.ab, w.in.x}, {w.o.x});
|
||||
/* The epilogue's codes, for an fp8 or int8 out-projection -- the int8 pair when the model feeds
|
||||
* it (ActFP8::q8_fed), whose dtype picks the kernel's quantiser; a bf16 one reads `o.x` and
|
||||
* nothing else, and the operands are left absent. */
|
||||
if (op_recur && w.o.cq()) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_recur, oq, 2));
|
||||
}
|
||||
/* THE FOLD, over the same weights and caches. Its window is a register preload, so the band
|
||||
* stops at eight tokens a sequence; not RAD_ARCH_TRY, since a plugin without the row is the
|
||||
* ordinary case and the pair runs. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 8 ? g.max_tok : 8;
|
||||
op_cr = rw(b, RAD_OP(b, "gdn_conv_recurrent_update",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, hi), RAD_INT("head_k", cfg.head_k),
|
||||
RAD_INT("head_v", cfg.head_v),
|
||||
RAD_INT("conv_width", cfg.conv_width),
|
||||
RAD_INT("n_head_v", cfg.n_head_v), RAD_F64("scale", q_scale),
|
||||
RAD_F64("eps", g.eps), RAD_STR("act", cfg.act),
|
||||
RAD_STR("state_form",
|
||||
g.max_spec > 0 ? "anchor" : "per_candidate")),
|
||||
RAD_WEIGHTS(w_conv, w_a_log, w_dt_bias, w_out_norm)),
|
||||
{w.in.x, w.ab}, {w.o.x});
|
||||
if (op_cr && w.o.cq()) {
|
||||
const rad_buf oq[2] = { w.o.cq(), w.o.cs() };
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_cr, oq, 2));
|
||||
}
|
||||
if (op_cr) cr_rows = hi;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
|
||||
RAD_ARCH_TRY(out.declare(b, nm, g, nm.f("blk.%d.ssm_out", l), g.n_embd, v_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { s.out }, w.o, w.h.x));
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void GdnFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* st = kv_batch(batch, kv_state);
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
|
||||
const int32_t* st_idx = st ? st->state_index : nullptr;
|
||||
/* HOW MANY SLOTS THE ROW NAMES. One is the state; a linear kernel serving speculation
|
||||
* asks for scratch beside it and the manager sizes the row to suit (RadKVGroupBatch).
|
||||
* The block passes the row through and does not read it. */
|
||||
const int64_t st_w = st && st->state_index_pitch > 0 ? st->state_index_pitch : 1;
|
||||
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const int64_t H = cfg.n_head_v;
|
||||
/* The two halves of `w.in.x`: the convolution's [q|k|v] and the output gate behind it. */
|
||||
const int64_t conv_dim = cfg.conv_dim();
|
||||
const int64_t v_dim = cfg.v_dim();
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
in.step(c, w.h, w.in.x, T);
|
||||
RAD_ISSUE_N(c, op_ab, T, brows(w.h.x, T), RAD_W(w_ab), brows(w.ab, T));
|
||||
|
||||
/* THE TWO PATHS, EACH OVER ITS OWN RUN OF SEQUENCES.
|
||||
*
|
||||
* The step is sorted decode-first, so the decode rows are sequences [0, D) holding tokens
|
||||
* [0, DT) and the prefill chunks are sequences [D, S) holding the rest. Each path is issued
|
||||
* over its own half and a pure step issues exactly one of them.
|
||||
*
|
||||
* THE PER-SEQUENCE ARRAYS MOVE AND THE TOKEN OPERANDS DO NOT. Every kernel here takes
|
||||
* cu_seqlens and derives both its grid and its rows from it -- N is cu's own length minus one
|
||||
* and row zero of a sequence is the ABSOLUTE cu[n] -- so the prefill half is addressed by
|
||||
* handing it `cu + D` while leaving q, k, v and the rest at their base. Offsetting those too
|
||||
* would count the displacement twice. The decode half is the prefix, so it narrows instead:
|
||||
* its cu ends at DT and its token operands are cut to DT rows, which agree because they are
|
||||
* the same number.
|
||||
*
|
||||
* The two ops that take no cu -- the gated norm and the standalone quantiser -- are per TOKEN,
|
||||
* so they take a row slice and are the only place DT appears as an offset.
|
||||
*
|
||||
* What this buys is that a mixed step does not run the chunked path over a sequence that is
|
||||
* only decoding. That path commits the state directly and has no num_accepted operand, so a
|
||||
* draft verified on it could not be rolled back and the scheduler would have to refuse one in
|
||||
* every mixed step -- on an agentic load, a large share of all decode rows. */
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
/* And the band the decode half selects on. max_q_len over a mixed step is the prefill chunk;
|
||||
* over a pure decode step it is already the right number, so a batch that leaves
|
||||
* max_q_len_decode zero still selects correctly there. */
|
||||
const int32_t qd = batch->phase == RAD_PHASE_MIXED ? batch->max_q_len_decode : batch->max_q_len;
|
||||
const int64_t P = S - D;
|
||||
const int64_t PT = T - DT;
|
||||
const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */
|
||||
|
||||
if (D > 0 && op_cr && qd <= cr_rows) {
|
||||
RAD_ISSUE_N(c, op_cr, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
praw(cv_idx, RAD_I32, D),
|
||||
bcol(w.ab, 0, H, DT), bcol(w.ab, H, H, DT),
|
||||
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
} else if (D > 0) {
|
||||
RAD_ISSUE_N(c, op_conv_update, qd,
|
||||
bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer),
|
||||
praw(cv_idx, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT));
|
||||
RAD_ISSUE_N(c, op_recur, qd,
|
||||
brows(w.q, DT), brows(w.k, DT), brows(w.v, DT),
|
||||
bcol(w.ab, 0, H, DT), bcol(w.ab, H, H, DT),
|
||||
RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_state, layer),
|
||||
praw2(st_idx, RAD_I32, D, st_w), praw(batch->num_accepted, RAD_I32, D),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
bcol(w.in.x, conv_dim, v_dim, DT), RAD_W(w_out_norm), brows(w.o.x, DT),
|
||||
w.o.cq() ? brows(w.o.cq(), DT) : RAD_NONE,
|
||||
w.o.cq() ? brows(w.o.cs(), DT) : RAD_NONE);
|
||||
}
|
||||
|
||||
if (P > 0) {
|
||||
RAD_ISSUE(c, op_conv_prep,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias),
|
||||
kv_cache(kv_conv, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE(c, op_kkt,
|
||||
brows(w.k, T), brows(w.beta, T), brows(w.gdec, T),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(w.kkt, T));
|
||||
RAD_ISSUE(c, op_scan,
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.kkt, T),
|
||||
brows(w.gdec, T), brows(w.beta, T),
|
||||
kv_cache(kv_state, layer), praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
brows(w.o.x, T), kv_cache(kv_state, layer),
|
||||
praw2(st_idx ? st_idx + D * st_w : nullptr, RAD_I32, P, st_w));
|
||||
/* PER TOKEN, so this one is a row slice and not a sequence sub-array. Over the decode
|
||||
* rows the recurrent kernel has already applied the gate in its own epilogue. */
|
||||
RAD_ISSUE_N(c, op_gnorm, PT,
|
||||
brow_slice(w.o.x, DT, PT, v_dim),
|
||||
bcol_at(w.in.x, DT, in_w, conv_dim, v_dim, PT),
|
||||
RAD_W(w_out_norm), brow_slice(w.o.x, DT, PT, v_dim));
|
||||
/* PREFILL STILL QUANTISES SEPARATELY, and only prefill. The decode kernel folds the
|
||||
* quantiser into its own epilogue -- see the operand list on gdn_recurrent_update -- so
|
||||
* issuing this over those rows would overwrite the same bytes with the same values for a
|
||||
* launch a layer, in every delta-net layer, for nothing. The chunked
|
||||
* scan has no such epilogue: its workgroup is a chunk, not a row, and the group's amax is
|
||||
* not a reduction it can do. */
|
||||
q_o.step(c, T, DT, PT);
|
||||
}
|
||||
|
||||
out.step(c, w.o, w.h.x, T);
|
||||
if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_GDN_FP8_H */
|
||||
@@ -0,0 +1,402 @@
|
||||
/* rad_block_hc.h -- the GATED RESIDUAL, which is what Qwen4-Exp has instead of a pre-norm and a
|
||||
* residual add.
|
||||
*
|
||||
* ============================== THE RESIDUAL STREAM IS `hc` TIMES AS WIDE ==============================
|
||||
*
|
||||
* hidden_size 2560 at hc_count 4 is a 10240-wide stream. It is entered as FOUR IDENTICAL COPIES of
|
||||
* the embedding, carried through all 48 layers, and collapsed once at the end by a connection with
|
||||
* no write half. Every block -- attention or delta net, then the feed-forward, so 96 of them --
|
||||
* reads a 2560 mix of the four streams and writes its output back into all four, and both halves
|
||||
* are data-dependent:
|
||||
*
|
||||
* read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one 10240 gain, `1 + w`
|
||||
* g = sigmoid(mix_up @ silu(mix_down @ N / hc))
|
||||
* x = mean over the four streams of g * N -> the block's input
|
||||
* inj[s] = 2 * sigmoid(inject_w[s] . N / hc) -> four scalars in (0, 2)
|
||||
* write h[s] += inj[s] * y for each stream s
|
||||
*
|
||||
* docs/OPS.md's `hc_read` / `hc_write` rows carry the same statement and name the three choices a
|
||||
* second implementation has to match (the mix is a MEAN; each gate argument has its own `/ hc`;
|
||||
* the write adds into the UNNORMED stream).
|
||||
*
|
||||
* ============================== WHY IT IS A BLOCK AND NOT TWO CALLS ==============================
|
||||
*
|
||||
* Because the two halves share a weight set and a buffer set, and because the pairing is the
|
||||
* invariant: a read whose `inj` nothing consumes is a bug, and a write whose `inj` came from a
|
||||
* different read is a worse one. One struct declares both, holds the four weights once, and gives
|
||||
* the plugin a `read()` and a `write()` that cannot be mismatched.
|
||||
*
|
||||
* ============================== WHAT IT COSTS, AND WHERE THAT GOES ==============================
|
||||
*
|
||||
* The arithmetic is nothing: 2 x 10240 x 320 plus 4 x 10240 is 6.6M MACs a token against the 5.9M
|
||||
* of one expert pair. The LAUNCHES are the cost. A kernel costs a dispatch whatever it computes,
|
||||
* and there are 96 connections a step, so every extra op in a connection is 96 more dispatches --
|
||||
* a real share of a decode budget measured in tens of milliseconds.
|
||||
*
|
||||
* That is why the read emits the fp8 form of `x` itself rather than leaving a `quant_act_fp8`
|
||||
* behind it, and it is why the write is a candidate to be FOLDED INTO THE PRODUCING BLOCK'S
|
||||
* EPILOGUE later (this tree's own rule: fold the quantiser into the producer, and quantise the
|
||||
* bf16 that was written). Neither the read's five ops nor the write's one are on the table as
|
||||
* separate launches.
|
||||
*
|
||||
* ============================== WHAT IS NOT SHARDED ==============================
|
||||
*
|
||||
* Nothing here. The residual stream is replicated on every rank (spec §9) and so is every weight
|
||||
* in this file: 6.7 MB a connection at bf16, 1.3 GB over the model, which is the price of not
|
||||
* putting a collective inside the connection. A sharded low-rank gate would need an all-reduce
|
||||
* between `mix_down` and `mix_up` -- 96 more collectives a step, on 1280 bytes each, and a decode
|
||||
* all-reduce is mostly fixed cost whatever the message.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_HC_H
|
||||
#define RAD_BLOCK_HC_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding.
|
||||
*
|
||||
* One launch for the whole step, and it is its own op rather than part of the embedding lookup
|
||||
* because that op's weight is [vocab, n_embd] and its output width is n_embd -- a wide output
|
||||
* would be a different weight shape. The copies are identical here and diverge at the first
|
||||
* connection, since every block writes into all hc streams with a DIFFERENT per-branch gain. */
|
||||
struct HcEnter {
|
||||
Geom g{};
|
||||
int64_t hc = 0;
|
||||
rad_buf x = 0, h = 0;
|
||||
rad_op op = 0;
|
||||
|
||||
int declare(RadBuilder* b, const Geom& geom, int64_t hc_, rad_buf x_, rad_buf h_) {
|
||||
g = geom; hc = hc_; x = x_; h = h_;
|
||||
if (hc <= 1 || !x || !h) return RAD_E_INVAL;
|
||||
op = rw(b, RAD_OP(b, "hc_enter",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", hc), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{x}, {h});
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
void step(RadCtx* c_, int64_t T) const {
|
||||
RAD_ISSUE_N(c_, op, T, brows(x, T), brows(h, T));
|
||||
}
|
||||
};
|
||||
|
||||
struct HyperConn {
|
||||
struct Config {
|
||||
int64_t hc = 0; /* streams; the reference refuses hc <= 1 and so does this */
|
||||
int64_t lowrank = 0; /* the read gate's waist */
|
||||
/* Whether this connection has a WRITE half. The final mixer does not: it collapses the
|
||||
* wide stream into the one hidden state the lm_head reads and nothing follows it. */
|
||||
int inject = 1;
|
||||
/* Whether the read also emits the block input's fp8 codes. The trunk connections all do;
|
||||
* the mixer does not, because its consumer is the lm_head, which reads a bf16 input. */
|
||||
int quant = 1;
|
||||
/* Whether the WRITE also carries the all-reduce of the block's output, which the block in
|
||||
* front then skips on every step takes_ar() answers yes to. The block's partial sum and the
|
||||
* write's input are the same buffer, so the reduction moves into the write's kernel and
|
||||
* the pair's second launch disappears. */
|
||||
int reduce = 0;
|
||||
/* Whether the read also emits the HADAMARD-ROTATED fp8 codes of the block input, for a
|
||||
* consumer whose weight carries the rotation (MoeFP8's rotated expert plane). They ride in
|
||||
* the plain codes' finisher, so this needs `quant`, and the consumer then declares no
|
||||
* quantiser of its own -- one dependent launch fewer a connection. */
|
||||
int rotate = 0;
|
||||
/* Whether those codes are INT8 (the input's q8/s8 pair) rather than E4M3 (q/s): a model
|
||||
* whose trunk linears are int8 (LinearFP8::i8) reads them there, so the read writing them
|
||||
* is one quantiser launch fewer a consumer. The rotated twin stays E4M3 either way -- it
|
||||
* is the routed experts' operand. */
|
||||
int codes_i8 = 0;
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, in place */
|
||||
ActFP8 x{}; /* [max_tok, n_embd] the block input; q/s unused if !quant */
|
||||
rad_buf inj = 0; /* [max_tok, hc] the per-branch write gains */
|
||||
rad_buf rq = 0; /* [max_tok, n_embd] the rotated codes, when `rotate` */
|
||||
rad_buf rs = 0; /* [max_tok, n_embd/128] and their scales */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* hc_norm.weight, [hc*n_embd] */
|
||||
const char* mix_down = nullptr; /* input_mix_weight_down.weight, [lowrank, hc*n_embd] */
|
||||
const char* mix_up = nullptr; /* input_mix_weight_up.weight, [hc*n_embd, lowrank] */
|
||||
const char* inject_w = nullptr; /* block_inject_weight.weight, [hc, hc*n_embd] */
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
|
||||
rad_weight w_norm = 0, w_down = 0, w_up = 0, w_inj = 0;
|
||||
/* Whether the two mixing matrices are E4M3 rows with a scale a group of each row rather than
|
||||
* bf16 -- OPS.md's `mix` -- which is their encoding's to say, read at declare. */
|
||||
bool mix_e4m3 = false;
|
||||
rad_op op_read = 0, op_write = 0;
|
||||
/* The write with the all-reduce folded in; 0 when not asked for or when no kernel serves it.
|
||||
* `op_ar_write6` is the same write on the ROTATED 6-BIT wire, declared only where a step can
|
||||
* reach that wire -- an install that accepts a lossy payload -- and issued on exactly the steps
|
||||
* ar_wire_is_exact answers no to: at a prefill chunk that is every all-reduce the trunk makes,
|
||||
* and the payload is 2.6x smaller than the exact one. */
|
||||
rad_op op_ar_write = 0;
|
||||
rad_op op_ar_write6 = 0;
|
||||
/* AND WITH THE MoE GATHER FOLDED IN FRONT OF THAT: the block behind this write leaves its
|
||||
* routed experts' rows unsummed, and the reduction's message is their sum. Declared by
|
||||
* declare_gather() after the block, whose buffers it reads; `gather_rows` is the bound it serves
|
||||
* and 0 when it was not declared or no kernel serves it (see gather_taken). */
|
||||
struct GatherSrc {
|
||||
rad_buf ye = 0, ew = 0, sorted = 0, sh = 0, sg = 0; /* sh and sg: the shared arm, or 0 */
|
||||
int64_t top_k = 0;
|
||||
int64_t rows = 0; /* one pass of the block, at most */
|
||||
};
|
||||
GatherSrc gsrc{};
|
||||
rad_op op_ar_gather_write = 0, op_ar_gather_write6 = 0;
|
||||
int64_t gather_rows = 0, gather_rows6 = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* THE REDUCING WRITE THIS STEP ISSUES, on the wire its message goes out on; 0 where that wire
|
||||
* has no fused form, and the block's own collective then runs in front of the plain write. */
|
||||
rad_op ar_write(int64_t T) const {
|
||||
return ar_wire_is_exact(g, T) ? op_ar_write : op_ar_write6;
|
||||
}
|
||||
/* WHETHER THIS STEP'S WRITE REDUCES THE BLOCK'S OUTPUT. The block in front asks the same
|
||||
* question of the same T -- ar_taken with ar_take() -- before skipping its own collective. */
|
||||
bool takes_ar(int64_t T) const { return ar_write(T) != 0; }
|
||||
/* What that block is told: which wires this write takes. The rotated form is declared only
|
||||
* beside the exact one, so the two together take every message. */
|
||||
int ar_take() const { return op_ar_write6 ? kArOutBoth : kArOutExact; }
|
||||
bool takes_gather(int64_t T) const {
|
||||
return takes_ar(T) && gather_taken(g, T, gather_rows, gather_rows6);
|
||||
}
|
||||
|
||||
/* `name` is the declared prefix -- "blk.7.attn_hc" -- and `src` the checkpoint side. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
|
||||
const Config& cfg, const Wire& wire, const Src& src);
|
||||
|
||||
int declare_gather(RadBuilder* b, const GatherSrc& src);
|
||||
|
||||
void read (RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const;
|
||||
};
|
||||
|
||||
inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const char* name,
|
||||
const Config& cfg, const Wire& wire, const Src& src) {
|
||||
g = geom; c = cfg; w = wire;
|
||||
if (c.hc <= 1 || c.lowrank <= 0 || g.n_embd <= 0) {
|
||||
fprintf(stderr, "radiance: %s: hc = %lld, lowrank = %lld -- a gated residual needs hc > 1 "
|
||||
"and a positive waist\n",
|
||||
name, (long long)c.hc, (long long)c.lowrank);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!src.norm || !src.mix_down || !src.mix_up) return RAD_E_INVAL;
|
||||
/* An inject WEIGHT with no `inj` buffer, or the reverse, is a connection whose two halves
|
||||
* disagree about whether there is a write. Refused here rather than discovered as an
|
||||
* all-rejected draft three stages later. */
|
||||
if (c.inject && (!src.inject_w || !w.inj)) {
|
||||
fprintf(stderr, "radiance: %s: inject is on but %s is missing\n", name,
|
||||
src.inject_w ? "the inj buffer" : "block_inject_weight");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!c.inject && (src.inject_w || w.inj)) {
|
||||
fprintf(stderr, "radiance: %s: inject is off, so neither block_inject_weight nor an inj "
|
||||
"buffer may be passed\n", name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (c.quant && (c.codes_i8 ? (!w.x.q8 || !w.x.s8) : (!w.x.q || !w.x.s))) return RAD_E_INVAL;
|
||||
if (c.rotate && (!c.quant || !w.rq || !w.rs)) {
|
||||
fprintf(stderr, "radiance: %s: the rotated codes need the plain ones (quant) and the "
|
||||
"rq/rs pair on the wire\n", name);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!w.h || !w.x.x) return RAD_E_INVAL;
|
||||
|
||||
const int64_t HN = hn();
|
||||
|
||||
/* The name maps first: they are how the model is asked what each weight is. */
|
||||
const char* nn = nm.f("%s_norm.weight", name);
|
||||
const char* dn = nm.f("%s_down.weight", name);
|
||||
const char* un = nm.f("%s_up.weight", name);
|
||||
const char* in = nm.f("%s_inject.weight", name);
|
||||
RAD_ARCH_TRY(map_copy(b, nn, src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, dn, src.mix_down));
|
||||
RAD_ARCH_TRY(map_copy(b, un, src.mix_up));
|
||||
if (c.inject) RAD_ARCH_TRY(map_copy(b, in, src.inject_w));
|
||||
|
||||
/* THE MIXING MATRICES ARE WHATEVER THEIR ENCODING IS: bf16, or E4M3 rows with a scale a
|
||||
* group of each row -- lowrank 320 is 2.5 scale blocks, so a 128x128 tile cannot cover them.
|
||||
* Each is declared over every plane it has, at the codes' dtype, and the read's kernel takes
|
||||
* codes and scales together. The two are one format or the read has no kernel. */
|
||||
const uint32_t mdt = weight_codes_dtype(b, dn, RAD_BF16);
|
||||
if (weight_codes_dtype(b, un, RAD_BF16) != mdt || (mdt != RAD_BF16 && mdt != RAD_F8E4M3)) {
|
||||
fprintf(stderr, "radiance: %s: the mixing matrices are %s and %s; a connection reads both "
|
||||
"as bf16 or both as E4M3 rows\n", name,
|
||||
rad_dtype_name(mdt), rad_dtype_name(weight_codes_dtype(b, un, RAD_BF16)));
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
mix_e4m3 = mdt == RAD_F8E4M3;
|
||||
|
||||
/* F32 like every other norm gain in this tree: 10240 numbers read once a connection, and the
|
||||
* norm's arithmetic is f32 regardless, so narrowing them buys nothing. */
|
||||
w_norm = decl_w(b, nn, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_down = decl_w(b, dn, mdt, {c.lowrank, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_model());
|
||||
w_up = decl_w(b, un, mdt, {HN, c.lowrank}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_model());
|
||||
if (c.inject)
|
||||
w_inj = decl_w(b, in, RAD_BF16, {c.hc, HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_model());
|
||||
if (!w_norm || !w_down || !w_up || (c.inject && !w_inj)) return RAD_E_INVAL;
|
||||
|
||||
/* `inject` and `group` are declared even when off, with the value 0, because a kernel row
|
||||
* bands on them: a fused read that writes four gates is a different kernel from one that does
|
||||
* not, and the resolver needs to be able to say so. An ABSENT key fails a constraint, so
|
||||
* leaving them out would make both rows unselectable rather than one. */
|
||||
/* RAD_WEIGHTS expands to TWO arguments -- the array and its length -- so it cannot sit in a
|
||||
* ternary, and the four-or-three choice is made by building the array. The absent inject
|
||||
* weight is a SHORTER list and not a zero handle: rad_plugin.h's absent-operand rule is about
|
||||
* the launch, but a declared weight of 0 is a declaration failure here. */
|
||||
const rad_weight wts[4] = { w_norm, w_down, w_up, w_inj };
|
||||
const int n_wts = c.inject ? 4 : 3;
|
||||
|
||||
/* The write set is positional and the optional OUTPUTS are the tail, so an absent one shortens
|
||||
* the list exactly as an absent weight does. The read's outputs are x, inj?, q?, scale? and
|
||||
* both switches drop a suffix, never a middle -- which is why the schema puts inj before the
|
||||
* quantiser's pair rather than after. */
|
||||
rad_buf wr[6] = { w.x.x, 0, 0, 0, 0, 0 };
|
||||
int n_wr = 1;
|
||||
if (c.inject) wr[n_wr++] = w.inj;
|
||||
if (c.quant) { wr[n_wr++] = c.codes_i8 ? w.x.q8 : w.x.q; wr[n_wr++] = c.codes_i8 ? w.x.s8 : w.x.s; }
|
||||
if (c.rotate) { wr[n_wr++] = w.rq; wr[n_wr++] = w.rs; }
|
||||
|
||||
op_read = RAD_OP(b, "hc_read",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("lowrank", c.lowrank),
|
||||
RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("wadd", g.wadd), RAD_INT("inject", c.inject ? 1 : 0),
|
||||
RAD_INT("group", c.quant ? RAD_FP8_BLOCK : 0),
|
||||
RAD_INT("rotate", c.rotate ? 1 : 0),
|
||||
RAD_STR("mix", mix_e4m3 ? "e4m3" : "bf16")),
|
||||
wts, n_wts);
|
||||
if (!op_read) return RAD_E_INVAL;
|
||||
{
|
||||
const rad_buf rd[1] = { w.h };
|
||||
rad_op_reads (b, op_read, rd, 1);
|
||||
rad_op_writes(b, op_read, wr, n_wr);
|
||||
}
|
||||
|
||||
if (c.inject) {
|
||||
op_write = rw(b, RAD_OP(b, "hc_write",
|
||||
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.x.x, w.inj, w.h}, {w.h});
|
||||
if (!op_write) return RAD_E_INVAL;
|
||||
/* A handle that did not resolve is 0 and not an error: a backend without the fused kernel
|
||||
* keeps the pair, and takes_ar() then answers no on every step. */
|
||||
if (c.reduce && g.world == 2)
|
||||
op_ar_write = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
|
||||
if (op_ar_write && !g.wire_exact)
|
||||
op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("wire", 6)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
|
||||
if (!op_ar_write || src.top_k <= 0 || !src.ye || !src.ew || !src.sorted) return RAD_OK;
|
||||
const bool shared = src.sh && src.sg;
|
||||
gsrc = src;
|
||||
/* EVERY ROW COUNT ONE PASS CARRIES, prefill chunks included: the kernel reads its slots from
|
||||
* an LDS table at a decode step and from an inverse table at a chunk, where the gather's reads
|
||||
* then run beside the reduction's push instead of in a launch of their own. */
|
||||
int64_t rows = src.rows;
|
||||
if (rows > g.max_tok) rows = g.max_tok;
|
||||
if (rows < 1) return RAD_OK;
|
||||
const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg };
|
||||
const rad_buf wr[2] = { w.x.x, w.h };
|
||||
/* One op a wire, as the write itself: the rotated form beside the rotated write only. A handle
|
||||
* that did not resolve is 0 and not an error: the block keeps its gather and this write keeps
|
||||
* the reduction alone, and that wire's bound stays 0 so both say so. */
|
||||
op_ar_gather_write = RAD_OP(b, "ar_gather_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none")),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_ar_gather_write) {
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write, rd, shared ? 8 : 6));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write, wr, 2));
|
||||
gather_rows = rows;
|
||||
}
|
||||
if (op_ar_write6) {
|
||||
op_ar_gather_write6 = RAD_OP(b, "ar_gather_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none"),
|
||||
RAD_INT("wire", 6)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_ar_gather_write6) {
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write6, rd, shared ? 8 : 6));
|
||||
RAD_ARCH_TRY(rad_op_writes(b, op_ar_gather_write6, wr, 2));
|
||||
gather_rows6 = rows;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
(void)T;
|
||||
const int64_t HN = hn();
|
||||
RAD_ISSUE_N(c_, op_read, rows,
|
||||
brow_slice(w.h, r0, rows, HN), RAD_W(w_norm), RAD_W(w_down), RAD_W(w_up),
|
||||
c.inject ? RAD_W(w_inj) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
c.inject ? brow_slice(w.inj, r0, rows, c.hc) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.q8 : w.x.q, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.quant ? brow_slice(c.codes_i8 ? w.x.s8 : w.x.s, r0, rows,
|
||||
fp8_blocks(g.n_embd)) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rq, r0, rows, g.n_embd) : RAD_NONE,
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* `y` is the block's output, and it is `w.x.x` -- the same buffer the read wrote the block's INPUT
|
||||
* into. Every block in this tree leaves its delta in the activation its norm produced, so the
|
||||
* write reads it there; the input is dead by then. */
|
||||
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (!op_write) return;
|
||||
if (takes_gather(T)) {
|
||||
const int64_t k = gsrc.top_k;
|
||||
const bool shared = gsrc.sh && gsrc.sg;
|
||||
RAD_ISSUE_N(c_, ar_wire_is_exact(g, T) ? op_ar_gather_write : op_ar_gather_write6, rows,
|
||||
brows(gsrc.ye, rows * k), brow_slice(gsrc.ew, r0, rows, k),
|
||||
brows(gsrc.sorted, rows * k),
|
||||
shared ? brow_slice(gsrc.sh, r0, rows, g.n_embd) : RAD_NONE,
|
||||
shared ? brow_slice(gsrc.sg, r0, rows, 1) : RAD_NONE,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.inj, r0, rows, c.hc),
|
||||
brow_slice(w.h, r0, rows, hn()));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c_, takes_ar(T) ? ar_write(T) : op_write, rows,
|
||||
brow_slice(w.x.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.inj, r0, rows, c.hc),
|
||||
brow_slice(w.h, r0, rows, hn()));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_HC_H */
|
||||
@@ -0,0 +1,123 @@
|
||||
/* rad_block_mlp.h -- one SwiGLU feed-forward block, bf16 operands.
|
||||
*
|
||||
* rmsnorm -> gate_up gemm -> silu_mul -> down gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* gate and up are one weight and one GEMM. That is a convert-time fusion the plugin owns (spec
|
||||
* §2.4): the container ships ffn_gate.weight and ffn_up.weight, the map concatenates them along
|
||||
* dim 0, and silu_mul splits [M, 2n] back into gate times up. It buys one GEMM launch instead of
|
||||
* two and one movement unit instead of two.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MLP_H
|
||||
#define RAD_BLOCK_MLP_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MlpBF16 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the down-projection output */
|
||||
rad_buf gate_up = 0; /* [max_tok, 2 * n_ff] */
|
||||
rad_buf ffn = 0; /* [max_tok, n_ff] */
|
||||
};
|
||||
|
||||
/* Checkpoint-side names for one layer. The plugin owns the spelling because it is the only
|
||||
* component that knows both sides of the map (spec §2.4), and one architecture arrives as
|
||||
* `model.language_model.layers.N.mlp.*` and another as `blk.N.ffn_*`. */
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* post_attention_layernorm.weight */
|
||||
const char* gate = nullptr;
|
||||
const char* up = nullptr;
|
||||
const char* down = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_gate_up = 0, w_down = 0;
|
||||
rad_op op_norm = 0, op_gate_up = 0, op_act = 0, op_down = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int MlpBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l;
|
||||
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", l), { src.gate, src.up }, 0));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_down.weight", l), src.down));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up.weight", l), RAD_BF16, {2 * g.n_ff, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0, {g.n_ff, g.n_ff});
|
||||
w_down = decl_w(b, nm.f("blk.%d.ffn_down.weight", l), RAD_BF16, {g.n_embd, g.n_ff},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
op_gate_up = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_gate_up)),
|
||||
{w.h}, {w.gate_up});
|
||||
|
||||
op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn});
|
||||
|
||||
op_down = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", g.n_ff), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_down)),
|
||||
{w.ffn}, {w.h});
|
||||
|
||||
/* Column-sharded down projection: every rank holds a partial sum. Emitted here, by the
|
||||
* plugin, so the graph dump shows it here (spec §9). */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void MlpBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* Every operand carries the STEP's row count and not the buffer's: a kernel reads its extents
|
||||
* off the operands, because a ranged parameter has been collapsed to a band by the time issue
|
||||
* runs (arch/common/rad_arch.h, libref/ref_ops.h). */
|
||||
const int64_t T = batch->n_tok;
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_gate_up, brows(w.h, T), RAD_W(w_gate_up), brows(w.gate_up, T));
|
||||
RAD_ISSUE(c, op_act, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE(c, op_down, brows(w.ffn, T), RAD_W(w_down), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MLP_H */
|
||||
@@ -0,0 +1,203 @@
|
||||
/* rad_block_mlp_fp8.h -- the SwiGLU feed-forward block with block-scaled FP8 linears.
|
||||
*
|
||||
* rmsnorm -> quant_act_fp8 -> gate_up gemm_nt_q -> silu_mul -> quant_act_fp8 -> down gemm_nt_q
|
||||
* -> [all_reduce] -> residual add
|
||||
*
|
||||
* THE ARCHITECTURE IS rad_block_mlp.h's AND IS DOCUMENTED THERE -- the gate/up fusion, why the
|
||||
* all-reduce is emitted by the plugin, what the residual add is for. This file is that block with
|
||||
* two ops added and two changed, and it repeats none of it: a second copy of the prose is a second
|
||||
* thing to keep true.
|
||||
*
|
||||
* What differs, and only this:
|
||||
*
|
||||
* - the two projections are LinearFP8 (rad_fp8.h): an E4M3 weight, a bf16 [N/128][K/128] scale
|
||||
* plane declared as a weight of its own, and `gemm_nt_q` at dtype fp8a8 instead of `gemm_nt`.
|
||||
* - each of them is preceded by a `quant_act_fp8` over its input, because an fp8a8 GEMM takes an
|
||||
* E4M3 activation and the checkpoint's `activation_scheme` is `dynamic` -- there is no
|
||||
* activation scale on disk and one is computed every step.
|
||||
* - the norm, the activation and the collective are UNCHANGED. Activations between ops are still
|
||||
* bf16; only the two GEMM operands are narrow. So `Geom::dtype` stays "bf16" for this block and
|
||||
* every op in it but the two linears resolves exactly as it does in the bf16 plugin.
|
||||
*
|
||||
* The gate/up fusion survives the format, which is not obvious and is the reason it is kept: the
|
||||
* two sources are [17408,5120] each and their scale planes [136,40] each, and concatenating both
|
||||
* along dim 0 gives [34816,5120] against [272,40] -- which is the grid, because 34816/128 is 272.
|
||||
* A fusion whose parts were not whole multiples of 128 rows would silently misalign every scale
|
||||
* after the seam.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MLP_FP8_H
|
||||
#define RAD_BLOCK_MLP_FP8_H
|
||||
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct MlpFP8 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
ActFP8 h{}; /* [max_tok, n_embd] normed input, then the down-projection output */
|
||||
rad_buf gate_up = 0; /* [max_tok, 2 * n_ff] */
|
||||
ActFP8 ffn{}; /* [max_tok, n_ff] */
|
||||
};
|
||||
|
||||
/* The checkpoint side. `gate`, `up` and `down` name the `.weight` tensors; a block-fp8
|
||||
* checkpoint's scale planes sit beside them and the checkpoint reader pairs them, so a caller
|
||||
* cannot spell one of the pair and forget the other. */
|
||||
struct Src {
|
||||
const char* norm = nullptr;
|
||||
const char* gate = nullptr;
|
||||
const char* up = nullptr;
|
||||
const char* down = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
|
||||
rad_weight w_norm = 0;
|
||||
LinearFP8 gate_up{}, down{};
|
||||
NormQuantFP8 nq_h{};
|
||||
GateQuantFP8 gq_ffn{};
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
/* ...AND THE gate_up PROJECTION WITH THE GATE AND THE QUANTISER IN ITS EPILOGUE.
|
||||
*
|
||||
* `gq_ffn`'s only input is `gate_up`'s only output. Unfused it is one of the larger remaining
|
||||
* items in a decode step, and roughly half of that is the launch and half the second pass over
|
||||
* a [M, 2*n_ff] bf16 tensor the GEMM's transposing store had just scattered. Folded, that
|
||||
* tensor is never written at all.
|
||||
*
|
||||
* DECLARED BESIDE THE PAIR AND NOT INSTEAD OF IT, exactly as LinearFP8's matvec is: the fold
|
||||
* is the narrow tile's epilogue and serves M <= 64, so a prefill chunk takes the pair. The two
|
||||
* are byte-identical -- r4d_selftest holds them to it, and ref_test holds the reference to
|
||||
* the same claim -- so this is two spellings of one arithmetic and not two answers. */
|
||||
rad_op op_gated = 0;
|
||||
int64_t gated_rows = 0;
|
||||
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
|
||||
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
|
||||
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
|
||||
* fold's two flags again, one boundary later, and they are separate for the same reason: a
|
||||
* block is declared without knowing what follows it. On EITHER wire -- the fused kernel
|
||||
* carries both payloads -- and both sides ask ar_fused_ok(g, T), so the two cannot disagree
|
||||
* about whether the collective has already been issued. */
|
||||
bool ar_out = false;
|
||||
|
||||
|
||||
/* `fold` says this block has a PREDECESSOR whose delta is still in `w.h.x`, so its norm does
|
||||
* the residual add that block would otherwise have issued. False for the first block of a
|
||||
* chain, whose residual stream comes straight from the embedding. 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);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
};
|
||||
|
||||
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_) {
|
||||
g = geom; w = wire; layer = l;
|
||||
ar_out = ar_out_;
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* THE NORM, THE QUANTISER AND THE RESIDUAL ADD ARE ONE OP, and rad_fp8.h's NormQuantFP8 says
|
||||
* why: both were a launch and a second pass over a row this kernel already had in registers.
|
||||
* Folded, the norm reads the PREVIOUS block's delta out of the shared `h` buffer and adds it
|
||||
* into the stream; unfolded it reads the stream directly and the block ends with its own add. */
|
||||
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));
|
||||
RAD_ARCH_TRY(gate_up.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l),
|
||||
2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l),
|
||||
{ src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff }));
|
||||
|
||||
/* THE bf16 SILU PRODUCT IS WRITTEN ONLY FOR A READER: a down projection that reads the bf16
|
||||
* plane (LinearFP8::reads_x). A block-fp8 down_proj takes the codes and their scale alone. */
|
||||
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));
|
||||
|
||||
/* The fold, over the same weights and into the same activation the pair writes. Not
|
||||
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
|
||||
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
|
||||
if (hi > 0 && !gate_up.bf16) {
|
||||
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
|
||||
RAD_INT("K", gate_up.K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(gate_up.w, gate_up.ws)),
|
||||
{ w.h.q, w.h.s },
|
||||
gq_ffn.want_x ? std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ w.ffn.q, w.ffn.s });
|
||||
if (op_gated) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(down.declare(b, nm, g, down_base,
|
||||
g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l),
|
||||
{ src.down }, w.ffn, w.h.x));
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only where the NEXT block's norm will not do it; see rad_fp8.h's NormQuantFP8. */
|
||||
if (add_out)
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h.x}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ONE ROW SLICE OF THE BLOCK. `rows` defaults to the whole step, and at r0 = 0 with rows = T every
|
||||
* operand is byte-for-byte the one the unsliced form built -- `brow_slice` at offset 0 is `brows`.
|
||||
*
|
||||
* Every op here is per row: the norm and the quantiser group along K within a row, the GEMMs give
|
||||
* each output row its own accumulation, and the fused all-reduce closes every reduction over one
|
||||
* row (r4d_ar.cpp says so where it caps the block count). So a slice computes exactly the rows it
|
||||
* names and nothing about the arithmetic depends on how the chunk was cut -- PROVIDED the cut
|
||||
* obeys the band rule in core/runtime/ctx.h. */
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
RAD_W(gate_up.ws), brow_slice(w.ffn.q, r0, rows, g.n_ff),
|
||||
brow_slice(w.ffn.s, r0, rows, g.n_ff / RAD_FP8_BLOCK),
|
||||
gq_ffn.want_x ? brow_slice(w.ffn.x, r0, rows, g.n_ff) : RAD_NONE);
|
||||
} else {
|
||||
gate_up.step(c, w.h, w.gate_up, T, r0, rows);
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
RAD_ISSUE_N(c, op_add, rows, brow_slice(w.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
brow_slice(w.x, r0, rows, g.n_embd));
|
||||
}
|
||||
|
||||
inline void MlpFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
slice(c, T, 0, T);
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MLP_FP8_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,478 @@
|
||||
/* rad_block_mtp_fp8.h -- the multi-token-prediction head, with block-scaled FP8 projections.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* Qwen3.5 / Qwen3-Next ship ONE extra transformer layer beside the trunk, under an `mtp.` prefix
|
||||
* of its own, whose job is to predict token i+2 from the trunk's hidden state at i and the
|
||||
* embedding of the token at i+1. It is the drafter for speculative decoding, and it is a drafter
|
||||
* with no second checkpoint: the embedding table and the lm_head are the trunk's
|
||||
* (`mtp_use_dedicated_embeddings: false`, and no `mtp.lm_head` in the file).
|
||||
*
|
||||
* THE INDEXING IS THE WHOLE THING, so it is stated once here and everything else follows:
|
||||
*
|
||||
* head index i reads hidden(i) and embed(token at i + 1)
|
||||
* writes its K and V at KV position i, with rope position i
|
||||
* predicts the token at i + 2
|
||||
*
|
||||
* That is 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 and the
|
||||
* acceptance rate collapses, while the model's own output stays exactly correct.
|
||||
*
|
||||
* The forward is short and every piece of it already exists in this library:
|
||||
*
|
||||
* h = gather(the trunk's final hidden states, at the rows this pass continues from)
|
||||
* e = embed(the token one position on)
|
||||
* x = fc( concat( pre_fc_norm_embedding(e), pre_fc_norm_hidden(h) ) )
|
||||
* x = one gated-GQA layer + one SwiGLU feed-forward, over x <- AttnGatedFP8, MlpFP8
|
||||
* h'= mtp.norm(x)
|
||||
* logits = the TRUNK's lm_head over h'
|
||||
*
|
||||
* and h' is BOTH the logits input and the `h` of the next draft round. That is the reference's
|
||||
* shape too: a Qwen3-Next MTP forward returns one tensor and the proposer feeds the same tensor
|
||||
* back, unlike an EAGLE head which returns a (normed, unnormed) pair.
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* RadBatch::draft_pass says which, and the sign is the whole distinction:
|
||||
*
|
||||
* < 0 A HISTORY PASS, one row a token, gathering the trunk's hidden states. It exists
|
||||
* because 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 layer 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 it
|
||||
* is a drafter that proposes noise. The scheduler runs one over the positions the last
|
||||
* step added, the verified ones included.
|
||||
*
|
||||
* It is also DRAFT ROUND 1 for every sequence that drafts: that sequence's last history
|
||||
* row is the committed position with the token the trunk chose after it -- round 1's
|
||||
* whole input -- so the pass ends in the lm_head over those rows (RadBatch::draft_out_ids)
|
||||
* and leaves the head's output at them where round 2 reads it.
|
||||
*
|
||||
* > 1 A DRAFT ROUND, one row a sequence, reading the head's own output from the round before,
|
||||
* which is already in the same buffer. Every round ends in the lm_head, because a draft is
|
||||
* a token. There is no round-1 pass; the history pass is it.
|
||||
*
|
||||
* ============================== WHAT IS AND IS NOT FP8 ==============================
|
||||
*
|
||||
* Read off mtp.safetensors rather than assumed, exactly as qwen35_fp8.cpp reads the trunk:
|
||||
*
|
||||
* F8_E4M3 + scale layers.0.self_attn.{q,k,v,o}_proj, layers.0.mlp.{gate,up,down}_proj
|
||||
* BF16, no scale fc, norm, pre_fc_norm_embedding, pre_fc_norm_hidden, and every norm inside
|
||||
* the layer
|
||||
*
|
||||
* `fc` is [5120, 10240] and bf16, so it is a plain `gemm_nt`, issued ONCE over the whole chunk.
|
||||
* libr4d's bf16 GEMM row for this shape is C_LE("M", 65536) and K here is 10240, a multiple of 16,
|
||||
* so the wide row serves the whole chunk in one launch. That matters because the history pass runs
|
||||
* one row a TOKEN over a whole prefill chunk: banding this at 64 and slicing it would be dozens of
|
||||
* launches a chunk for a GEMM whose traffic is microseconds.
|
||||
*
|
||||
* ============================== THE CONCAT ORDER ==============================
|
||||
*
|
||||
* `fc` reads 10240 columns and the two halves are the normed embedding and the normed hidden
|
||||
* state. WHICH HALF IS FIRST IS NOT IN THE CHECKPOINT: both orders are one contiguous [5120,10240]
|
||||
* matrix and no shape, name or dtype distinguishes them. DeepSeek-V3's MTP -- the design this one
|
||||
* follows -- concatenates `enorm(embedding)` then `hnorm(hidden)`, and that is the order here.
|
||||
*
|
||||
* Both readings are self-consistent, libref shares whichever one the graph picks, and no per-op
|
||||
* oracle can reach it -- but it has a CHEAP EMPIRICAL ANSWER, the draft acceptance rate. A head
|
||||
* wired the right way round accepts most of what it proposes; wired the wrong way round it
|
||||
* proposes noise and accepts nothing, while the model's own output stays perfectly correct
|
||||
* because a rejected draft costs only time.
|
||||
*
|
||||
* ============================== THE NORM GAINS ==============================
|
||||
*
|
||||
* GemmaRMSNorm's `1 + w` (Geom::wadd) applies here and the checkpoint proves it rather than
|
||||
* suggesting it: pre_fc_norm_hidden sits at -0.06 .. -0.24 and pre_fc_norm_embedding at
|
||||
* -0.27 .. -0.61 -- NEGATIVE gains, which only `1 + w` explains. `mtp.norm` sits at 0.59 .. 1.31,
|
||||
* which reads as either, so it takes the same `final_wadd` the trunk's output norm takes -- one
|
||||
* question, asked once, answered in one place.
|
||||
*
|
||||
* ============================== 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_main. Two reasons, and neither is thrift:
|
||||
*
|
||||
* - the slot mapping and the block table are the trunk's. The head writes its K and V at the
|
||||
* slot the trunk's token for that position occupies, so 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 -- which is why vLLM's EAGLE/MTP proposer needs no second block
|
||||
* manager either.
|
||||
* - a second group would need its own page geometry, its own free list and its own eviction,
|
||||
* for a cache one seventeenth the size of the one already there.
|
||||
*
|
||||
* The cost is that the group's page grows from 16 layers to 17 -- 6% more attention KV -- and it
|
||||
* is paid only when the deployment declares speculation, because that is when the head is
|
||||
* declared at all.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MTP_FP8_H
|
||||
#define RAD_BLOCK_MTP_FP8_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_block_mlp_fp8.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
/* THE 2-BIT DRAFT HEAD IS A WEIGHT THE MODEL HOLDS OR DOES NOT. `head` is the lm_head under a name
|
||||
* of its own, which a recipe quantises to the 2-bit grid -- u2 codes, an f16 scale and a u8 zero a
|
||||
* group of 128 -- so one checkpoint tensor makes two logical weights. This declares its name map
|
||||
* (to `lm`, the checkpoint's head) and answers whether the model holds it at two bits, which is
|
||||
* when the draft rounds read it. A checkpoint served as it stands, or a container converted
|
||||
* without the rule, holds the bf16 head alone, and the draft rounds read that.
|
||||
*
|
||||
* Called ONCE, by the plugin, before it declares the head's buffers -- a name map is declared once
|
||||
* -- and the block reads the answer back from whether those buffers exist. */
|
||||
inline bool mtp_draft_head_q2(RadBuilder* b, const char* head, const char* lm) {
|
||||
if (!head || !lm) return false;
|
||||
if (map_copy(b, head, lm) < 0) return false;
|
||||
RadEncoding e{};
|
||||
return weight_enc(b, head, &e) && e.n_planes > 0 && e.plane[0].dtype == RAD_U2;
|
||||
}
|
||||
|
||||
/* TEMPLATED ON THE FEED-FORWARD, because the head is a TRUNK LAYER and a trunk layer's
|
||||
* feed-forward is dense in one member of this family and routed in the next. Qwen3.6-35B-A3B's
|
||||
* `mtp.layers.0` carries `mlp.experts.*`, `mlp.gate` and a shared expert, exactly as its trunk
|
||||
* layers do; a head hard-wired to MlpFP8 could not declare it, and the model would have a
|
||||
* container with a drafter in it and no way to run one.
|
||||
*
|
||||
* `Ffn` is MlpFP8 or MoeFP8. Both take the same declare() arity over their own Wire and Src -- the
|
||||
* MoE block's Config travels inside its Src for exactly this reason -- so nothing below has to
|
||||
* know which one it has. */
|
||||
template <class Ffn>
|
||||
struct MtpBlockFP8 {
|
||||
struct Wire {
|
||||
/* [max_tok, n_embd] the TRUNK's final hidden states for the step just run -- the plugin's
|
||||
* `h`, which gather_rows already reads for the trunk's own logits. A pass names the rows
|
||||
* it wants through out_ids and never has to know how they were laid out. */
|
||||
rad_buf src = 0;
|
||||
/* [max_tok, n_embd] IN: the hidden state this pass predicts from. OUT: the head's own,
|
||||
* which is the next draft round's input. Sized for a whole prefill chunk because a
|
||||
* history pass is one row a token. */
|
||||
rad_buf hout = 0;
|
||||
rad_buf e = 0; /* [max_tok, n_embd] the input token's embedding */
|
||||
rad_buf c = 0; /* [max_tok, 2 * n_embd] the two normed halves, fc's input */
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the head's own residual stream */
|
||||
rad_buf logits = 0; /* [max_logit_rows, n_vocab] the trunk's, shared */
|
||||
/* THE 2-BIT DRAFT HEAD's working set -- see the block comment at op_dlogits. Every one of
|
||||
* these is a draft round's, so they are sized at max_logit_rows and not at max_tok: a
|
||||
* history pass never reaches any of them. */
|
||||
rad_buf dq = 0; /* [max_logit_rows, n_embd] int8 codes */
|
||||
rad_buf ds = 0; /* [max_logit_rows, 1] f32, one scale a row */
|
||||
rad_buf dsum = 0; /* [n_embd/group, mpad] f32, GROUP-major (quant_act_i8's asum) */
|
||||
rad_buf dlog = 0; /* [max_logit_rows, n_vocab] bf16, the coarse logits */
|
||||
rad_buf didx = 0; /* [max_logit_rows, 1] i32, the proposed token */
|
||||
rad_buf dval = 0; /* [max_logit_rows, 1] f32, its logit */
|
||||
/* The layer's working set is the TRUNK's -- those buffers are dead by the time any of
|
||||
* this runs, and a second set would be 150 MiB of activation planes for one layer. */
|
||||
AttnGatedFP8::Wire attn{};
|
||||
typename Ffn::Wire mlp{};
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* fc = nullptr;
|
||||
const char* norm = nullptr;
|
||||
const char* pre_norm_hidden = nullptr;
|
||||
const char* pre_norm_embedding = nullptr;
|
||||
/* The checkpoint's lm_head, again. The trunk maps it as `output.weight`; the draft head is
|
||||
* a second logical weight over the SAME tensor, which the recipe quantises to 2-bit codes
|
||||
* (mtp_draft_head_q2). One source, two weights, no second checkpoint tensor. */
|
||||
const char* lm = nullptr;
|
||||
AttnGatedFP8::Src attn{};
|
||||
typename Ffn::Src mlp{};
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0; /* ABSOLUTE, so the KV group's layer_slot lookup finds it */
|
||||
int64_t rows = 0; /* the widest pass: one row a token of a prefill chunk */
|
||||
int64_t off_e = 0, off_h = 0; /* the two halves' column offsets inside `c` */
|
||||
rad_weight w_tok = 0, w_lm = 0, w_fc = 0, w_norm = 0, w_pre_h = 0, w_pre_e = 0;
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit lm_head and its (scale, zero) plane */
|
||||
bool q2 = false; /* is the draft round reading it? */
|
||||
AttnGatedFP8 attn{};
|
||||
Ffn mlp{};
|
||||
rad_op op_gather = 0, op_embed = 0, op_embed_ar = 0, op_pre_h = 0, op_pre_e = 0, op_fc = 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. */
|
||||
bool media = false;
|
||||
MediaRows mrows{};
|
||||
rad_op op_norm = 0, op_dsel = 0, op_dback = 0, op_logits = 0;
|
||||
rad_op op_dquant = 0, op_dlogits = 0, op_dtopk = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
|
||||
int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head, float out_wadd,
|
||||
const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
template <class Ffn>
|
||||
inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup kv, int64_t rotary_dim, rad_weight tok_embd,
|
||||
rad_weight lm_head, float out_wadd, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; w_tok = tok_embd; w_lm = lm_head;
|
||||
rows = g.max_tok;
|
||||
if (rows <= 0 || !w_tok || !w_lm) return RAD_E_INVAL;
|
||||
|
||||
/* The normed embedding first, then the normed hidden state; see THE CONCAT ORDER above. */
|
||||
off_e = 0;
|
||||
off_h = g.n_embd;
|
||||
|
||||
/* The head's own weights. SHARD_NONE on all four: three are per-channel norms over the
|
||||
* residual stream, which is replicated, and `fc` reads and writes that same stream -- a
|
||||
* column-sharded fc would need an all-reduce to buy 52 MiB a rank back, which is the wrong
|
||||
* side of the trade at one GEMM per draft round. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_hidden.weight"), src.pre_norm_hidden));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.pre_fc_norm_embedding.weight"), src.pre_norm_embedding));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.norm.weight"), src.norm));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("mtp.fc.weight"), src.fc));
|
||||
|
||||
w_pre_h = decl_w(b, nm.f("mtp.pre_fc_norm_hidden.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_pre_e = decl_w(b, nm.f("mtp.pre_fc_norm_embedding.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_norm = decl_w(b, nm.f("mtp.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_fc = decl_w(b, nm.f("mtp.fc.weight"), RAD_BF16, {g.n_embd, 2 * g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* 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. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.hout});
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), 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.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 does. Its own op rather than the trunk's because it writes a
|
||||
* different buffer, which is the rule the gather above states. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, rows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.e}, {w.e});
|
||||
|
||||
op_pre_h = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pre_h)),
|
||||
{w.hout}, {w.c});
|
||||
op_pre_e = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pre_e)),
|
||||
{w.e}, {w.c});
|
||||
|
||||
op_fc = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", 2 * g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fc)),
|
||||
{w.c}, {w.x});
|
||||
|
||||
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
|
||||
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", out_wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.hout});
|
||||
|
||||
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
|
||||
* sequence in round order, to the front of `hout` -- where the lm_head reads a round's rows
|
||||
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
|
||||
* gather in place could overwrite a row another sequence has yet to read. */
|
||||
op_dsel = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hout}, {w.x});
|
||||
op_dback = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x}, {w.hout});
|
||||
if (!op_dsel || !op_dback) return RAD_E_INVAL;
|
||||
|
||||
/* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
|
||||
* rather than at `rows`: it runs over one row a 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),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{w.hout}, {w.logits});
|
||||
|
||||
/* ---- THE 2-BIT DRAFT HEAD -------------------------------------------------------------
|
||||
*
|
||||
* `logits_gemm` IS ALREADY AT THE MEMORY ROOFLINE for the bf16 lm_head's 2.54 GB, so the only
|
||||
* lever it has is FEWER BYTES. That matters here and not at the trunk, because a speculative
|
||||
* step runs the projection THREE times: once to verify, and once per draft round.
|
||||
*
|
||||
* The two draft ones do not need the exact distribution. A draft is a PROPOSAL; the target
|
||||
* verifies every one of them with its own untouched bf16 head, and speculative decoding is
|
||||
* distribution-preserving -- so a worse draft costs ACCEPTANCE and cannot change a token the
|
||||
* model emits. That is the one place in the step where precision buys throughput outright.
|
||||
*
|
||||
* So the drafter reads a 2-bit copy: 318 MB of codes and 40 MB of (scale, zero) dwords against
|
||||
* 2.54 GB, an eighth of the traffic. It is a logical weight of its own over the checkpoint's
|
||||
* head (mtp_draft_head_q2), quantised by the recipe; libr4d's `gemm_w2a8_nt` takes its codes
|
||||
* and its scale and zero planes as two operands and lays them out as `r4d.w2a8.frag.g128` at
|
||||
* load (libr4d/r4d_layout.cpp). The grid is asymmetric -- four levels are not enough for a
|
||||
* symmetric one -- which is why the activation side is `quant_act_i8`'s three-output form: the
|
||||
* per-group row sums are what subtract the stored zero.
|
||||
*
|
||||
* AND IT DOES NOT GO THROUGH THE SAMPLER. The 2-bit GEMM writes bf16 and the sampler's chain
|
||||
* reads the f32 logits plane, so a draft round would need a cast of a 248K-wide row to reach
|
||||
* it -- for an argmax. `row_topk` at R=1 is that argmax, on the bf16 the GEMM already wrote,
|
||||
* and the engine reads the proposed id straight out of `didx`. The trunk's logits plane is
|
||||
* left alone, which is also what lets a draft round sample nothing at all.
|
||||
*/
|
||||
enum { MTP_W2_GROUP = 128 }; /* libr4d's R4D_GEMM_W2A8_GROUP, and the layout's g128 tag */
|
||||
/* The plugin declared the working set only where mtp_draft_head_q2 found the head at two
|
||||
* bits, which declared its name map too. */
|
||||
q2 = src.lm && w.dq && w.ds && w.dsum && w.dlog && w.didx && w.dval;
|
||||
if (q2) {
|
||||
/* REPLICATED, AT THE WHOLE VOCABULARY, and that is a decision rather than an omission.
|
||||
*
|
||||
* The trunk's lm_head is row-sharded and its logits are merged across ranks by the
|
||||
* sampler. This head does NOT go through the sampler -- the comment above op_dlogits says
|
||||
* why -- so its argmax is a `row_topk` over one rank's plane, and a sharded plane would
|
||||
* make every rank propose only tokens from its own half. Replicating it costs 341 MiB a
|
||||
* card at 2 bits (against the 1.27 GiB a rank saves on the trunk head) and keeps the
|
||||
* draft path a single-rank computation, which is what it is.
|
||||
*
|
||||
* The stored bytes are also tile-major (16 output rows a packed block), so the relayout
|
||||
* would have to be handed a row share that is a whole number of tiles. */
|
||||
const char* dhn = nm.f("mtp.draft_head.weight");
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {g.n_vocab_all, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_dhs = decl_view(b, nm.f("mtp.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{g.n_vocab_all, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_INT("group", MTP_W2_GROUP),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hout}, {w.dq, w.ds, w.dsum});
|
||||
|
||||
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("N", g.n_vocab_all), RAD_INT("K", g.n_embd),
|
||||
RAD_INT("group", MTP_W2_GROUP), RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
|
||||
op_dtopk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("N", g.n_vocab_all), RAD_INT("R", 1),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval});
|
||||
}
|
||||
|
||||
/* THE HEAD'S OUTPUT STAYS LIVE THROUGH THE WHOLE HEAD. It is the next round's input, written
|
||||
* before this pass's lm_head runs; declared as read by the lm_head's first op 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. */
|
||||
{
|
||||
const rad_op last = q2 ? op_dtopk : op_logits;
|
||||
if (rad_op_reads(b, last, &w.hout, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
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 (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. */
|
||||
template <class Ffn>
|
||||
inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int r = batch->draft_pass;
|
||||
|
||||
/* The history pass gathers; the rounds after it read the head's own output, which the pass
|
||||
* before 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");
|
||||
return;
|
||||
}
|
||||
if (r < 0 && batch->n_out > 0)
|
||||
RAD_ISSUE_N(c, op_gather, batch->n_out,
|
||||
RAD_B(w.src), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(w.hout, batch->n_out));
|
||||
|
||||
RAD_ISSUE(c, op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.e, T));
|
||||
mrows.step(c, batch, w.e, T);
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.e, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_pre_h, brows(w.hout, T), RAD_W(w_pre_h), bcol(w.c, off_h, g.n_embd, T));
|
||||
RAD_ISSUE(c, op_pre_e, brows(w.e, T), RAD_W(w_pre_e), bcol(w.c, off_e, g.n_embd, T));
|
||||
|
||||
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
|
||||
|
||||
attn.step(c, batch);
|
||||
mlp.step(c, batch);
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
|
||||
|
||||
/* A history pass that drafts nothing exists only to leave K and V behind. One that does
|
||||
* brings round 1's rows to the front first. */
|
||||
int64_t L = T; /* the rows the lm_head runs over */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.x, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, 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. */
|
||||
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). */
|
||||
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);
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
}
|
||||
|
||||
/* The dense head, which is the 27B's and every other member of this family whose feed-forward is
|
||||
* one SwiGLU. The routed one is MtpBlockFP8<MoeFP8>, named by the plugin that wants it -- this
|
||||
* header does not include rad_block_moe_fp8.h, because a dense plugin should not compile a routed
|
||||
* block it will never declare. */
|
||||
using MtpFP8 = MtpBlockFP8<MlpFP8>;
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MTP_FP8_H */
|
||||
@@ -0,0 +1,587 @@
|
||||
/* 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 ==============================
|
||||
*
|
||||
* 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:
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ============================== THE INDEXING ==============================
|
||||
*
|
||||
* head index i reads hidden(i) and embed(token at i + 1)
|
||||
* 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.
|
||||
*
|
||||
* ============================== THE TWO KINDS OF PASS ==============================
|
||||
*
|
||||
* `RadBatch::draft_pass` says which and the SIGN is the whole distinction:
|
||||
*
|
||||
* < 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.
|
||||
*
|
||||
* ============================== THE CARRY, AND WHY IT IS A COPY ==============================
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* ============================== 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.
|
||||
*
|
||||
* ============================== WHAT IS AND IS NOT DECLARED ==============================
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_MTP_HC_H
|
||||
#define RAD_BLOCK_MTP_HC_H
|
||||
|
||||
#include "rad_block_attn_gated_fp8.h"
|
||||
#include "rad_block_hc.h"
|
||||
#include "rad_block_moe_fp8.h"
|
||||
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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 */
|
||||
rad_buf e = 0; /* [max_tok, n_embd] the input token's embedding */
|
||||
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. */
|
||||
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. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* fc_hidden = nullptr;
|
||||
const char* fc_embedding = nullptr;
|
||||
const char* pre_norm_hidden = nullptr;
|
||||
const char* pre_norm_embedding = nullptr;
|
||||
HyperConn::Src hc_attn{}, hc_mlp{}, hc_mix{};
|
||||
AttnGatedFP8::Src attn{};
|
||||
MoeFP8::Src mlp{};
|
||||
/* The indexer's names and geometry; `qk_proj` null declares no indexer at all. */
|
||||
QsaIndexer::Config qsa{};
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
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 */
|
||||
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. */
|
||||
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;
|
||||
rad_weight w_dh = 0, w_dhs = 0;
|
||||
|
||||
HyperConn hc_attn{}, hc_mlp{}, mixer{};
|
||||
AttnGatedFP8 attn{};
|
||||
QsaIndexer qsa{};
|
||||
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. */
|
||||
|
||||
bool media = false;
|
||||
|
||||
MediaRows mrows{};
|
||||
rad_op op_dsel = 0, op_dback = 0;
|
||||
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. */
|
||||
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); }
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
|
||||
rad_kvgroup* qsa_bk, int64_t rotary_dim, rad_weight tok_embd, rad_weight lm_head,
|
||||
const HyperConn::Config& hc, int draft_depth, const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup kv,
|
||||
rad_kvgroup* qsa_bk, int64_t rotary_dim, rad_weight tok_embd,
|
||||
rad_weight lm_head, const HyperConn::Config& hc, int draft_depth,
|
||||
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. */
|
||||
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. */
|
||||
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");
|
||||
const char* nfe = nm.f("mtp.fc_embedding.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, nph, src.pre_norm_hidden));
|
||||
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. */
|
||||
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 "
|
||||
"reads both as bf16 or both as E4M3 rows\n", rad_dtype_name(fdt),
|
||||
rad_dtype_name(weight_codes_dtype(b, nfe, RAD_BF16)));
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
w_pre_h = decl_w(b, nph, RAD_F32, {HN}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_pre_e = decl_w(b, npe, RAD_F32, {g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
w_fc_h = decl_w(b, nfh, fdt, {g.n_embd, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
grp_layer(l));
|
||||
w_fc_e = decl_w(b, nfe, fdt, {g.n_embd, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
|
||||
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. */
|
||||
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)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.hin});
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), 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.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. */
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, rows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.e}, {w.e});
|
||||
|
||||
op_enter = rw(b, RAD_OP(b, "mtp_enter",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", hc.hc), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd),
|
||||
RAD_INT("ngroup", ngroup),
|
||||
RAD_STR("fc", fdt == RAD_F8E4M3 ? "e4m3" : "bf16")),
|
||||
RAD_WEIGHTS(w_pre_h, w_pre_e, w_fc_h, w_fc_e)),
|
||||
{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. */
|
||||
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));
|
||||
attn.ar_out_take = hc_attn.ar_take();
|
||||
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn,
|
||||
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));
|
||||
/* The rotated expert input rides in this read, as it does 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; }
|
||||
RAD_ARCH_TRY(hc_mlp.declare(b, nm, g, nm.f("mtp.ffn_hc"), mcfg, mwire, src.hc_mlp));
|
||||
mlp.ar_out_take = hc_mlp.ar_take();
|
||||
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. */
|
||||
{
|
||||
HyperConn::GatherSrc gs{};
|
||||
gs.ye = mlp.w.edn;
|
||||
gs.ew = mlp.w.ew;
|
||||
gs.sorted = mlp.w.sorted;
|
||||
if (mlp.gfold) { gs.sh = mlp.w.sout; gs.sg = mlp.w.sgate; }
|
||||
gs.top_k = mlp.c.top_k;
|
||||
gs.rows = mlp.c.rows;
|
||||
RAD_ARCH_TRY(hc_mlp.declare_gather(b, gs));
|
||||
mlp.gather_out_rows = hc_mlp.gather_rows;
|
||||
mlp.gather_out_rows6 = hc_mlp.gather_rows6;
|
||||
}
|
||||
|
||||
/* ---- the carry. See the header: `mtp_enter` cannot be issued 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});
|
||||
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
|
||||
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
|
||||
* the mixer. Two ops and not one because a gather in place could overwrite a row another
|
||||
* sequence has yet to read. */
|
||||
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)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hw}, {w.hin});
|
||||
op_dback = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hin}, {w.hw});
|
||||
if (!op_dsel || !op_dback) return RAD_E_INVAL;
|
||||
|
||||
/* ---- 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. */
|
||||
{
|
||||
HyperConn::Config mc = hc;
|
||||
mc.inject = 0;
|
||||
mc.quant = 0;
|
||||
HyperConn::Wire mixw{};
|
||||
mixw.h = w.hw; mixw.x.x = w.hout; /* q/s deliberately absent */
|
||||
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. */
|
||||
op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_lm)),
|
||||
{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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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));
|
||||
w_dhs = decl_view(b, nm.f("mtp.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{hrows, g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_layer(l));
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
op_dquant = rw(b, RAD_OP(b, "quant_act_i8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_INT("group", MTP_W2_GROUP),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.hout}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("N", hrows), RAD_INT("K", g.n_embd),
|
||||
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. */
|
||||
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),
|
||||
RAD_INT("R", kDraftTopR), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval, w.dpair})
|
||||
: rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("N", hrows),
|
||||
RAD_INT("R", kDraftTopR), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.didx, w.dval});
|
||||
/* ---- THE COARSE HEAD'S CANDIDATES, RESCORED EXACTLY.
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
const bool rerank = dh_shard || g.world <= 1;
|
||||
if (rerank) {
|
||||
op_drerank = RAD_OP(b, "logit_rerank",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("R", kDraftTopR), RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("vocab_off", g.vocab_off),
|
||||
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. */
|
||||
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. */
|
||||
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),
|
||||
RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", kDraftTopR * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_dmerge = rw(b, RAD_OP(b, "row_topk_merge",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("R", kDraftTopR),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dgath}, {w.didx, w.dval});
|
||||
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
|
||||
}
|
||||
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. */
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
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. */
|
||||
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. */
|
||||
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");
|
||||
return;
|
||||
}
|
||||
if (r < 0 && batch->n_out > 0)
|
||||
RAD_ISSUE_N(c, op_gather, batch->n_out,
|
||||
RAD_B(w.src), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(w.hin, batch->n_out));
|
||||
|
||||
RAD_ISSUE(c, op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.e, T));
|
||||
mrows.step(c, batch, w.e, T);
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.e, T), RAD_NONE);
|
||||
|
||||
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);
|
||||
/* 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);
|
||||
attn.step(c, batch);
|
||||
hc_attn.write(c, T, 0, T);
|
||||
|
||||
hc_mlp.read(c, T, 0, T);
|
||||
mlp.step(c, batch);
|
||||
hc_mlp.write(c, T, 0, T);
|
||||
|
||||
/* 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 that drafts takes round 1's rows out of its own
|
||||
* -- into the carry, and back to the front of `hw` for the mixer below -- and one that does
|
||||
* not exists only to leave K and V behind. */
|
||||
int64_t L = T; /* the rows the lm_head runs over */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
} else if (r < depth) {
|
||||
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
|
||||
}
|
||||
|
||||
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. */
|
||||
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). */
|
||||
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. */
|
||||
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));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, L), brows(w.dgath, L));
|
||||
RAD_ISSUE_N(c, op_dmerge, L, brows(w.dgath, L), brows(w.didx, L), brows(w.dval, L));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_dtopk, L, brows(w.dlog, L), brows(w.didx, L), brows(w.dval, L),
|
||||
RAD_NONE); /* the `pairs` slot, absent: operands are positional */
|
||||
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), RAD_NONE);
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_MTP_HC_H */
|
||||
@@ -0,0 +1,547 @@
|
||||
/* rad_block_ple.h -- Qwen4-Exp's Per-Layer Embedding, declared and issued.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* ONE layer of the model gets a second embedding table, addressed not by the token but by a HASH of
|
||||
* the last three. Qwen3.8-Flash-Next's is 320,001,536 rows of 160 -- FOUR FIFTHS OF THE CHECKPOINT,
|
||||
* 51 of its 125 billion parameters -- read sixteen rows a token and mixed into the residual stream
|
||||
* by a dot product against the stream itself:
|
||||
*
|
||||
* ids = ngram_ids(tokens) [T, 16] a hash of the last 3 ids, per head
|
||||
* e = embed_lookup_q(ids, table, scale) [T, 2560] 16 x 160, flattened
|
||||
* k = key_proj(e) [T, hc*n] v = value_proj(e) [T, n]
|
||||
* gv,
|
||||
* gvn = ple_gate(k, h, v, ...) the dot, the signed sqrt, the broadcast
|
||||
* out = ple_conv(gvn, resid = gv, ...) dilated depthwise conv, silu, and the add
|
||||
* h += out
|
||||
*
|
||||
* and it happens BEFORE the attention hyper-connection reads the stream, so `h` here is the wide
|
||||
* un-normed residual.
|
||||
*
|
||||
* ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ======================
|
||||
*
|
||||
* 51.2 GB cannot be on the card and cannot be staged onto it, so `embed_lookup_q` runs on the HOST
|
||||
* over the container's own mmap and its result crosses the link once -- 5 KB a token at decode.
|
||||
* libavx/avx_ngram.cpp carries that argument in full. Three consequences reach this file:
|
||||
*
|
||||
* THE TABLE IS A WEIGHT OPERAND, because the planner puts an op on the host only when every
|
||||
* weight operand of it is Site::Host. A gather whose source were an activation could never be
|
||||
* placed there.
|
||||
*
|
||||
* ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by a host kernel, so they live
|
||||
* in the host arena; everything downstream of `e` is ordinary device work.
|
||||
*
|
||||
* IT IS 128 CHECKPOINT TENSORS. RadNameMap holds eight sources, so the map is declared in pieces
|
||||
* by map_concat_shards() and the order IS the concatenation -- a permuted table is a model that
|
||||
* loads, runs, and looks up the wrong embeddings.
|
||||
*
|
||||
* ============================== TWO STATES, ONE CONTRACT ==============================
|
||||
*
|
||||
* The n-gram hash needs the two committed ids in front of the step, and the convolution needs nine
|
||||
* timesteps of its input. Both are RAD_KV_CONV rolling windows read at `num_accepted - 1`. They
|
||||
* differ in ONE thing: the token window's cold value is EOS and the convolution's is zero, because
|
||||
* zero is a real token id. `has_init` says which slots are cold and both ops read it.
|
||||
*
|
||||
* WHAT A STEP LEAVES IN THE WINDOW DEPENDS ON WHAT KIND OF STEP IT WAS, and the op learns that
|
||||
* from whether `num_accepted` is passed (libref/ref_ple.cpp). A decode row may have its drafts
|
||||
* rejected, so its window is left in gdn_conv_update's shifted layout, where the next step's read
|
||||
* offset picks out the history ending at the last token kept. A prefill chunk commits everything,
|
||||
* so its window is its tail at offset zero, which the scheduler's `num_accepted` of 1 for the next
|
||||
* step reads. One layout cannot serve both: at offset zero the first holds the history ending at
|
||||
* the step's FIRST token and the second the history ending at its LAST. So step() issues both ops
|
||||
* once per half of the batch, the way rad_block_gdn_fp8.h issues its two convolutions.
|
||||
*/
|
||||
#ifndef RAD_BLOCK_PLE_H
|
||||
#define RAD_BLOCK_PLE_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct PleLayer {
|
||||
struct Config {
|
||||
int64_t hc = 0; /* hyper-connection streams */
|
||||
int64_t embed_dim = 0; /* ple_embed_dim: heads * head_dim */
|
||||
int64_t heads = 0; /* (ngram - 1) * heads_per_ngram */
|
||||
int64_t ngram = 0;
|
||||
int64_t eos = -1;
|
||||
int64_t rows = 0; /* the table's row count, padded */
|
||||
int64_t shards = 0; /* how many checkpoint tensors it is stored as */
|
||||
int64_t conv_width = 0;
|
||||
int64_t dilation = 0; /* == ngram, in this model */
|
||||
int64_t head_dim() const { return heads > 0 ? embed_dim / heads : 0; }
|
||||
int64_t hist() const { return (conv_width - 1) * dilation; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
rad_buf h = 0; /* [max_tok, hc * n_embd] THE WIDE STREAM, read and added into */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
/* The table's shards are named `<prefix><i><suffix>`; everything else is one tensor. */
|
||||
const char* shard_prefix = nullptr;
|
||||
const char* shard_suffix = nullptr;
|
||||
const char* mult = nullptr;
|
||||
const char* vocab_sizes = nullptr;
|
||||
const char* offsets = nullptr;
|
||||
const char* key_proj = nullptr;
|
||||
const char* value_proj = nullptr;
|
||||
const char* norm_key = nullptr;
|
||||
const char* norm_query = nullptr;
|
||||
const char* norm_conv = nullptr;
|
||||
const char* conv1d = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
int layer_ = 0;
|
||||
|
||||
rad_weight w_table = 0, w_scale = 0, w_mult = 0, w_vsz = 0, w_off = 0;
|
||||
/* The table as the checkpoint ships it -- plain bf16, no scale weight -- rather than E4M3. */
|
||||
bool table_bf16 = false;
|
||||
rad_weight w_key = 0, w_value = 0, w_nk = 0, w_nq = 0, w_nc = 0, w_conv = 0;
|
||||
|
||||
rad_kvgroup kv_tok = 0, kv_conv = 0;
|
||||
rad_buf b_ids = 0, b_emb = 0, b_embd = 0, b_k = 0, b_v = 0, b_gv = 0, b_gvn = 0, b_out = 0;
|
||||
rad_op op_ids = 0, op_gather = 0, op_embd = 0, op_key = 0, op_value = 0;
|
||||
rad_op op_gate = 0, op_conv = 0, op_add = 0;
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */
|
||||
int64_t ahead_rows(const RadBatch* batch) const {
|
||||
const int64_t a = batch->n_ahead;
|
||||
return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer,
|
||||
const Wire& wire, const Src& src);
|
||||
/* The hash, issued at the TOP of the step; the rest, at the layer. See step(). */
|
||||
void ids(RadCtx* c_, const RadBatch* batch) const;
|
||||
void step(RadCtx* c_, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg,
|
||||
int layer, const Wire& wire, const Src& src) {
|
||||
g = geom; c = cfg; w = wire;
|
||||
|
||||
if (c.hc <= 1 || c.heads <= 0 || c.ngram < 2 || c.eos < 0 || c.rows <= 0 ||
|
||||
c.shards <= 0 || c.conv_width <= 1 || c.dilation <= 0 || c.embed_dim <= 0) {
|
||||
fprintf(stderr, "radiance: ple: geometry refused -- hc %lld heads %lld ngram %lld eos "
|
||||
"%lld rows %lld shards %lld width %lld dilation %lld embed %lld\n",
|
||||
(long long)c.hc, (long long)c.heads, (long long)c.ngram, (long long)c.eos,
|
||||
(long long)c.rows, (long long)c.shards, (long long)c.conv_width,
|
||||
(long long)c.dilation, (long long)c.embed_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* `heads` is `ngram - 1` equal blocks, one per n-gram order, and `embed_dim` splits evenly
|
||||
* across them. Both are the reference's own constructor checks. */
|
||||
if (c.heads % (c.ngram - 1) || c.embed_dim % c.heads) {
|
||||
fprintf(stderr, "radiance: ple: %lld heads over %lld n-gram orders, %lld embed dims -- "
|
||||
"neither divides\n", (long long)c.heads, (long long)(c.ngram - 1),
|
||||
(long long)c.embed_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!w.h) return RAD_E_INVAL;
|
||||
if (!src.shard_prefix || !src.shard_suffix || !src.mult || !src.vocab_sizes ||
|
||||
!src.offsets || !src.key_proj || !src.value_proj || !src.norm_key || !src.norm_query ||
|
||||
!src.norm_conv || !src.conv1d) return RAD_E_INVAL;
|
||||
/* ============================== THE WHOLE LAYER IS REPLICATED UNDER TP ==============================
|
||||
*
|
||||
* Replication is the RIGHT answer here, not a gap: sharding would be the mistake.
|
||||
*
|
||||
* THE TABLE IS ADDRESSED BY A HASH OF THE TOKENS, which every rank computes identically, so a
|
||||
* vocabulary shard would give each rank rows it can never be asked for. And it costs NOTHING
|
||||
* to replicate: it is Tier::Mapped, read from the container's own file, so both ranks point at
|
||||
* the same table on the same machine and gather through one row cache they share.
|
||||
*
|
||||
* WHAT IS LEFT IS 63 MiB A RANK -- key_proj 50, value_proj 12.5, three norm gains and a conv
|
||||
* weight -- against the 112 GiB of experts TP exists to split here. Column-sharding the
|
||||
* projections would shard `gv` and `gvn` across the hyper-connection streams, and then the
|
||||
* convolution and the residual add would need the full width back: an all-gather a step, to
|
||||
* save 31 MiB a card. Geom::n_embd is "the residual stream, replicated on every rank", and
|
||||
* this layer reads and writes exactly that.
|
||||
*
|
||||
* SO EVERY RANK RUNS THE WHOLE LAYER AND THERE IS NO COLLECTIVE IN IT. Both ranks see the same
|
||||
* token ids, hash them the same way, gather the same rows and add the same `out` into their
|
||||
* own copy of a stream that was already identical -- bit for bit, because the all-reduce that
|
||||
* produced it delivers the same sum to both. The duplicated work is two small GEMMs and one
|
||||
* host gather per rank.
|
||||
*
|
||||
* ---- AND THAT LAST SENTENCE IS TRUE AT DECODE AND EXPENSIVE AT PREFILL ---------------------
|
||||
*
|
||||
* The duplicated gather is `heads` rows a TOKEN, so what is sixteen rows at a decode step is
|
||||
* sixteen thousand at a 1024-token chunk and thirty-two thousand at a 2048 one. A gather that
|
||||
* reads the table through the mapping costs each rank about 70 ms at a 2048-token chunk --
|
||||
* about 7.6% of a prefill step each. The RANKS ARE THREADS IN ONE PROCESS, so the page faults
|
||||
* are shared, but each rank still walks every row, and the step waits for both.
|
||||
*
|
||||
* THAT COST IS PAGE-TABLE POPULATION, NOT I/O. The distinct rows a prefill wants land on
|
||||
* distinct 4 KiB pages -- about ONE USEFUL ROW A PAGE, where a page holds 25 of them -- so a
|
||||
* gather through the mapping pays a fault per row. At decode, with varied text, it is the
|
||||
* other way round: half of every step's rows are new, and the page cache makes the waiting
|
||||
* thread start each of those reads itself. So the kernel keeps the rows in a cache of its own
|
||||
* and reads a miss straight from the file (libavx/avx_ngram.cpp).
|
||||
*
|
||||
* AND THAT CACHE SPLITS THE COLD WORK WITHOUT A COLLECTIVE. Dividing the rows between ranks,
|
||||
* or having one rank gather for both, would need a cross-rank HOST barrier inside a block that
|
||||
* deliberately has no collective in it. The shared cache does not: each rank claims the misses
|
||||
* it reaches first, reads only those, and waits only for rows the other rank has already
|
||||
* claimed -- so a miss is read once, and a late rank finds the rows there. What each rank still
|
||||
* does alone is decode the rows into its own output, which is a table lookup a byte. A
|
||||
* vocabulary shard is still wrong for the reason given above.
|
||||
*/
|
||||
|
||||
const int64_t HN = hn();
|
||||
const int64_t HD = c.head_dim();
|
||||
|
||||
/* ---- the table, its scale, and the three hash constants -------------------------------- */
|
||||
/* E4M3 with ONE scale for all 320 million rows -- Qwen3.8-Flash-Next-FP8's own choice, and the
|
||||
* table's statistics say why that works: E4M3 carries its own exponent, a row's dynamic range
|
||||
* is 2.3x, and the scale sits on a three-octave plateau. ONE STORED WEIGHT, `fp8_e4m3*bf16[*x*]`
|
||||
* -- its codes and a one-element scale plane, made by the recipe from the dense checkpoint
|
||||
* (data/recipes/qwen4exp-w4.recipe) -- and the gather takes the two planes as two operands.
|
||||
* The shards are joined along rows by the name map, declared first because it is how the
|
||||
* model is asked what the table is. RAD_ACCESS_VOCAB because it IS a vocabulary table, just
|
||||
* not the token one. */
|
||||
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
|
||||
RAD_ARCH_TRY(map_concat_shards(b, tn, src.shard_prefix, src.shard_suffix, (int)c.shards, 0));
|
||||
/* OR THE CHECKPOINT'S OWN bf16 TABLE, 102 GB, when the container holds it as it ships: the
|
||||
* same op with no scale (embed_lookup_q's absent scale is one), so it stays a host gather over
|
||||
* the mapping like the E4M3 one -- the gather's row cache serves either row size. */
|
||||
RadEncoding te{};
|
||||
table_bf16 = weight_enc(b, tn, &te) && rad_enc_is(&te, "plain") && te.n_planes == 1 &&
|
||||
te.plane[0].dtype == RAD_BF16;
|
||||
if (table_bf16) {
|
||||
w_table = decl_w(b, tn, RAD_BF16, {c.rows, HD}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE,
|
||||
grp_model());
|
||||
} else {
|
||||
w_table = decl_view(b, tn, nullptr, "codes", RAD_F8E4M3, {c.rows, HD},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model());
|
||||
w_scale = decl_view(b, nm.f("blk.%d.ple_ngram.scale", layer), tn, "scale", RAD_BF16, {1},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
}
|
||||
|
||||
/* I64 AND NOT I32. The multipliers are ~2.4e13 -- the hash's whole point is that a token id
|
||||
* times one of them fills sixty-three bits -- so narrowing them would change every id. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_mult", layer), src.mult));
|
||||
w_mult = decl_w(b, nm.f("blk.%d.ple_mult", layer), RAD_I64, {c.ngram},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_vocab_sizes", layer), src.vocab_sizes));
|
||||
w_vsz = decl_w(b, nm.f("blk.%d.ple_vocab_sizes", layer), RAD_I64, {c.heads},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_offsets", layer), src.offsets));
|
||||
w_off = decl_w(b, nm.f("blk.%d.ple_offsets", layer), RAD_I64, {c.heads},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---- the projections and the three gains ------------------------------------------------ */
|
||||
/* BF16 AND NOT fp8: `modules_to_not_convert` in the FP8 checkpoint names both projections, so
|
||||
* these arrive dense whichever checkpoint is the source. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_key.weight", layer), src.key_proj));
|
||||
w_key = decl_w(b, nm.f("blk.%d.ple_key.weight", layer), RAD_BF16, {HN, c.embed_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_value.weight", layer), src.value_proj));
|
||||
w_value = decl_w(b, nm.f("blk.%d.ple_value.weight", layer), RAD_BF16,
|
||||
{g.n_embd, c.embed_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_key.weight", layer), src.norm_key));
|
||||
w_nk = decl_w(b, nm.f("blk.%d.ple_norm_key.weight", layer), RAD_F32, {HN},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_query.weight", layer), src.norm_query));
|
||||
w_nq = decl_w(b, nm.f("blk.%d.ple_norm_query.weight", layer), RAD_F32, {HN},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_norm_conv.weight", layer), src.norm_conv));
|
||||
w_nc = decl_w(b, nm.f("blk.%d.ple_norm_conv.weight", layer), RAD_F32, {HN},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* The checkpoint stores it [hc*n, 1, width]; the op wants [hc*n, width], which is the same
|
||||
* bytes with the depthwise group axis dropped. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_conv.weight", layer), src.conv1d));
|
||||
w_conv = decl_w(b, nm.f("blk.%d.ple_conv.weight", layer), RAD_BF16, {HN, c.conv_width},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
if (!w_table || (!table_bf16 && !w_scale) || !w_mult || !w_vsz || !w_off || !w_key || !w_value ||
|
||||
!w_nk || !w_nq || !w_nc || !w_conv) return RAD_E_INVAL;
|
||||
|
||||
/* ---- the two rolling windows ------------------------------------------------------------ */
|
||||
/* RAD_KV_CONV is "per-sequence, a rolling window of width-1 + num_spec entries", which is both
|
||||
* of these. The token window's `conv_width` is ngram, so its window is ngram - 1 + n_spec.
|
||||
*
|
||||
* THE CHANNEL COUNT IS n_head_kv * head_dim AND NOT state_dim, which is the one field pair a
|
||||
* reader of RadKVGroupDecl gets wrong: `state_dim` is RAD_KV_LINEAR's per-head geometry and
|
||||
* the CONV kind never looks at it. Declared into state_dim, both of these size to zero bytes a
|
||||
* sequence and the KV manager refuses the model at bring-up -- which is the good outcome, but
|
||||
* rad-kbench cannot find it: it synthesises the state operand from the op's own shape function
|
||||
* and never asks the manager for one. */
|
||||
{
|
||||
RadKVGroupDecl td{};
|
||||
td.kind = RAD_KV_CONV;
|
||||
td.dtype = RAD_I32;
|
||||
td.conv_width = c.ngram;
|
||||
td.n_head_kv = 1;
|
||||
td.head_dim = 1; /* one token id a slot */
|
||||
kv_tok = rad_decl_kv_group(b, nm.f("kv_ple_tok"), &td);
|
||||
|
||||
RadKVGroupDecl cd{};
|
||||
cd.kind = RAD_KV_CONV;
|
||||
cd.dtype = g.act_dtype;
|
||||
/* The conv's history is (width-1)*dilation deep, so the GROUP's width -- which the manager
|
||||
* reads as "window = conv_width - 1 + n_spec" -- is that plus one. Passing the raw
|
||||
* conv_width here would size the window for an undilated convolution and the deepest tap
|
||||
* would read a value that was never written. */
|
||||
cd.conv_width = c.hist() + 1;
|
||||
cd.n_head_kv = 1;
|
||||
cd.head_dim = HN; /* [n_states, hc*n_embd, hist + n_spec] */
|
||||
kv_conv = rad_decl_kv_group(b, nm.f("kv_ple_conv"), &cd);
|
||||
}
|
||||
if (!kv_tok || !kv_conv) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv_tok));
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, layer, kv_conv));
|
||||
|
||||
/* ---- buffers ---------------------------------------------------------------------------- */
|
||||
/* HOST DOMAIN for the two the gather touches. `ids` is written by ngram_ids and read by the
|
||||
* host gather; `e` is written by the host gather and read by one device copy onto the card
|
||||
* (`ple_emb_dev`, below). The host arena is mapped, so the device side of that hand-off is a
|
||||
* link read (core/runtime/ctx.cpp) -- 5 KB a token at decode.
|
||||
*
|
||||
* `ids` IS PERSIST because it is written at the top of the step and read at this layer: the
|
||||
* buffer plan computes liveness in DECLARED order, where the two ops are neighbours, and a
|
||||
* transient would lend its bytes to anything issued in between. */
|
||||
{
|
||||
/* TWICE THE STEP'S ROWS: the step's own ids, then the ids of the prompt that follows it
|
||||
* (RadBatch::n_ahead), which the gather hands to its reader to fetch while the step runs. */
|
||||
RadBufDecl d{};
|
||||
d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads;
|
||||
d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST;
|
||||
b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d);
|
||||
|
||||
/* [max_tok, embed_dim] AND NOT [max_tok * heads, head_dim], because ONE declared shape has
|
||||
* to serve two readings and only this one does. The gather writes `heads` rows a token and
|
||||
* the projections read one row a token of `embed_dim` -- the same bytes either way -- and
|
||||
* the direction that works is decided by HOW EACH KERNEL FINDS ITS ROW COUNT.
|
||||
*
|
||||
* The gather derives it: r4d_rows_pitch(x, n_embd) is numel / the width the kernel asks
|
||||
* for, so [T, 2560] read at 160 IS T*16 rows of 160. The GEMM does not: gemm_ops takes
|
||||
* M = a->shape[0] and K = a->shape[1] straight off the operand, because a strided rank-3
|
||||
* activation has to be refused rather than folded. So the wide shape serves both and the
|
||||
* tall one serves only the gather: declared tall, the key projection is handed M = T*16,
|
||||
* K = 160 against a [T, 10240] output and refuses the step. */
|
||||
RadBufDecl e{};
|
||||
e.dtype = g.act_dtype; e.rank = 2;
|
||||
e.shape[0] = g.max_tok; e.shape[1] = c.embed_dim;
|
||||
e.kind = RAD_BUF_TRANSIENT; e.domain = RAD_DOMAIN_HOST;
|
||||
b_emb = rad_decl_buffer(b, nm.f("ple_emb"), &e);
|
||||
}
|
||||
/* AND ITS COPY ON THE CARD, which is what the two projections read. `e` in the mapped host
|
||||
* arena is a link read, and a GEMM does not read its A operand once: the tiled kernel reads
|
||||
* each row band once a column block, 80 times for the key projection, every one of them a PCIe
|
||||
* round trip or a hit on the copy that round trip left in the card's cache. At a 2048-token
|
||||
* chunk the two projections take about 3.0 and 0.9 ms reading the host arena against 1.4 and
|
||||
* 0.3 ms reading VRAM. One pass of the link into VRAM is 10.5 MB at a chunk and 5 KB a token
|
||||
* at decode. */
|
||||
b_embd = decl_b(b, nm.f("ple_emb_dev"), g.act_dtype, {g.max_tok, c.embed_dim});
|
||||
b_k = decl_b(b, nm.f("ple_k"), g.act_dtype, {g.max_tok, HN});
|
||||
b_v = decl_b(b, nm.f("ple_v"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
b_gv = decl_b(b, nm.f("ple_gv"), g.act_dtype, {g.max_tok, HN});
|
||||
b_gvn = decl_b(b, nm.f("ple_gvn"), g.act_dtype, {g.max_tok, HN});
|
||||
b_out = decl_b(b, nm.f("ple_out"), g.act_dtype, {g.max_tok, HN});
|
||||
if (!b_ids || !b_emb || !b_embd || !b_k || !b_v || !b_gv || !b_gvn || !b_out)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* NO DERIVED BUFFER FOR THE STATE SLOTS, and that is worth saying because the obvious reading
|
||||
* of the core says otherwise. `conv_state_index` exists, computes exactly the cursor these two
|
||||
* states want, and is called by NO architecture plugin: rad_block_gdn_fp8.h takes
|
||||
* `cv->state_index` straight off RadKVGroupBatch, which the step batch fills PER GROUP. This
|
||||
* block does the same -- one fewer per-step computation, and the same number the working
|
||||
* precedent uses.
|
||||
*
|
||||
* ---- the ops, in the order step() issues them ------------------------------------------- */
|
||||
layer_ = layer;
|
||||
|
||||
op_ids = rw(b, RAD_OP(b, "ngram_ids",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads),
|
||||
RAD_INT("ngram", c.ngram), RAD_INT("eos", c.eos)),
|
||||
RAD_WEIGHTS(w_mult, w_vsz, w_off)),
|
||||
{}, {b_ids});
|
||||
|
||||
/* M IS T * heads HERE, not T: the gather fetches one table row per HEAD per token, and the
|
||||
* band this op resolves on is that count. */
|
||||
if (table_bf16)
|
||||
op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
|
||||
RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_table)),
|
||||
{b_ids}, {b_emb});
|
||||
else
|
||||
op_gather = rw(b, RAD_OP(b, "embed_lookup_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * c.heads), RAD_INT("n_embd", HD),
|
||||
RAD_INT("n_vocab", c.rows), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_table, w_scale)),
|
||||
{b_ids}, {b_emb});
|
||||
|
||||
op_embd = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.embed_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{b_emb}, {b_embd});
|
||||
|
||||
op_key = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", HN),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_key)),
|
||||
{b_embd}, {b_k});
|
||||
op_value = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", c.embed_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_value)),
|
||||
{b_embd}, {b_v});
|
||||
|
||||
/* `q` IS THE INCOMING STREAM ITSELF, un-normed: the op owns all three norms because the third
|
||||
* is taken over bytes it wrote. */
|
||||
op_gate = rw(b, RAD_OP(b, "ple_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_F64("eps", g.eps),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)),
|
||||
RAD_WEIGHTS(w_nk, w_nq, w_nc)),
|
||||
{b_k, w.h, b_v}, {b_gv, b_gvn});
|
||||
|
||||
op_conv = rw(b, RAD_OP(b, "ple_conv",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
|
||||
RAD_INT("width", c.conv_width), RAD_INT("dilation", c.dilation),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_conv)),
|
||||
{b_gvn, b_gv}, {b_out});
|
||||
|
||||
/* AND THE ADD INTO THE STREAM. The reference is `hidden_states = hidden_states + ple(...)`,
|
||||
* and `ple(...)` is what ple_conv already produced -- the convolution's residual operand
|
||||
* folded the layer's own `gv + silu(conv)`, so what is left is one add of the whole thing. */
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", HN),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h, b_out}, {w.h});
|
||||
|
||||
if (!op_ids || !op_gather || !op_embd || !op_key || !op_value || !op_gate || !op_conv ||
|
||||
!op_add)
|
||||
return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE SLOTS COME OFF THE GROUP BATCH, per group, exactly as the gated delta net reads them. And
|
||||
* `has_init` is `ctx_lens`: a sequence with computed tokens behind it has a history, one without
|
||||
* has none, which is the same test rad_block_gdn_fp8.h makes of the same field.
|
||||
*
|
||||
* THE TWO WINDOWED OPS ARE ISSUED ONCE PER HALF OF THE STEP. The step is sorted decode-first, so
|
||||
* the decode rows are sequences [0, D) holding tokens [0, DT) and the prefill chunks are sequences
|
||||
* [D, S) holding the rest (batch_split). The decode half passes `num_accepted`, which is what
|
||||
* makes the op leave its window in the layout a partly rejected verify can be read back from; the
|
||||
* prefill half passes none, so each chunk leaves its tail at offset zero. A pure step issues one
|
||||
* half, so a pure decode step is one launch and only a mixed step pays a second.
|
||||
*
|
||||
* The prefill half is addressed the way the GDN's is: the per-sequence arrays move to `+ D` and
|
||||
* the token operands stay at their base, because each kernel takes a sequence's rows from the
|
||||
* ABSOLUTE offsets in `cu`. The decode half is the prefix, so it narrows to DT rows instead. */
|
||||
/* THE HASH GOES FIRST IN THE STEP, AHEAD OF EVERY LAYER. It reads the batch's token ids and its
|
||||
* own rolling window and nothing the trunk computes, so it can run as soon as the batch has been
|
||||
* uploaded. The gather that consumes it runs on the host and has to wait for it; issued here, that
|
||||
* wait is for one small kernel, and the layers issued between the two keep the device busy while
|
||||
* the host gathers. Issued at the layer, the wait would be for every layer in front of it, and the
|
||||
* device would sit idle through the gather. */
|
||||
inline void PleLayer::ids(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
|
||||
const RadKVGroupBatch* tk = kv_batch(batch, kv_tok);
|
||||
const int32_t* tk_idx = tk ? tk->state_index : nullptr;
|
||||
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t P = S - D;
|
||||
|
||||
if (D > 0)
|
||||
RAD_ISSUE_N(c_, op_ids, DT,
|
||||
praw(batch->token_ids, RAD_I32, DT), kv_cache(kv_tok, layer_),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
praw(tk_idx, RAD_I32, D),
|
||||
praw(batch->ctx_lens, RAD_I32, D),
|
||||
praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(b_ids, DT), RAD_NONE);
|
||||
/* THE PROMPT THAT FOLLOWS the last prefill chunk is hashed in the same launch, into the rows
|
||||
* after the step's: `tok` then reaches past the step by that many tokens, and the window the
|
||||
* op leaves behind is the step's alone. */
|
||||
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c_, op_ids, T,
|
||||
praw(batch->token_ids, RAD_I32, T + A), kv_cache(kv_tok, layer_),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
|
||||
RAD_W(w_mult), RAD_W(w_vsz), RAD_W(w_off),
|
||||
praw(tk_idx ? tk_idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P),
|
||||
RAD_NONE,
|
||||
brows(b_ids, T),
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
}
|
||||
|
||||
inline void PleLayer::step(RadCtx* c_, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t S = batch->n_seq;
|
||||
const int64_t HD = c.head_dim();
|
||||
|
||||
const RadKVGroupBatch* cv = kv_batch(batch, kv_conv);
|
||||
const int32_t* cv_idx = cv ? cv->state_index : nullptr;
|
||||
|
||||
int64_t D = 0, DT = 0;
|
||||
batch_split(batch, &D, &DT);
|
||||
const int64_t P = S - D;
|
||||
|
||||
/* T ROWS, not T * heads: the buffer is [max_tok, embed_dim] and the gather derives its own
|
||||
* 16-rows-a-token reading out of numel. The op's M band is still T * heads -- that is how many
|
||||
* table rows it fetches -- but the OPERAND is the token count. */
|
||||
/* The ids of the prompt that follows, which the gather's reader fetches while this step
|
||||
* runs, so the next step finds its rows already read. */
|
||||
const int64_t A = P > 0 ? ahead_rows(batch) : 0;
|
||||
RAD_ISSUE_N(c_, op_gather, T * c.heads,
|
||||
brows(b_ids, T), RAD_W(w_table), table_bf16 ? RAD_NONE : RAD_W(w_scale),
|
||||
brows(b_emb, T),
|
||||
A > 0 ? brow_slice(b_ids, T, A, c.heads) : RAD_NONE);
|
||||
(void)HD;
|
||||
|
||||
RAD_ISSUE_N(c_, op_embd, T, brows(b_emb, T), brows(b_embd, T));
|
||||
RAD_ISSUE_N(c_, op_key, T, brows(b_embd, T), RAD_W(w_key), brows(b_k, T));
|
||||
RAD_ISSUE_N(c_, op_value, T, brows(b_embd, T), RAD_W(w_value), brows(b_v, T));
|
||||
|
||||
RAD_ISSUE_N(c_, op_gate, T,
|
||||
brows(b_k, T), brows(w.h, T), brows(b_v, T),
|
||||
RAD_W(w_nk), RAD_W(w_nq), RAD_W(w_nc),
|
||||
brows(b_gv, T), brows(b_gvn, T));
|
||||
|
||||
if (D > 0)
|
||||
RAD_ISSUE_N(c_, op_conv, DT,
|
||||
brows(b_gvn, DT), RAD_W(w_conv), kv_cache(kv_conv, layer_),
|
||||
praw(batch->cu_seqlens, RAD_I32, D + 1), brows(b_gv, DT),
|
||||
praw(cv_idx, RAD_I32, D),
|
||||
praw(batch->ctx_lens, RAD_I32, D),
|
||||
praw(batch->num_accepted, RAD_I32, D),
|
||||
brows(b_out, DT));
|
||||
if (P > 0)
|
||||
RAD_ISSUE_N(c_, op_conv, T,
|
||||
brows(b_gvn, T), RAD_W(w_conv), kv_cache(kv_conv, layer_),
|
||||
praw(batch->cu_seqlens + D, RAD_I32, P + 1), brows(b_gv, T),
|
||||
praw(cv_idx ? cv_idx + D : nullptr, RAD_I32, P),
|
||||
praw(batch->ctx_lens + D, RAD_I32, P),
|
||||
RAD_NONE,
|
||||
brows(b_out, T));
|
||||
|
||||
/* M IS T, not T * HN. `add` counts ROWS of `n` -- every other block in this tree issues it
|
||||
* that way -- and the declared band is 1..max_tok. Passing the element count instead lands
|
||||
* outside every band of the op's own bucket table and the run phase refuses the step. */
|
||||
RAD_ISSUE_N(c_, op_add, T, brows(w.h, T), brows(b_out, T), brows(w.h, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_PLE_H */
|
||||
@@ -0,0 +1,345 @@
|
||||
/* rad_block_vit.h -- the Qwen-VL vision tower (Qwen2.5-VL / Qwen3-VL / Qwen3.5 / Qwen3.8), and the
|
||||
* scatter that puts its rows into a language model's embeddings.
|
||||
*
|
||||
* 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)
|
||||
* x += pos_embed resampled to each segment's grid bilinear, corners aligned (grid_embed)
|
||||
* depth times:
|
||||
* x += proj(attn(rope(qkv(LN1(x))))) full attention within a segment (one image, or
|
||||
* one temporal group of a video), 2-D rotary over
|
||||
* (row, column) -- `axial` with half the rotated
|
||||
* width a side, each on its own ladder
|
||||
* x += fc2(gelu_tanh(fc1(LN2(x))))
|
||||
* out = fc2'(gelu(fc1'(LN(x) viewed [P/merge^2, merge^2 * width]))) the patch merger
|
||||
*
|
||||
* which is transformers' Qwen3_5VisionModel with no deepstack taps (the checkpoints this tree
|
||||
* serves list none, and one that did would be refused at declare). Every linear layer is
|
||||
* `gemm_nt_bias` with its activation and residual in the epilogue, each rounded where the
|
||||
* reference's separate tensors are.
|
||||
*
|
||||
* EVERY RANK RUNS THE WHOLE TOWER. Its weights are replicated rather than sharded: the rows are
|
||||
* needed on every rank (each rank embeds every token), and a tower split across ranks would pay a
|
||||
* collective per layer to save compute that happens once per picture. The weights are
|
||||
* RAD_ACCESS_PER_REQUEST, so placement may keep them off the card when VRAM is short.
|
||||
*
|
||||
* ITS ACTIVATIONS ARE SIZED BY THE PASS, not by a step: RadBuildCtx::max_enc_patches rows. A
|
||||
* sizing declare (shape_probe) sizes them by the probe's step instead, which keeps the tower out
|
||||
* of the smaller arena levels -- an encoder pass always runs at the full plan (Engine::arena_step).
|
||||
*/
|
||||
#ifndef RAD_BLOCK_VIT_H
|
||||
#define RAD_BLOCK_VIT_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct VisionTower {
|
||||
/* Geometry, from the container's vision_config. */
|
||||
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, temporal = 0, chans = 0;
|
||||
int64_t merge = 0, side = 0, n_embd = 0, head_dim = 0, patch_dim = 0, P = 0;
|
||||
float eps = 1e-6f, theta = 10000.0f;
|
||||
bool on = false;
|
||||
|
||||
struct Layer {
|
||||
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
|
||||
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
|
||||
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
|
||||
rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
|
||||
};
|
||||
std::vector<Layer> L;
|
||||
rad_weight w_patch = 0, b_patch = 0, w_pos = 0;
|
||||
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
|
||||
rad_op op_patch = 0, op_pos = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
|
||||
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mf = 0, b_out = 0;
|
||||
char sec[48] = {};
|
||||
|
||||
/* Is there a tower to declare: the container carries one and the deployment asked for media.
|
||||
* `why` is set when the container carries one this block cannot serve. */
|
||||
static bool present(const RadModelMeta* m) {
|
||||
return rad_meta_geti(m, "vision_config.depth", 0) > 0;
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
|
||||
int64_t model_embd, int first_group);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int VisionTower::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);
|
||||
const int64_t npos = rad_meta_geti(m, "vision_config.num_position_embeddings", 0);
|
||||
theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta",
|
||||
rad_meta_getf(m, "vision_config.rope_theta", 10000.0));
|
||||
side = (int64_t)std::llround(std::sqrt((double)npos));
|
||||
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 ||
|
||||
merge <= 0 || n_embd <= 0 || side <= 0 || side * side != npos || width % heads) {
|
||||
fprintf(stderr, "radiance: the container's vision_config is incomplete or inconsistent "
|
||||
"(depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, merge %lld, "
|
||||
"positions %lld)\n", (long long)depth, (long long)width, (long long)heads,
|
||||
(long long)ff, (long long)patch, (long long)merge, (long long)npos);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* THE MERGER WRITES ROWS OF THE MODEL'S OWN WIDTH, or its rows could not replace a token's. */
|
||||
if (n_embd != model_embd) {
|
||||
fprintf(stderr, "radiance: 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;
|
||||
}
|
||||
/* DEEPSTACK -- tower layers feeding the language model's early layers directly -- is a second
|
||||
* input path this block does not carry. Refused by name rather than dropped. */
|
||||
const char* ds = rad_meta_gets(m, "vision_config.deepstack_visual_indexes", "");
|
||||
for (const char* q = ds; q && *q; ++q)
|
||||
if (*q >= '0' && *q <= '9') {
|
||||
fprintf(stderr, "radiance: this vision tower has deepstack taps (%s), which this plugin "
|
||||
"does not serve\n", ds);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
|
||||
if (std::strcmp(act, "gelu_pytorch_tanh") && std::strcmp(act, "gelu")) {
|
||||
fprintf(stderr, "radiance: vision_config.hidden_act '%s' is not served\n", act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const char* mlp_act = std::strcmp(act, "gelu") ? "gelu_tanh" : "gelu";
|
||||
head_dim = width / heads;
|
||||
patch_dim = chans * temporal * patch * patch;
|
||||
/* The 2-D rotary: half the head a side, each on its own ladder. */
|
||||
if (head_dim % 4) return RAD_E_SHAPE;
|
||||
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 in a sizing declare too. It is a
|
||||
* fixed parameter the kernel is chosen by, and the engine runs the real declare's kernel at
|
||||
* every level; only the ranged row counts may follow the probe's step. */
|
||||
const int64_t max_seg = P;
|
||||
if (ctx->shape_probe) {
|
||||
/* A sizing declare: the tower's rows follow the probe's step, which keeps its activations
|
||||
* out of the levels a decode step runs at. Rounded to a whole merged row. */
|
||||
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 and the merger, and one group a
|
||||
* block from `first_group` on, past every language layer, so a tower block is its own unit
|
||||
* of movement and never shares one with a text layer. */
|
||||
auto bw = [&](const char* dn, const char* src, uint32_t dt, std::initializer_list<int64_t> shp,
|
||||
RadWeightGroup g) -> rad_weight {
|
||||
/* the map first: it is how the checkpoint is asked what the weight is */
|
||||
if (map_copy(b, dn, src) < 0) return 0;
|
||||
return decl_w(b, dn, dt, shp, ACC, RAD_SHARD_NONE, g);
|
||||
};
|
||||
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("model.visual.patch_embed.proj.weight"),
|
||||
RAD_BF16, { width, patch_dim }, grp_model());
|
||||
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("model.visual.patch_embed.proj.bias"),
|
||||
RAD_BF16, { width }, grp_model());
|
||||
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("model.visual.pos_embed.weight"),
|
||||
RAD_BF16, { npos, 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;
|
||||
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt("model.visual.blocks.%d.norm1.weight", li), RAD_BF16, { width }, g);
|
||||
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt("model.visual.blocks.%d.norm1.bias", li), RAD_BF16, { width }, g);
|
||||
l.qkv_w = bw(nm.f("v.blk.%d.qkv.weight", li), nm.ckpt("model.visual.blocks.%d.attn.qkv.weight", li), RAD_BF16, { 3 * width, width }, g);
|
||||
l.qkv_b = bw(nm.f("v.blk.%d.qkv.bias", li), nm.ckpt("model.visual.blocks.%d.attn.qkv.bias", li), RAD_BF16, { 3 * width }, g);
|
||||
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt("model.visual.blocks.%d.attn.proj.weight", li), RAD_BF16, { width, width }, g);
|
||||
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt("model.visual.blocks.%d.attn.proj.bias", li), RAD_BF16, { width }, g);
|
||||
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt("model.visual.blocks.%d.norm2.weight", li), RAD_BF16, { width }, g);
|
||||
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt("model.visual.blocks.%d.norm2.bias", li), RAD_BF16, { width }, g);
|
||||
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc1.weight", li), RAD_BF16, { ff, width }, g);
|
||||
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc1.bias", li), RAD_BF16, { ff }, g);
|
||||
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc2.weight", li), RAD_BF16, { width, ff }, g);
|
||||
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt("model.visual.blocks.%d.mlp.linear_fc2.bias", li), RAD_BF16, { width }, g);
|
||||
}
|
||||
mn_w = bw(nm.f("v.merger.norm.weight"), nm.ckpt("model.visual.merger.norm.weight"), RAD_BF16, { width }, grp_model());
|
||||
mn_b = bw(nm.f("v.merger.norm.bias"), nm.ckpt("model.visual.merger.norm.bias"), RAD_BF16, { width }, grp_model());
|
||||
m1_w = bw(nm.f("v.merger.fc1.weight"), nm.ckpt("model.visual.merger.linear_fc1.weight"), RAD_BF16, { mm * width, mm * width }, grp_model());
|
||||
m1_b = bw(nm.f("v.merger.fc1.bias"), nm.ckpt("model.visual.merger.linear_fc1.bias"), RAD_BF16, { mm * width }, grp_model());
|
||||
m2_w = bw(nm.f("v.merger.fc2.weight"), nm.ckpt("model.visual.merger.linear_fc2.weight"), RAD_BF16, { n_embd, mm * width }, grp_model());
|
||||
m2_b = bw(nm.f("v.merger.fc2.bias"), nm.ckpt("model.visual.merger.linear_fc2.bias"), RAD_BF16, { n_embd }, grp_model());
|
||||
if (!w_patch || !b_patch || !w_pos || !mn_w || !mn_b || !m1_w || !m1_b || !m2_w || !m2_b)
|
||||
return RAD_E_INVAL;
|
||||
|
||||
/* ---- activations. `mh` is the merger's input, declared at the MERGED width: the norm writes
|
||||
* it as P rows of `width` and the first merger layer reads it as P/mm rows of mm * width,
|
||||
* which is the same bytes -- 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_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
|
||||
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width });
|
||||
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, mm * width });
|
||||
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
|
||||
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || !b_mf || !b_out) return RAD_E_INVAL;
|
||||
|
||||
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
|
||||
rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "gemm_nt_bias",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
auto lnorm = [&](int64_t rows, rad_weight w, rad_weight bias) -> rad_op {
|
||||
return RAD_OP(b, "layernorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width),
|
||||
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w, bias));
|
||||
};
|
||||
|
||||
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
|
||||
op_pos = rw(b, RAD_OP(b, "grid_embed",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
|
||||
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(w_pos)),
|
||||
{ b_x }, { b_x });
|
||||
for (Layer& l : L) {
|
||||
l.ln1 = rw(b, lnorm(P, l.n1w, l.n1b), { b_x }, { b_h });
|
||||
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
|
||||
l.rope = rw(b, RAD_OP(b, "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("scale", 1.0),
|
||||
RAD_STR("mode", "axial"),
|
||||
RAD_INT("rotary_dim", head_dim),
|
||||
RAD_STR("sections", sec)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv }, { b_qkv });
|
||||
l.attn = rw(b, RAD_OP(b, "attn_dense",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("gqa", 1), RAD_INT("causal", 0),
|
||||
RAD_STR("dtype", "bf16"),
|
||||
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
|
||||
RAD_INT("max_seqlen", max_seg)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ b_qkv }, { b_att });
|
||||
l.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
|
||||
l.ln2 = rw(b, lnorm(P, l.n2w, l.n2b), { b_x }, { b_h });
|
||||
l.up = rw(b, gemm(P, ff, width, mlp_act, l.up_w, l.up_b), { b_h }, { b_ff });
|
||||
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
|
||||
}
|
||||
op_mln = rw(b, lnorm(P, mn_w, mn_b), { b_x }, { b_mh });
|
||||
op_m1 = rw(b, gemm(R, mm * width, mm * width, "gelu", m1_w, m1_b), { b_mh }, { b_mf });
|
||||
op_m2 = rw(b, gemm(R, n_embd, mm * width, "none", m2_w, m2_b), { b_mf }, { b_out });
|
||||
|
||||
if (!ctx->shape_probe) {
|
||||
RadEncoderDecl e{};
|
||||
e.name = "vision";
|
||||
e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO;
|
||||
e.patch_dim = patch_dim;
|
||||
e.merge = mm;
|
||||
e.max_patches = P;
|
||||
e.n_embd = n_embd;
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x "
|
||||
"%lld x %lld, merge %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, (long long)temporal, (long long)patch, (long long)patch,
|
||||
(long long)merge, (long long)P, (long long)R, (long long)n_embd);
|
||||
}
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void VisionTower::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;
|
||||
}
|
||||
/* The patches, their coordinates -- planes 0 and 1 are a dense [2, P] (row, column), all four
|
||||
* a dense [4, P] -- and the segment boundaries, all 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 crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
|
||||
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
|
||||
|
||||
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
|
||||
brows(b_qkv, Pn));
|
||||
RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), rc);
|
||||
RAD_ISSUE_N(c, l.attn, Pn,
|
||||
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
|
||||
brows(b_x, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
|
||||
brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
|
||||
brows(b_x, Pn), brows(b_x, Pn));
|
||||
}
|
||||
/* The merger norm writes P rows of `width` into a buffer declared at the merged width: the
|
||||
* same bytes the next layer reads as P/mm rows. */
|
||||
RAD_ISSUE_N(c, op_mln, Pn, brows(b_x, Pn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mh, Rn));
|
||||
RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b), RAD_NONE,
|
||||
brows(b_mf, Rn));
|
||||
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
|
||||
brows(b_out, Rn));
|
||||
}
|
||||
|
||||
/* ================================================================== the encoder rows
|
||||
*
|
||||
* THE ROWS AN ENCODER PRODUCED, OVER THE TOKEN EMBEDDINGS THEY REPLACE (RadBatch::mm_rows). One
|
||||
* `scatter_rows` over opaque bytes: a row is `n_embd` bf16, the destination the embedding buffer.
|
||||
*
|
||||
* ISSUE IT BEFORE THE EMBEDDING'S REDUCTION. The lookup is vocab-sharded, so each rank's output is
|
||||
* a partial sum, and the core hands rank 0 the encoder rows and every other rank zeros: overwritten
|
||||
* there, the reduction that follows -- an all_reduce, or the first layer's fused norm -- counts
|
||||
* each row once, as it counts a token's embedding once. */
|
||||
struct MediaRows {
|
||||
rad_op op = 0;
|
||||
int64_t n_embd = 0;
|
||||
|
||||
int declare(RadBuilder* b, int64_t max_tok, int64_t width, rad_buf embd) {
|
||||
n_embd = width;
|
||||
op = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, max_tok), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ embd }, { embd });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* `embd` narrowed to this pass's tokens; nothing is issued on a pass with no media rows. */
|
||||
void step(RadCtx* c, const RadBatch* batch, rad_buf embd, int64_t T) const {
|
||||
if (!op || batch->n_mm_rows <= 0) return;
|
||||
RAD_ISSUE_N(c, op, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(embd, T));
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_BLOCK_VIT_H */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,456 @@
|
||||
/* rad_qsa.h -- Qwen4-Exp's QSA indexer: the part of a full-attention layer that decides WHICH
|
||||
* blocks of key history that layer's attention reads.
|
||||
*
|
||||
* docs/QSA.md is the decomposition and the argument; this is the declaration side of it. The
|
||||
* kernels are libr4d's `qsa_block_key`, `qsa_score` and `qsa_select`, and the sparse attention is
|
||||
* the ORDINARY `attn_paged` issued with the selection in place of the sequence's own block table
|
||||
* -- both of those are plain operands, so nothing in core/ learns what QSA is.
|
||||
*
|
||||
* WHAT IS HERE is the whole indexer: the projection and the query path, the block-key path with
|
||||
* its two states, and the score and selection the sparse attention is issued with. Below
|
||||
* `budget + ratio - 1` tokens of context the selection is EVERY visible block, so the sparse path
|
||||
* must reproduce the dense path's text byte for byte -- which is the oracle any change to this
|
||||
* file is checked against.
|
||||
*/
|
||||
#ifndef RAD_QSA_H
|
||||
#define RAD_QSA_H
|
||||
|
||||
#include "rad_arch.h"
|
||||
#include "rad_fp8.h"
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct QsaIndexer {
|
||||
struct Config {
|
||||
int64_t heads = 0; /* indexer_n_heads -- 4 */
|
||||
int64_t head_dim = 0; /* indexer_head_dim -- 128 */
|
||||
int64_t ratio = 0; /* indexer_compress_ratio -- 4 tokens a block */
|
||||
int64_t budget = 0; /* indexer_budget -- 2048 tokens, so 512 blocks */
|
||||
int64_t rot = 0; /* the LAYER's rotary width, which the indexer shares */
|
||||
const char* mode = "neox";
|
||||
/* Checkpoint names. Absent means this layer has no indexer and declare() is a no-op. */
|
||||
const char* qk_proj = nullptr;
|
||||
const char* q_norm = nullptr;
|
||||
const char* k_norm = nullptr;
|
||||
/* Derived, and all four are the caller's because they size things it declares. */
|
||||
int64_t topk = 0; /* budget / ratio -- blocks the selection keeps */
|
||||
int64_t max_blocks = 0; /* max_ctx / ratio -- the widest block table */
|
||||
int64_t max_work = 0; /* ceil(max_tok / ratio) + max_seqs */
|
||||
/* THE TAIL'S RING LENGTH, `ratio + max_spec`, and the `max_spec` is the whole of it.
|
||||
*
|
||||
* A tail of exactly `ratio` rows indexed by `pos % ratio` is right when a step's tokens
|
||||
* are the tokens that happened. Under speculation they are not: a verify step runs
|
||||
* 1 + n_spec positions and the next step RESTARTS at the first rejected one, so positions
|
||||
* the tail has already overwritten are needed again. Concretely at ratio 4, depth 3,
|
||||
* positions 9..12 -- the store writes slots 1,2,3,0 and position 12 lands on the slot
|
||||
* position 8 is still owed to. Accept one and the next step rebuilds block 2 (tokens
|
||||
* 8..11) out of a slot holding token 12. That block key is then wrong in the cache for
|
||||
* the rest of the sequence, and it happens on any step that straddles a block boundary
|
||||
* and does not accept everything -- which is most of them.
|
||||
*
|
||||
* The deepest rollback is to the first draft, so the widest window a step can still owe
|
||||
* is [p0 - ratio + 1, p0 + n_spec]: ratio + n_spec positions, each needing its own
|
||||
* residue. Under `ratio + max_spec` a slot is only ever overwritten by a position that
|
||||
* far ahead, which is past the end of the step that could ask for it. */
|
||||
int64_t ring = 0; /* ratio + max_spec */
|
||||
/* THE ATTENTION GROUP, because the SELECTION's output is what the attention reads and so
|
||||
* it is that group's page ids that come out. The block-key group is this block's own and
|
||||
* is declared on first use -- see declare(). */
|
||||
rad_kvgroup kv_attn = 0;
|
||||
/* THE TAIL'S GROUP: one RAD_KV_LINEAR state a sequence a layer, `ring` rows of
|
||||
* `head_dim`. It is a KV group and not a buffer because a buffer has no way to name a
|
||||
* SEQUENCE -- see the note on Wire. */
|
||||
rad_kvgroup kv_tail = 0;
|
||||
/* DOES ANYTHING READ THE SELECTION? False on the DENSE path, where the attention is
|
||||
* issued with the sequence's own block table and `sel` is written for nobody. The block-key
|
||||
* half still runs -- it is STATEFUL, and a history built without it is a history the sparse
|
||||
* path could not later read -- but the score and the selection are then dead work, and on
|
||||
* this model they are the largest op in the indexer. Declared either way, so the graph and
|
||||
* the buffer plan do not depend on it. */
|
||||
bool emit_sel = true;
|
||||
};
|
||||
|
||||
/* The two planes the front half produces. `qk` is the projection whole -- `heads` query heads
|
||||
* then ONE raw key head -- and `q` is the query heads normed and rotated, contiguous.
|
||||
*
|
||||
* THE RAW KEY IS NEVER NORMED OR ROTATED HERE. It is pooled over `ratio` tokens FIRST and the
|
||||
* norm and the rotation happen to the pooled result, at the position of the block's first
|
||||
* token (`qsa_block_key`). Reading the reference quickly gives the opposite impression,
|
||||
* because the q path right above it does both. */
|
||||
struct Wire {
|
||||
rad_buf qk = 0; /* [max_tok, (heads + 1) * head_dim] */
|
||||
rad_buf q = 0; /* [max_tok, heads * head_dim] */
|
||||
/* THE TAIL IS NOT IN THIS WIRE AND CANNOT BE. Every other buffer here is within-step
|
||||
* scratch, which is why one set serves the whole model; the tail carries an unfinished
|
||||
* block's RAW INDEX KEYS ACROSS STEPS, and that makes it state with two axes a buffer
|
||||
* cannot express.
|
||||
*
|
||||
* THE LAYER. The keys are `index_qk_proj`'s output and that weight is PER LAYER, so a
|
||||
* shared tail has layer L pooling layer L-1's keys -- at decode three of every four
|
||||
* keys in a completing block come from the wrong layer. Every layer needs its own,
|
||||
* including the MTP head's.
|
||||
*
|
||||
* THE SEQUENCE. A per-layer buffer indexed by the BATCH ROW is no better across
|
||||
* requests: the row is step-local -- the scheduler builds the step from `running_` in
|
||||
* priority order and then stable-sorts decode first -- so a sequence that outlives an
|
||||
* earlier one shifts down a row and inherits its keys. A buffer has no per-sequence
|
||||
* axis to index instead; a KV group does, and that is the one the engine keeps stable
|
||||
* for the life of a sequence, zeroes when it hands a slot out, and checkpoints with
|
||||
* the rest of the linear state when the prefix cache saves one.
|
||||
*
|
||||
* So the tail is `Config::kv_tail`, a RAD_KV_LINEAR group, and declare() binds this
|
||||
* layer to it. Nothing about it belongs to a wire shared by every layer. */
|
||||
rad_buf stage = 0; /* [max_work * ratio, head_dim] */
|
||||
rad_buf page = 0; /* [max_work] i32 */
|
||||
rad_buf bpos = 0; /* [max_work] i32, or [max_work, 3] under M-RoPE */
|
||||
rad_buf nc = 0; /* [max_seqs] i32 */
|
||||
/* The selection, ONE ROW A QUERY and not one a sequence. At decode the two are the same
|
||||
* thing; at prefill a chunk's queries share one history and each picks its own set out of
|
||||
* it, which is the whole of Stage B (docs/QSA.md). `sel` and `seqused` are what the sparse
|
||||
* attention is issued with in place of the sequence's own block table and length.
|
||||
*
|
||||
* `score` IS THE BIG ONE: max_tok * max_ctx/ratio floats, 134 MB at a 2048-token chunk and
|
||||
* 64K of context. It is one buffer for the whole model rather than one a layer, and
|
||||
* declare() refuses a geometry whose product is unreasonable rather than discovering it as
|
||||
* an allocation failure. Tiling the query axis would cap it, and the reason it is not done
|
||||
* is that `cu` is absolute over the batch: a tile would need its rows rebased, which means
|
||||
* a per-token sequence id operand -- qsa_work is where it would come from. */
|
||||
rad_buf score = 0; /* [max_tok, max_blocks] f32 */
|
||||
rad_buf sel = 0; /* [max_tok, topk + 1] i32 */
|
||||
rad_buf nsel = 0; /* [max_tok] i32 */
|
||||
rad_buf sequ = 0; /* [max_tok] i32 */
|
||||
/* THE MODEL'S cos/sin PLANE, [rope_table_rows, rot], or 0 if it builds none. It is the
|
||||
* attention block's -- `rope_table` fills it once a step for every layer -- and the
|
||||
* indexer's own rotation is at the same `rot`, `theta` and `scale`, so the rows are
|
||||
* already there. A block handed no table asks for no fusion and runs the per-head norms
|
||||
* below, which is what keeps a plugin that does not build the table on the unfused
|
||||
* path. */
|
||||
rad_buf cos_sin = 0;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Config c{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_weight w_qn = 0, w_kn = 0;
|
||||
LinearFP8 proj{};
|
||||
rad_kvgroup kv_bk = 0;
|
||||
rad_op op_norm = 0, op_rope = 0, op_qprep = 0;
|
||||
/* The most rows `op_qprep` may be issued over, 0 when it is not declared. It is the model's
|
||||
* own `qk_fuse_rows` and it is NOT a tuning: the cos/sin table is filled only for steps at or
|
||||
* under it, so above it the rows this op would read were never written. */
|
||||
int64_t qprep_rows = 0;
|
||||
rad_op op_work = 0, op_bkey = 0, op_tail = 0, op_score = 0, op_select = 0;
|
||||
|
||||
bool on() const { return op_rope != 0; }
|
||||
|
||||
/* `bk` is the block-key KV group, created on FIRST USE and shared by every QSA layer after
|
||||
* that -- which is why it is an in/out parameter rather than a member. It cannot be declared
|
||||
* with the model's other groups: `Builder::find_kv_consumer` binds a group to the first op
|
||||
* declared AFTER it that carries a `block_size`, and between a model-level declaration and
|
||||
* this block's `qsa_block_key` there is a whole layer of other ops. Declared immediately
|
||||
* before its own consumer, the binding cannot be anything else. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
|
||||
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
|
||||
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const Config& cfg, const Wire& wire, const ActFP8& in,
|
||||
rad_kvgroup* bk) {
|
||||
g = geom; c = cfg; w = wire; layer = l;
|
||||
if (!c.qk_proj || !c.q_norm) return RAD_OK; /* no indexer on this layer */
|
||||
if (c.heads <= 0 || c.head_dim <= 0 || c.ratio <= 0 || c.budget <= 0) return RAD_E_INVAL;
|
||||
if (!w.qk || !w.q) return RAD_E_INVAL;
|
||||
/* The rotation is the LAYER's and it has to fit inside the index head, which the checkpoint's
|
||||
* own validator also requires -- so a container that violated it is refused here by name
|
||||
* rather than rotating past the end of a head. */
|
||||
if (c.rot < 0 || c.rot > c.head_dim || (c.rot & 1)) return RAD_E_SHAPE;
|
||||
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim; /* the projection width */
|
||||
|
||||
RAD_ARCH_TRY(proj.declare(b, nm, g, nm.f("blk.%d.qsa_qk", l), nw, g.n_embd,
|
||||
RAD_SHARD_NONE, grp_layer(l), { c.qk_proj }, in, w.qk));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_q_norm.weight", l), c.q_norm));
|
||||
w_qn = decl_w(b, nm.f("blk.%d.qsa_q_norm.weight", l), RAD_F32, { c.head_dim },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_qn) return RAD_E_INVAL;
|
||||
|
||||
/* ONE DECLARED NORM, ISSUED ONCE A HEAD, and the reason is the projection's layout rather
|
||||
* than a preference. `qk` is `heads + 1` heads wide, so the query heads are 128 apart WITHIN
|
||||
* a token and 640 apart ACROSS tokens -- which is not a stride any rank-2 view can express,
|
||||
* and the ABI narrows dim 0 or the last dimension and nothing between. A column slice of ONE
|
||||
* head is expressible, so the norm runs `heads` times and writes into a contiguous `q` that
|
||||
* the rotation can then take whole.
|
||||
*
|
||||
* Four extra launches a layer, and for a 128-wide row the launch IS the cost: the norms and
|
||||
* the ropes across the model's indexer layers are a real slice of a decode step against
|
||||
* microseconds of arithmetic. `op_qprep` is the fused form that replaces them.
|
||||
*
|
||||
* THE FUSED FORM IS `qk_norm_rope_gate`'S K SIDE, not a new op. That kernel already reads a
|
||||
* plain [tokens, heads, head_dim] input at the operand's OWN row pitch and writes the heads
|
||||
* contiguously -- which is exactly this projection's query half inside its `heads + 1` width
|
||||
* -- and it already rounds the norm to bf16 before rotating, because that is what a norm that
|
||||
* stores a tensor and a rope that reads it back do. The only thing its q side adds is the
|
||||
* [q|gate] split, and there is no gate here, so `n_head` 0 asks for the half that fits and
|
||||
* passes no q operands at all. Five launches a layer become one.
|
||||
*
|
||||
* IT NEEDS THE MODEL'S cos/sin TABLE and asks for nothing if it has none. The rotation is at
|
||||
* the same `rot`, `theta` and `scale` as the attention block's, so `rope_table` has already
|
||||
* written the rows this step's positions name -- and a plugin that builds no table leaves
|
||||
* `w.cos_sin` at 0 and runs the per-head norms below unchanged.
|
||||
*
|
||||
* AND ONLY UP TO `qk_fuse_rows`, WHICH IS A CORRECTNESS BOUND AND NOT A TUNING. The model
|
||||
* issues `rope_table` only for steps at or under that row count -- the fusion pays where the
|
||||
* launch is the cost, and a prefill chunk's kernels already fill the card -- so ABOVE it the
|
||||
* table rows this op would read were never written THIS step. It would rotate by another
|
||||
* step's angles: fluent text with a subtly wrong sense of position, which is the failure
|
||||
* `rope_table`'s own note calls out and which nothing downstream would flag. The bound is the
|
||||
* attention block's, off the same function, so the two cannot drift apart. */
|
||||
const bool qprep_neox = !std::strcmp(c.mode, "neox") || !std::strcmp(c.mode, "mrope") ||
|
||||
g.rope_mc;
|
||||
qprep_rows = qk_fuse_rows(g);
|
||||
if (w.cos_sin && qprep_neox && qprep_rows > 0 && (c.head_dim % 32) == 0)
|
||||
op_qprep = rw(b, RAD_OP(b, "qk_norm_rope_gate",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qprep_rows),
|
||||
RAD_INT("head_dim", c.head_dim), RAD_INT("n_head", 0),
|
||||
RAD_INT("n_head_kv", c.heads), RAD_INT("rot", c.rot),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", g.wadd_qk), RAD_INT("cs_f32", 1)),
|
||||
RAD_WEIGHTS(w_qn)),
|
||||
{w.qk, w.cos_sin}, {w.q});
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn)),
|
||||
{w.qk}, {w.q});
|
||||
op_rope = rw(b, decl_rope(b, g, g.max_tok, c.head_dim, c.heads, 0, c.rot, c.mode),
|
||||
{w.q}, {w.q});
|
||||
|
||||
/* ---- the block-key path. Nothing below reads anything above except `w.qk`'s raw-key half. */
|
||||
if (!c.k_norm || !w.stage || !c.topk || !c.max_blocks || !c.max_work)
|
||||
return RAD_E_INVAL;
|
||||
if (!c.kv_tail || c.ring < c.ratio) return RAD_E_INVAL;
|
||||
/* THIS LAYER'S TAIL STATE. The group is the caller's -- it holds one state per sequence per
|
||||
* BOUND LAYER, so binding is how this layer gets its own, and it is the same call the
|
||||
* block-key group needs for the same reason. */
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, c.kv_tail));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.qsa_k_norm.weight", l), c.k_norm));
|
||||
w_kn = decl_w(b, nm.f("blk.%d.qsa_k_norm.weight", l), RAD_F32, { c.head_dim },
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
if (!w_kn) return RAD_E_INVAL;
|
||||
|
||||
op_work = rw(b, RAD_OP(b, "qsa_work",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("ring", c.ring),
|
||||
RAD_INT("seqs", g.max_seqs),
|
||||
RAD_INT("work", c.max_work), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qk}, {w.stage, w.page, w.bpos, w.nc});
|
||||
|
||||
/* THE GROUP IS DECLARED HERE, immediately before the op that sizes it -- see declare()'s
|
||||
* note. `kv_heads` 1, `block_size` the compress ratio and `head_dim` n/(2*ratio) make a page
|
||||
* hold exactly `n` contiguous values, which is one block key, and make the manager allocate
|
||||
* exactly one page per `ratio` tokens. The geometry is a container, not an attention shape. */
|
||||
if (*bk == 0) {
|
||||
if ((c.head_dim % (2 * c.ratio)) != 0) return RAD_E_SHAPE;
|
||||
RadKVGroupDecl d{};
|
||||
d.kind = RAD_KV_FULL;
|
||||
d.dtype = RAD_BF16;
|
||||
d.n_head_kv = 1;
|
||||
d.head_dim = c.head_dim / (2 * c.ratio);
|
||||
*bk = rad_decl_kv_group(b, nm.f("kv_qsa_bkey"), &d);
|
||||
if (!*bk) return RAD_E_INVAL;
|
||||
}
|
||||
kv_bk = *bk;
|
||||
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
|
||||
op_bkey = g.rope_mc
|
||||
? RAD_OP(b, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_WEIGHTS(w_kn))
|
||||
: RAD_OP(b, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
RAD_F64("eps", g.eps), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_F64("wadd", g.wadd_qk),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn));
|
||||
op_bkey = rw(b, op_bkey, {w.stage, w.page, w.bpos}, {});
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv_bk));
|
||||
|
||||
op_tail = rw(b, RAD_OP(b, "qsa_tail_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("ring", c.ring),
|
||||
RAD_INT("seqs", g.max_seqs),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qk}, {});
|
||||
|
||||
/* M IS QUERIES ON BOTH, up to a whole prefill chunk. A band stopping at max_seqs would be
|
||||
* right only for a per-SEQUENCE selection; this one selects per QUERY. */
|
||||
op_score = rw(b, RAD_OP(b, "qsa_score",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("heads", c.heads), RAD_INT("blocks", c.max_blocks),
|
||||
RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q, w.nc}, {w.score});
|
||||
op_select = rw(b, RAD_OP(b, "qsa_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok),
|
||||
RAD_INT("blocks", c.max_blocks), RAD_INT("topk", c.topk),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("seqs", g.max_seqs)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.score, w.nc}, {w.sel, w.nsel, w.sequ});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
|
||||
if (!on()) return;
|
||||
const int64_t T = batch->n_tok, S = batch->n_seq;
|
||||
const int64_t qw = c.heads * c.head_dim;
|
||||
const int64_t nw = (c.heads + 1) * c.head_dim;
|
||||
const int64_t koff = qw; /* the raw-key head, after the query heads */
|
||||
|
||||
proj.step(c_, in, w.qk, T);
|
||||
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
|
||||
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
|
||||
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
|
||||
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
|
||||
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
|
||||
*
|
||||
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
|
||||
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
|
||||
RAD_ISSUE_N(c_, op_qprep, T,
|
||||
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
|
||||
RAD_NONE, RAD_W(w_qn),
|
||||
RAD_NONE, brows(w.q, T), RAD_NONE);
|
||||
} else {
|
||||
for (int64_t h = 0; h < c.heads; ++h)
|
||||
RAD_ISSUE_N(c_, op_norm, T,
|
||||
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
|
||||
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
|
||||
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
|
||||
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
|
||||
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
|
||||
if (!bkb || !atb || !tlb) return;
|
||||
/* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
|
||||
* deployment speculates -- the manager gives every linear group a second copy then, because
|
||||
* the kernel that needed one asked for it -- and this op wants the committed slot in every
|
||||
* case. The pitch is the batch's, not a constant. */
|
||||
const int64_t tw = tlb->state_index_pitch > 0 ? tlb->state_index_pitch : 1;
|
||||
|
||||
/* THE WORK LIST BEFORE THE TAIL STORE, and the order is load-bearing rather than tidy: the
|
||||
* gather reads the raw keys of the block that is completing, and up to `ratio - 1` of them
|
||||
* are in the tail from earlier steps -- which the store is about to overwrite with this
|
||||
* step's. Reversed, every block completing at decode would pool three of this step's keys.
|
||||
*
|
||||
* The ring makes the store's overwrite land `ring` positions later rather than `ratio`, so
|
||||
* the two do not collide within a step either -- but the order still decides what a
|
||||
* straddling block reads, and it is the cheaper of the two guarantees to keep. */
|
||||
const int64_t work = (T + c.ratio - 1) / c.ratio + S;
|
||||
/* THE BLOCK POSITIONS: one component a block, or -- under M-RoPE with the planes -- three.
|
||||
* Under M-RoPE `bpos` is declared [max_work, 3], a block a row, so a smaller step is fewer
|
||||
* rows and the arena's sizing declare can shrink it; this step hands [work, 3], or its first
|
||||
* column alone when the pass has no planes -- qsa_work then writes component 0 and the block
|
||||
* key reads the one-component form. */
|
||||
const bool mc = g.rope_mc && batch->rope_pos;
|
||||
RadOperand bpos = g.rope_mc ? RAD_B_COL(w.bpos, 0, mc ? 3 : 1) : brows(w.bpos, work);
|
||||
if (g.rope_mc) bpos.rows = work;
|
||||
RAD_ISSUE_N(c_, op_work, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
mc ? praw2(batch->rope_pos, RAD_I32, 3, T) : RAD_NONE,
|
||||
brows(w.stage, work * c.ratio), brows(w.page, work), bpos,
|
||||
brows(w.nc, S));
|
||||
RAD_ISSUE_N(c_, op_bkey, work,
|
||||
brows(w.stage, work * c.ratio), RAD_W(w_kn),
|
||||
brows(w.page, work), bpos,
|
||||
kv_cache(kv_bk, layer));
|
||||
RAD_ISSUE_N(c_, op_tail, T,
|
||||
bcol_at(w.qk, 0, nw, koff, c.head_dim, T),
|
||||
praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
kv_cache(c.kv_tail, layer),
|
||||
praw2(tlb->state_index, RAD_I32, S, tw));
|
||||
|
||||
/* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
|
||||
* even though a block table is: both ops take `cu`, the block table stays the sequence's, and
|
||||
* `m` is a query row. So a prefill chunk's queries each get their own selection out of the one
|
||||
* history they share, which is what the checkpoint does, and there is no cap on the context a
|
||||
* step may index. */
|
||||
if (!c.emit_sel) return;
|
||||
|
||||
/* HOW MUCH HISTORY THERE ACTUALLY IS. The score plane is declared for `max_ctx`, so scoring
|
||||
* and selecting to its width means a 2000-token prompt walks 50000 block slots -- and both
|
||||
* kernels size their GRID from the declared width, because the live count is device data.
|
||||
* Narrowing the operand is how the host tells them: the pitch stays the declaration's, only
|
||||
* the column count moves, which is the same trick the attention block plays with `reach`.
|
||||
*
|
||||
* IT IS A CEILING AND EVERY TERM IS SLACK, because an UNDER-estimate silently drops blocks
|
||||
* from the selection and nothing would say so. A query's complete-block count is at most
|
||||
* (position + 1) / ratio; the highest position this step can reach is bounded by the
|
||||
* host-side context bound plus every token in the step plus the draft window; and the +1
|
||||
* keeps `n < nb`, which is what makes the partial page -- `bt[n]` -- readable at all. */
|
||||
const int64_t reach = (int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + c.ratio;
|
||||
int64_t live = reach / c.ratio + 1;
|
||||
if (live > c.max_blocks) live = c.max_blocks;
|
||||
if (live < 1) live = 1;
|
||||
|
||||
RAD_ISSUE_N(c_, op_score, T,
|
||||
brows(w.q, T), kv_cache(kv_bk, layer),
|
||||
praw2(bkb->block_table, RAD_I32, S, bkb->block_table_pitch),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S),
|
||||
bcol_at(w.score, 0, c.max_blocks, 0, live, T));
|
||||
RAD_ISSUE_N(c_, op_select, T,
|
||||
bcol_at(w.score, 0, c.max_blocks, 0, live, T),
|
||||
praw2(atb->block_table, RAD_I32, S, atb->block_table_pitch),
|
||||
brows(w.nc, S), praw(batch->positions, RAD_I32, T),
|
||||
praw(batch->cu_seqlens, RAD_I32, S + 1),
|
||||
brows(w.sel, T), brows(w.nsel, T), brows(w.sequ, T));
|
||||
|
||||
/* RADIANCE_DEBUG_QSA: the only window into a selection. Nothing else in the tree reports one,
|
||||
* and the numbers it prints are what tell a divergence from the dense path apart from QSA
|
||||
* doing its job -- `nc` above `topk` is blocks being dropped ON PURPOSE. It SYNCHRONISES THE
|
||||
* STREAM, so it is an environment variable, off, and costs nothing when it is not set; the
|
||||
* first few decode steps are enough to see the shape. */
|
||||
if (getenv("RADIANCE_DEBUG_QSA")) {
|
||||
static int seen = 0;
|
||||
if (seen++ < 6) {
|
||||
rad_stream_sync(rad_stream(c_));
|
||||
std::vector<int32_t> hnc(1), hns(1), hsu(1), hsel(8);
|
||||
std::vector<float> hsc(8);
|
||||
rad_memcpy_async(hnc.data(), rad_buf_ptr(c_, w.nc), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hns.data(), rad_buf_ptr(c_, w.nsel), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hsu.data(), rad_buf_ptr(c_, w.sequ), 4, rad_stream(c_));
|
||||
rad_memcpy_async(hsel.data(), rad_buf_ptr(c_, w.sel), 32, rad_stream(c_));
|
||||
rad_memcpy_async(hsc.data(), rad_buf_ptr(c_, w.score), 32, rad_stream(c_));
|
||||
rad_stream_sync(rad_stream(c_));
|
||||
std::fprintf(stderr, "D qsa L%d nc=%d nsel=%d sequ=%d sel[%d %d %d %d] "
|
||||
"score[%.4g %.4g %.4g %.4g]\n", layer,
|
||||
hnc[0], hns[0], hsu[0], hsel[0], hsel[1], hsel[2], hsel[3],
|
||||
hsc[0], hsc[1], hsc[2], hsc[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* RAD_QSA_H */
|
||||
Reference in new issue
Block a user