Archived
arch: Gemma 4 31B with z-lab's DFlash drafter
Gemma 4's DFlash drafter moves into arch/common so both Gemma 4 plugins declare it, on the int8 grid too; the 31B declares it beside its w4a8 / w8a8 trunk when the container carries one; the w4a8 and Q8 -df recipes and compose files; the tests. Squashed from: - arch: Gemma 4's DFlash drafter into arch/common, for both Gemma 4 plugins, and on the int8 grid - arch: z-lab's DFlash drafter beside the 31B's w4a8 / w8a8 trunk, its gqa-8 attention at gqa 4 - data/recipes: gemma4-31b with DFlash, the w4a8 trunk with a block-fp8 drafter, and Q8 - tests: the 31B with its DFlash drafter declares the chains where libr4d's fused ops are not declared - tests: the 31B's steps with its DFlash drafter lint clean, on both grids, at one, two and four ranks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
239da14d17
commit
bdb37d5d16
12 files changed
+1960
-901
No files matched your search
@@ -1515,10 +1515,12 @@ struct DenseFP8 {
|
||||
/* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */
|
||||
bool mapped = false;
|
||||
|
||||
/* `mapped`: the caller made the name map already, to ask the encoding before choosing this
|
||||
* struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */
|
||||
int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts = {});
|
||||
std::initializer_list<int64_t> row_parts = {}, bool mapped = false);
|
||||
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
|
||||
@@ -1541,7 +1543,7 @@ struct DenseFP8 {
|
||||
inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K,
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> row_parts) {
|
||||
std::initializer_list<int64_t> row_parts, bool mapped) {
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+20
-183
@@ -90,8 +90,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
|
||||
#include "gemma4_dflash.h"
|
||||
#include <arch/rad_gemma4_dflash.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
@@ -223,16 +222,15 @@ struct Model {
|
||||
rad_weight w_tok = 0, w_onorm = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0;
|
||||
|
||||
enum { MAX_TAPS = 8 };
|
||||
enum { MAX_TAPS = Dflash1::MAX_TAPS };
|
||||
int n_taps = 0;
|
||||
int tap_layer[MAX_TAPS] = {};
|
||||
rad_buf b_dfsrc = 0;
|
||||
|
||||
Dflash1 df{};
|
||||
Dflash1::Wire dfw{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_df = false;
|
||||
const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */
|
||||
const char* tok_src = nullptr; /* the checkpoint's table, which the 8-bit draft head copies */
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
@@ -301,159 +299,19 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t
|
||||
|
||||
/* ============================================================== the drafter */
|
||||
|
||||
/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), past the trunk's layers, reading the
|
||||
* taps the trunk copies into `dflash_src` and the trunk's tied table. */
|
||||
static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Model& m, int base_layer) {
|
||||
Names& nm = m.nm;
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash"));
|
||||
if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads "
|
||||
"the target's embedding and head, so it is not this target's drafter\n",
|
||||
(long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Dflash1::Config dc{};
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.escale = m.escale;
|
||||
/* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */
|
||||
long long trained = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
|
||||
if (trained < 2) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
if ((long long)ctx->max_spec + 1 != trained) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, "
|
||||
"which is %lld draft tokens, and this serve asks for %d. A block-diffusion "
|
||||
"drafter denoises a fixed number of mask positions; run it at "
|
||||
"--num-speculative-tokens %lld (or `auto`).\n",
|
||||
trained, trained - 1, ctx->max_spec, trained - 1);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dc.block = trained;
|
||||
if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED;
|
||||
{
|
||||
std::vector<int> full;
|
||||
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
|
||||
if (lt) {
|
||||
RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention",
|
||||
&full));
|
||||
if ((int64_t)full.size() != dg.n_layer) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and "
|
||||
"it has %lld\n", full.size(), (long long)dg.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else {
|
||||
full.assign((size_t)dg.n_layer, 1);
|
||||
}
|
||||
bool any_swa = false;
|
||||
for (int64_t l = 0; l < dg.n_layer; ++l) {
|
||||
dc.full[l] = full[(size_t)l];
|
||||
any_swa = any_swa || !full[(size_t)l];
|
||||
}
|
||||
if (any_swa) {
|
||||
dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size",
|
||||
rad_meta_geti(meta, "draft.sliding_window", 0));
|
||||
if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no "
|
||||
"window\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* One unbounded cache for all the drafter's layers, because its full layer reads every
|
||||
* position. The sliding layers bound themselves with their attention op's `window`, so the
|
||||
* declared drafter window is 0 and the core stages the whole context. A separate window group
|
||||
* for the sliding layers would save memory. */
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft));
|
||||
|
||||
const int64_t qd = dg.n_head * dg.head_dim;
|
||||
const int64_t kvd = dg.n_head_kv * dg.head_dim;
|
||||
int64_t qr = dg.max_seqs * dc.block;
|
||||
if (qr > dg.max_tok) qr = dg.max_tok;
|
||||
const int64_t sr = dg.max_seqs * dc.steps();
|
||||
const int64_t tw = dc.n_taps * dg.n_embd;
|
||||
|
||||
Dflash1::Wire& dw = m.dfw;
|
||||
dw.src = m.b_dfsrc;
|
||||
dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)});
|
||||
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd});
|
||||
dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd});
|
||||
dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)});
|
||||
dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd});
|
||||
dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd});
|
||||
dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd});
|
||||
dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd});
|
||||
dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd});
|
||||
dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd});
|
||||
dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)});
|
||||
dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff});
|
||||
dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff});
|
||||
dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff});
|
||||
dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)});
|
||||
dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd});
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab});
|
||||
if (Dflash1::head_sharded(dg)) {
|
||||
const int64_t R = Dflash1::kTopR;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R});
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2});
|
||||
} else {
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1});
|
||||
}
|
||||
if (!Dflash1::head_sharded(dg) && dg.world > 1) {
|
||||
fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole "
|
||||
"16-row blocks over %d ranks, which the drafter's sharded head needs\n",
|
||||
(long long)dg.n_vocab_all, dg.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch
|
||||
* `steps`, read by the engine through the drafter declaration below. */
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1});
|
||||
|
||||
RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw,
|
||||
m.tok_src));
|
||||
Dflash1::Trunk t{};
|
||||
t.n_taps = m.n_taps;
|
||||
t.escale = m.escale;
|
||||
t.src = m.b_dfsrc;
|
||||
t.w_tok = m.w_tok;
|
||||
t.tok_src = m.tok_src;
|
||||
t.base_layer = base_layer;
|
||||
RAD_ARCH_TRY(Dflash1::declare_drafter(b, meta, ctx, m.nm, m.g, t, &m.df, &m.kv_draft));
|
||||
m.have_df = true;
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dflash";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = dc.steps();
|
||||
drf.window = 0; /* the full layer reads everything; see the group */
|
||||
drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id",
|
||||
rad_meta_geti(meta, "draft.mask_token_id", -1));
|
||||
if (drf.mask_token < 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
|
||||
int nfull = 0;
|
||||
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
|
||||
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
|
||||
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is "
|
||||
"%s, argmax %s",
|
||||
(long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
|
||||
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps,
|
||||
(long long)dc.block, (long long)dc.steps(),
|
||||
m.df.fp8_head
|
||||
? "the container's block-fp8 copy of the target's table (dflash.draft_head)"
|
||||
: "the target's tied bf16 table",
|
||||
Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -662,7 +520,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- the embedding scale and the rotary scaling the converter may have written. The scale
|
||||
* is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066
|
||||
* multiplies as 53.0. */
|
||||
m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E)));
|
||||
m.escale = embed_scale(E);
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd));
|
||||
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) {
|
||||
fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's "
|
||||
@@ -794,24 +652,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* ---- the drafter's taps, declared when the container carries a DFlash drafter and this
|
||||
* serve speculates. DFlash2 is refused by name: its convolutions and selector are another
|
||||
* block. */
|
||||
if (ctx->max_spec > 0) {
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash2")) {
|
||||
fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin "
|
||||
"serves the DFlash (v1) block z-lab publishes for Gemma 4\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (da && std::strstr(da, "DFlash")) {
|
||||
const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr);
|
||||
if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr);
|
||||
m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS);
|
||||
if (m.n_taps <= 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model "
|
||||
"has; it is paired with a different target\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E});
|
||||
}
|
||||
{
|
||||
const int n = Dflash1::taps(meta, ctx, m.n_layer, m.tap_layer, Model::MAX_TAPS);
|
||||
if (n < 0) return n;
|
||||
m.n_taps = n;
|
||||
if (n > 0) m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)n * E});
|
||||
}
|
||||
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
@@ -1869,15 +1714,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
out->draft_depth = 0;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) {
|
||||
long long bs = rad_meta_geti(meta, "draft.block_size", 0);
|
||||
if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0);
|
||||
if (bs > 1) {
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
}
|
||||
}
|
||||
(void)dflash_probe(meta, out);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,682 +0,0 @@
|
||||
/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4.
|
||||
*
|
||||
* ============================== WHAT IT IS ==============================
|
||||
*
|
||||
* rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around
|
||||
* attention and the feed-forward, and the candidate selector). The original DFlash is a small
|
||||
* Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one
|
||||
* forward and takes every position's argmax from the target's lm_head.
|
||||
*
|
||||
* context pass, one row a committed token:
|
||||
* c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids)))
|
||||
* for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v)
|
||||
*
|
||||
* query pass, `block` rows a sequence:
|
||||
* x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below
|
||||
* for each layer:
|
||||
* h = input_layernorm(x)
|
||||
* q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store
|
||||
* x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window,
|
||||
* the full layer non-causal over everything
|
||||
* x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x)
|
||||
* x = norm(x)
|
||||
* over the mask rows: logits = lm_head(x) [the target's]; draft = argmax
|
||||
*
|
||||
* ============================== THE THREE GEMMA-SPECIFIC FACTS ==============================
|
||||
*
|
||||
* From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is
|
||||
* verified against the trunk.
|
||||
*
|
||||
* The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as
|
||||
* bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which
|
||||
* applies it. `embed_lookup`'s `mult` carries it.
|
||||
*
|
||||
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
|
||||
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
|
||||
* layers and `False` on the full one, so this block declares two attention ops and issues the one
|
||||
* each layer's type names.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
*
|
||||
* ============================== THE HEAD ==============================
|
||||
*
|
||||
* The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma
|
||||
* ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read
|
||||
* and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's
|
||||
* slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` ->
|
||||
* `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR).
|
||||
*
|
||||
* The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a
|
||||
* 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the
|
||||
* table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical
|
||||
* weights, as in rad_block_dflash2.h), made by the recipe line
|
||||
*
|
||||
* dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
*
|
||||
* the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its
|
||||
* coarser logits. Drafts are still verified, so the copy can change proposals but never accepted
|
||||
* text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the
|
||||
* table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table:
|
||||
* DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not.
|
||||
*
|
||||
* ============================== THE LINEARS ARE FP8 ==============================
|
||||
*
|
||||
* As in DFlash2, since the drafter is read whole on every decode step: the container must be
|
||||
* converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16
|
||||
* one by name rather than letting the loader fail on a view.
|
||||
*/
|
||||
#ifndef GEMMA4_DFLASH_H
|
||||
#define GEMMA4_DFLASH_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace gemma4 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
|
||||
* transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */
|
||||
inline bool block_fp8_128(const RadEncoding& e) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] &&
|
||||
e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 &&
|
||||
sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
struct Dflash1 {
|
||||
enum { MAX_LAYERS = 8 };
|
||||
|
||||
struct Config {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
|
||||
int64_t window = 0; /* the sliding layers' window; 0 for none */
|
||||
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
|
||||
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
|
||||
int64_t steps() const { return block - 1; }
|
||||
};
|
||||
|
||||
struct Wire {
|
||||
/* the context pass */
|
||||
rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */
|
||||
rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */
|
||||
rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */
|
||||
/* the query pass */
|
||||
rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */
|
||||
rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */
|
||||
rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */
|
||||
rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */
|
||||
rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */
|
||||
/* the head, one row per draft position */
|
||||
rad_buf sel_h = 0; /* [srows, n_embd] */
|
||||
rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */
|
||||
rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */
|
||||
rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */
|
||||
rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */
|
||||
rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */
|
||||
};
|
||||
|
||||
Geom g{}; /* the drafter's geometry */
|
||||
Config cfg{};
|
||||
Wire w{};
|
||||
int first_layer = 0;
|
||||
int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
bool sharded = false;
|
||||
|
||||
DenseFP8 w_fc{};
|
||||
rad_weight w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_tok = 0; /* the target's table: embedding and head */
|
||||
DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */
|
||||
bool fp8_head = false;
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{};
|
||||
rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {};
|
||||
DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{};
|
||||
|
||||
rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0;
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0;
|
||||
rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {};
|
||||
/* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served
|
||||
* (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for
|
||||
* the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain
|
||||
* is issued instead. */
|
||||
rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {};
|
||||
rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {};
|
||||
rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {};
|
||||
rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0;
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0;
|
||||
|
||||
/* Candidates each rank contributes under a sharded head. The draft needs one, but the gather
|
||||
* moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is
|
||||
* refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax`
|
||||
* reduces the world * 2 of them to the global top-1. */
|
||||
static constexpr int64_t kTopR = 2;
|
||||
|
||||
static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); }
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire,
|
||||
const char* tok_src);
|
||||
void context(RadCtx* c, const RadBatch* batch) const;
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
|
||||
private:
|
||||
int64_t q_dim() const { return g.n_head * g.head_dim; }
|
||||
int64_t kv_dim() const { return g.n_head_kv * g.head_dim; }
|
||||
/* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views
|
||||
* whatever the container holds, and the loader's error for a bf16 weight read through an fp8
|
||||
* view would name the view, not the missing recipe. */
|
||||
static int need_quantised(RadBuilder* b, const char* wn) {
|
||||
RadEncoding e{};
|
||||
if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */
|
||||
const uint32_t dt = e.plane[0].dtype;
|
||||
if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK;
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears "
|
||||
"are served block fp8 (or MXFP4): convert with a recipe that names them, "
|
||||
"e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 "
|
||||
"scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and "
|
||||
"ffn_down.\n", wn, rad_dtype_name(dt));
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------------------ declare */
|
||||
|
||||
inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c,
|
||||
int base_layer, rad_kvgroup group, rad_weight tok_embd,
|
||||
const char* ck, const Wire& wire, const char* tok_src) {
|
||||
g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd;
|
||||
if (!ck || !w_tok || !tok_src) return RAD_E_INVAL;
|
||||
if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most "
|
||||
"%d\n", (long long)g.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL;
|
||||
|
||||
const int64_t qd = q_dim(), kvd = kv_dim();
|
||||
crows = g.max_tok;
|
||||
qrows = g.max_seqs * cfg.block;
|
||||
if (qrows > g.max_tok) qrows = g.max_tok;
|
||||
srows = g.max_seqs * cfg.steps();
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
sharded = head_sharded(g);
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const RadWeightGroup gl = grp_layer(first_layer + i);
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i),
|
||||
nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i)));
|
||||
w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
|
||||
w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
|
||||
w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
|
||||
w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl);
|
||||
/* The declared names match rad_block_dflash2.h's, so one recipe quantises both
|
||||
* drafters. */
|
||||
RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
|
||||
{ nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) }));
|
||||
RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff,
|
||||
g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl,
|
||||
{ nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i),
|
||||
nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) },
|
||||
{ g.n_ff, g.n_ff }));
|
||||
RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl,
|
||||
{ nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) }));
|
||||
for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up",
|
||||
"ffn_down" })
|
||||
RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s)));
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- attention: two kinds
|
||||
* Declared before either kv_store, which reads `block_size` back from the resolved kernel.
|
||||
* Both read the one KV group, so whichever resolves first answers for it. */
|
||||
auto attn = [&](int causal, int64_t window) {
|
||||
return rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal),
|
||||
RAD_INT("window", window), RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
};
|
||||
bool any_full = false, any_swa = false;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
|
||||
if (any_swa) op_attn_swa = attn(1, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* ---------------------------------------------------------------- the context pass */
|
||||
op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_hnorm)),
|
||||
{w.c}, {w.c});
|
||||
op_qc = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.c}, {w.cq, w.cs});
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck});
|
||||
op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv});
|
||||
op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.ck}, {w.ck});
|
||||
}
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck}, {w.ck});
|
||||
op_cstore = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ck, w.cv}, {});
|
||||
|
||||
/* ---------------------------------------------------------------- the query pass */
|
||||
op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {w.x});
|
||||
if (g.world > 1)
|
||||
op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x}, {w.x});
|
||||
op_qh = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.hq, w.hs});
|
||||
op_qat = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.attn}, {w.atq, w.ats});
|
||||
op_qff = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.ffn}, {w.ffq, w.ffs});
|
||||
|
||||
/* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the
|
||||
* fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of
|
||||
* the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */
|
||||
auto norm_quant = [&](rad_weight gain, bool add) -> rad_op {
|
||||
const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)),
|
||||
RAD_WEIGHTS(gain));
|
||||
return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs});
|
||||
};
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_anorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_anq[i] = norm_quant(w_anorm[i], l > 0);
|
||||
op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q});
|
||||
op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k});
|
||||
op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v});
|
||||
op_qn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn[i])),
|
||||
{w.q}, {w.q});
|
||||
op_kn[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv),
|
||||
RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_kn[i])),
|
||||
{w.k}, {w.k});
|
||||
op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h});
|
||||
op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fnorm[i])),
|
||||
{w.x}, {w.h});
|
||||
op_fnq[i] = norm_quant(w_fnorm[i], true);
|
||||
op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up});
|
||||
/* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's
|
||||
* rule, band included). */
|
||||
{
|
||||
const int64_t hi = qrows < 64 ? qrows : 64;
|
||||
if (hi > 0 && !w_gu[i].mx) {
|
||||
op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff),
|
||||
RAD_INT("K", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")),
|
||||
RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)),
|
||||
{w.hq, w.hs}, {w.ffq, w.ffs});
|
||||
if (op_gug[i]) gated_rows = hi;
|
||||
}
|
||||
}
|
||||
op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h});
|
||||
}
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k}, {w.k});
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
op_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.gate_up}, {w.ffn});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, qrows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
/* ---------------------------------------------------------------- the head
|
||||
* The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous,
|
||||
* projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded,
|
||||
* each rank reports its best kTopR as global ids with logits; these are all-gathered and
|
||||
* reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the
|
||||
* global winner is its own shard's first. */
|
||||
op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.sel_h});
|
||||
/* The fp8 copy, where the container holds one (see the file header). The name map comes first
|
||||
* since it is how the encoding is looked up; rad-convert writes only declared weights. The
|
||||
* copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and
|
||||
* `vocab_off` holds. */
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, tok_src));
|
||||
RadEncoding he{};
|
||||
fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he);
|
||||
if (fp8_head) {
|
||||
if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which "
|
||||
"is not whole %d-row scale blocks\n",
|
||||
(long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp_model());
|
||||
w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16,
|
||||
{ fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN,
|
||||
shard, grp_model());
|
||||
if (!w_dh.w || !w_dh.s) return RAD_E_INVAL;
|
||||
w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd});
|
||||
w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)});
|
||||
op_qsel = rw(b, RAD_OP(b, "quant_act_fp8",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.selq, w.sels});
|
||||
op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog});
|
||||
} else {
|
||||
op_head = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{w.sel_h}, {w.dlog});
|
||||
}
|
||||
if (sharded) {
|
||||
op_topk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.cand, w.unary, w.dpair});
|
||||
/* Row-interleaved, so one draft position's pairs from every rank land side by side. */
|
||||
op_dgather = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"),
|
||||
RAD_INT("row", kTopR * 2)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dpair}, {w.dgath});
|
||||
op_pick = rw(b, RAD_OP(b, "pair_argmax",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR),
|
||||
RAD_STR("dtype", "f32")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dgath}, {w.tokens});
|
||||
if (!op_pick) {
|
||||
fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the "
|
||||
"device, and no loaded kernel library serves it there\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
} else {
|
||||
op_topk = rw(b, RAD_OP(b, "row_topk",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab),
|
||||
RAD_INT("R", 1), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.dlog}, {w.tokens, w.unary});
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the context pass */
|
||||
|
||||
inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]),
|
||||
brows(w.ck, T));
|
||||
RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, first_layer + i));
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------------ the query pass */
|
||||
|
||||
inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (T <= 0) return;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T));
|
||||
if (op_embed_ar)
|
||||
RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE);
|
||||
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa;
|
||||
|
||||
/* The attention input, with the last layer's residual add where one launch takes both. */
|
||||
if (op_anq[i]) {
|
||||
RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T),
|
||||
l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T),
|
||||
brows(w.hs, T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref());
|
||||
RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref());
|
||||
RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref());
|
||||
RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T));
|
||||
RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T));
|
||||
RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T),
|
||||
kv_cache(kv, first_layer + i));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, first_layer + i),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T));
|
||||
RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T));
|
||||
RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T),
|
||||
RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (op_fnq[i]) {
|
||||
RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]),
|
||||
brows(w.hq, T), brows(w.hs, T), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T));
|
||||
RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T));
|
||||
}
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T),
|
||||
RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE,
|
||||
w_gu[i].bref());
|
||||
RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T));
|
||||
RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T),
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
/* the residual add, unless the next layer's input norm takes it */
|
||||
if (l + 1 == g.n_layer || !op_anq[i + 1])
|
||||
RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
|
||||
const int64_t S = batch->n_out;
|
||||
if (S <= 0) return;
|
||||
RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S));
|
||||
if (fp8_head) {
|
||||
RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S));
|
||||
RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w),
|
||||
RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref());
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S));
|
||||
}
|
||||
if (sharded) {
|
||||
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S),
|
||||
brows(w.dpair, S));
|
||||
RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S));
|
||||
RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S),
|
||||
RAD_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace gemma4 */
|
||||
|
||||
#endif /* GEMMA4_DFLASH_H */
|
||||
@@ -7,10 +7,17 @@
|
||||
* declare), with a second norm on each projection's output before its residual, a weightless RMS
|
||||
* norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to
|
||||
* cap * tanh(x / cap).
|
||||
*
|
||||
* Two draft models, whichever the container carries under `draft.`: Google's assistant head (a
|
||||
* serial head over the trunk's own cache, the Gemma4Head below) or z-lab's DFlash drafter (a
|
||||
* five-layer block drafter with its own cache, reading the trunk's residual stream at six layers,
|
||||
* arch/common/rad_gemma4_dflash.h) -- the 31B's z-lab/gemma-4-31B-it-DFlash proposes 15 tokens a
|
||||
* pass where the assistant proposes one a round.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
#include <arch/rad_gemma4_dflash.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
@@ -20,12 +27,6 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/* sqrt(n_embd) rounded to bf16: the reference's embedding module multiplies the looked-up rows by
|
||||
* `embed_scale.to(bf16)`, 73.5 at 5376 and not 73.32. */
|
||||
static double embed_scale(int64_t n) {
|
||||
return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)n)));
|
||||
}
|
||||
|
||||
namespace gemma4_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
@@ -839,7 +840,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off),
|
||||
RAD_F64("mult", embed_scale(n_trunk))),
|
||||
RAD_F64("mult", gemma4::embed_scale(n_trunk))),
|
||||
RAD_WEIGHTS(w_tok)),
|
||||
{}, {b_e});
|
||||
if (g.world > 1)
|
||||
@@ -1098,6 +1099,8 @@ struct Layer {
|
||||
* The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not
|
||||
* a quantiser. */
|
||||
G4Junction j_am{}, j_ma{};
|
||||
/* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */
|
||||
rad_op op_tap = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
@@ -1133,6 +1136,17 @@ struct Model {
|
||||
bool fuse = false;
|
||||
bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */
|
||||
int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */
|
||||
|
||||
/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), declared only when the container
|
||||
* carries one and the deployment speculates: the trunk layers it taps, the [max_tok, taps x
|
||||
* n_embd] plane the taps fill, the block and its own KV group. */
|
||||
enum { MAX_TAPS = gemma4::Dflash1::MAX_TAPS };
|
||||
int n_taps = 0;
|
||||
int tap_layer[MAX_TAPS] = {};
|
||||
rad_buf b_dfsrc = 0;
|
||||
gemma4::Dflash1 df{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_df = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
@@ -1255,6 +1269,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- the DFlash drafter's taps, declared when the container carries z-lab's drafter and this
|
||||
* serve speculates. The plane is declared here and written by an op declared inside each layer
|
||||
* it taps, because the buffer planner's liveness is declaration order (the tap below). */
|
||||
{
|
||||
const int n = gemma4::Dflash1::taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS);
|
||||
if (n < 0) return n;
|
||||
m.n_taps = n;
|
||||
if (n > 0)
|
||||
m.b_dfsrc = decl_b(b, nm.f("dflash_src"), g.act_dtype,
|
||||
{g.max_tok, (int64_t)n * g.n_embd});
|
||||
}
|
||||
|
||||
/* ---- the vocabulary edges. Gemma 4 ties the head to the embedding. */
|
||||
const char* pre = "model.language_model.layers";
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight")));
|
||||
@@ -1276,14 +1302,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
/* The embedding is scaled by sqrt(n_embd) at the lookup, not in the table (as in llama.cpp's
|
||||
* build_inp_embd and HF's ScaledWordEmbedding), so the plain table stays tied to the head.
|
||||
* Without it the token signal in the residual stream would be ~73x too small. The scale is
|
||||
* sqrt(n_embd) rounded to bf16, as the reference multiplies by it (embed_scale: 73.5
|
||||
* sqrt(n_embd) rounded to bf16, as the reference multiplies by it (gemma4::embed_scale: 73.5
|
||||
* at 5376, not 73.32). The first norm hides the difference but the residual stream does not,
|
||||
* and the DFlash drafter was trained on the reference's hidden states. */
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off),
|
||||
RAD_F64("mult", embed_scale(g.n_embd))),
|
||||
RAD_F64("mult", gemma4::embed_scale(g.n_embd))),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
if (g.world > 1)
|
||||
@@ -1329,6 +1355,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_scalar)),
|
||||
{mw.x}, {mw.x});
|
||||
|
||||
/* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1])
|
||||
* into the column slice the tap owns. It is declared here, in the layer it is issued
|
||||
* after, because the buffer planner's liveness is declaration order. A tap declared once
|
||||
* after the trunk made `dflash_src` look born at its end and free to share with what every
|
||||
* layer writes, which on arch/gemma4 cost 98% of the drafts with the reply still fluent. */
|
||||
for (int t = 0; t < m.n_taps; ++t)
|
||||
if (m.tap_layer[t] == (int)l && !lay.op_tap)
|
||||
lay.op_tap = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_dfsrc});
|
||||
}
|
||||
|
||||
/* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain).
|
||||
@@ -1414,10 +1453,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset));
|
||||
}
|
||||
|
||||
/* ---- the vision tower, its weight groups past the trunk's and the head's (counted even when
|
||||
* the head is not declared, so the groups do not move with max_spec). */
|
||||
/* ---- or z-lab's DFlash drafter, past the trunk's layers. It is declared last because
|
||||
* declaration order is the buffer planner's liveness. It reads the taps the trunk copied into
|
||||
* `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no
|
||||
* 8-bit copy, as its head. */
|
||||
if (m.n_taps > 0) {
|
||||
gemma4::Dflash1::Trunk t{};
|
||||
t.n_taps = m.n_taps;
|
||||
t.escale = gemma4::embed_scale(g.n_embd);
|
||||
t.src = m.b_dfsrc;
|
||||
t.w_tok = m.w_tok;
|
||||
t.tok_src = nm.ckpt("model.language_model.embed_tokens.weight");
|
||||
t.base_layer = (int)m.n_main;
|
||||
RAD_ARCH_TRY(gemma4::Dflash1::declare_drafter(b, meta, ctx, nm, g, t, &m.df, &m.kv_draft));
|
||||
m.have_df = true;
|
||||
}
|
||||
|
||||
/* ---- the vision tower, its weight groups past the trunk's and the draft model's: the
|
||||
* assistant's layers and its exit, or the DFlash drafter's layers. They are counted even when
|
||||
* the draft model is not declared, so the groups do not move with max_spec. */
|
||||
{
|
||||
const int64_t head_groups = has_assistant(meta) ? meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1 : 0;
|
||||
int64_t head_groups = 0;
|
||||
if (has_assistant(meta))
|
||||
head_groups = meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1;
|
||||
else if (gemma4::dflash_kind(meta) == 1)
|
||||
head_groups = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
|
||||
"model.", "gemma4_bf16"));
|
||||
}
|
||||
@@ -1448,12 +1508,19 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
m.vis.step(c, batch);
|
||||
return;
|
||||
}
|
||||
/* A draft pass runs only the head. The trunk already left its final-normed hidden state in
|
||||
* `h`, which the head's history pass gathers from. */
|
||||
/* A draft pass runs only the draft model. The trunk already left its final-normed hidden state
|
||||
* in `h`, which the assistant's history pass gathers from, and its taps in `dflash_src`, which
|
||||
* the DFlash drafter's context pass reads. */
|
||||
if (batch->draft_pass != 0) {
|
||||
if (m.have_df) {
|
||||
if (batch->draft_pass > 0) m.df.step(c, batch);
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
if (!m.have_head) {
|
||||
rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the "
|
||||
"container carries no `draft.` assistant, or declare ran at max_spec 0");
|
||||
"container carries no `draft.` assistant or DFlash drafter, or declare "
|
||||
"ran at max_spec 0");
|
||||
return;
|
||||
}
|
||||
m.head.step(c, batch);
|
||||
@@ -1483,13 +1550,20 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
if (m.fuse && !last) {
|
||||
/* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */
|
||||
l.j_ma.step(c, T, far);
|
||||
continue;
|
||||
} else {
|
||||
/* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after
|
||||
* the mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The
|
||||
* checkpoint's values (0.03-0.99) are trained weights that rescale the residual toward
|
||||
* O(1). */
|
||||
RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
}
|
||||
/* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the
|
||||
* mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's
|
||||
* values (0.03-0.99) are trained weights that rescale the residual toward O(1). */
|
||||
RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
/* The drafter's taps, once the layer's output is whole. Either way that is after the
|
||||
* scalar, since the junction applies it to the stream it writes. */
|
||||
for (int t = 0; t < m.n_taps && l.op_tap; ++t)
|
||||
if (m.tap_layer[t] == (int)li)
|
||||
RAD_ISSUE(c, l.op_tap, brows(m.b_x, T),
|
||||
bcol(m.b_dfsrc, (int64_t)t * m.g.n_embd, m.g.n_embd, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_final,
|
||||
@@ -1513,13 +1587,16 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); }
|
||||
|
||||
/* The default draft depth for `--num-speculative-tokens auto`. A serial head's depth is an
|
||||
* operating point, not a trained depth: every depth runs. */
|
||||
* operating point, not a trained depth: every depth runs. A DFlash drafter's is the block it was
|
||||
* trained at, fixed. */
|
||||
static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (!meta || !out) return RAD_E_INVAL;
|
||||
if (has_assistant(meta)) {
|
||||
out->draft_depth = kHeadDepth;
|
||||
out->draft_depth_fixed = 0;
|
||||
}
|
||||
/* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h). */
|
||||
(void)gemma4::dflash_probe(meta, out);
|
||||
/* The tower's pooling window, so a pass size the core picks itself is whole windows. */
|
||||
if (Gemma4Vision::present(meta)) {
|
||||
const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0);
|
||||
@@ -1530,9 +1607,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"Gemma 4 dense (text and images), w4a8 from its bf16 or its CT-INT4 (QAT) release: "
|
||||
"sliding-window and proportional-RoPE global attention over a plain RMSNorm stream "
|
||||
"with GELU feed-forward, per-layer scalar scaling and soft-capped logits")
|
||||
"Gemma 4 dense (text and images), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"release: sliding-window and proportional-RoPE global attention over a plain "
|
||||
"RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped "
|
||||
"logits; Google's assistant head or z-lab's DFlash drafter")
|
||||
RAD_ARCH_CHAT_FORMAT(gemma4_bf16)
|
||||
RAD_ARCH_PROBE(gemma4_bf16)
|
||||
#endif
|
||||
|
||||
Reference in new issue
Block a user