Archived
arch, data/recipes, libr4d: the 31B's prefill overlap, q|k|v as one linear, RedHatAI's DFlash2, its fc split
The 31B's prefill steps of 1024 rows or more run as two slices with each slice's all-reduces beside the other's compute; q, k and v as one linear where the container holds them so; the 31B serves RedHatAI's DFlash2 speculator; DFlash2's fc projection is split over the ranks, bit for bit. Squashed from: - arch/gemma4_bf16: a prefill step in two slices, each slice's reductions on the second lane - arch/gemma4_bf16: q, k and v as one linear where the container holds them so - data/recipes: the 31B -df recipes make q, k and v one linear (blk.*.attn_qkv) - arch/gemma4: the 31B serves RedHatAI's DFlash2 speculator (gemma-4-31B-it-speculator.dflash2) - libr4d: gemm_nt_q takes split_n, and all_gather lands rows at a wider output pitch - arch/common: DFlash2's fc split over the ranks as windows of block-aligned rows, bit for bit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdb37d5d16
commit
04e5480387
21 files changed
+1805
-199
No files matched your search
+24
-11
@@ -1262,17 +1262,30 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) {
|
||||
* layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split
|
||||
* over the ranks, and a plain RMS norm. A drafter is a second model, so nothing is defaulted: a
|
||||
* config that does not describe one is refused, naming `what` (spec §17). So is a vocabulary
|
||||
* other than the target's, since a drafter reads the target's embedding and lm_head. */
|
||||
* other than the target's, since a drafter reads the target's embedding and lm_head.
|
||||
*
|
||||
* The layer config sits at the top of `draft.` in z-lab's and SpecForge's checkpoints, and under
|
||||
* `draft.transformer_layer_config.` in vLLM's speculators format (RedHatAI's DFlash2 drafters),
|
||||
* whose top level holds the speculator's own keys instead (drafter_layer_prefix). */
|
||||
inline const char* drafter_layer_prefix(const RadModelMeta* meta) {
|
||||
if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) > 0) return "draft.";
|
||||
if (rad_meta_geti(meta, "draft.transformer_layer_config.num_hidden_layers", 0) > 0)
|
||||
return "draft.transformer_layer_config.";
|
||||
return "draft.";
|
||||
}
|
||||
inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) {
|
||||
dg = target;
|
||||
dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0);
|
||||
dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0);
|
||||
dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0);
|
||||
dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0);
|
||||
dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0);
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
const char* pre = drafter_layer_prefix(meta);
|
||||
char key[160];
|
||||
auto k = [&](const char* name) { std::snprintf(key, sizeof key, "%s%s", pre, name); return key; };
|
||||
dg.n_layer = rad_meta_geti(meta, k("num_hidden_layers"), 0);
|
||||
dg.head_dim = rad_meta_geti(meta, k("head_dim"), 0);
|
||||
dg.n_head_all = rad_meta_geti(meta, k("num_attention_heads"), 0);
|
||||
dg.n_head_kv_all = rad_meta_geti(meta, k("num_key_value_heads"), 0);
|
||||
dg.n_ff_all = rad_meta_geti(meta, k("intermediate_size"), 0);
|
||||
dg.eps = (float)rad_meta_getf(meta, k("rms_norm_eps"), 0.0);
|
||||
const double th = rad_meta_getf(meta, k("rope_theta"), 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, k("rope_parameters.rope_theta"), th);
|
||||
dg.wadd = dg.wadd_qk = 0.0f;
|
||||
if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 ||
|
||||
dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) {
|
||||
@@ -1283,11 +1296,11 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta,
|
||||
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv));
|
||||
RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff));
|
||||
const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all);
|
||||
const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all);
|
||||
if (dvocab != dg.n_vocab_all) {
|
||||
fprintf(stderr, "radiance: the %s drafter claims a %lld-token vocabulary and the target "
|
||||
"has %lld; it reads the target's embedding and lm_head\n",
|
||||
|
||||
+119
-21
@@ -69,10 +69,21 @@
|
||||
* q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per
|
||||
* draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor.
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the
|
||||
* context pass every step. Split by rows over the ranks and all-gathered, and
|
||||
* kept bit for bit. Each rank hands over an equal share of c's columns
|
||||
* (n_embd / world) and computes the fewest whole 128-row scale blocks that cover
|
||||
* it (the 31B at tp 4: 1344 columns a rank inside 11 blocks, 1408 rows, against
|
||||
* 42 blocks whole), a row span of the one stored weight
|
||||
* (DenseFP8::declare_slice), so no reconvert. The GEMM takes its K split from
|
||||
* the whole width (OPS.md's `split_n`), so each output is summed as the unsplit
|
||||
* fc sums it, and the all-gather reads each rank's window out of its wider rows
|
||||
* (an input pitch) and writes c whole. A GEMM cannot write a column slice (the
|
||||
* narrow fp8 kernel's store is tight), which is why the windows are the
|
||||
* gather's to cut. One rank, or an fc off block fp8, keeps it whole.
|
||||
*
|
||||
* Replicated:
|
||||
*
|
||||
* fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an
|
||||
* all-reduce to the prefill path.
|
||||
* conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole
|
||||
* replicated hidden row, so every rank needs every coefficient.
|
||||
* codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are
|
||||
@@ -127,6 +138,10 @@ struct Dflash2 {
|
||||
/* the context pass */
|
||||
rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */
|
||||
rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */
|
||||
/* [max_tok, fc_rows] the block-aligned rows of a split fc this rank computes, whose
|
||||
* fc_share-wide window at fc_off is gathered into c. The block declares it (only when it
|
||||
* splits fc); leave it 0. */
|
||||
rad_buf cpart = 0;
|
||||
/* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row
|
||||
* pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but
|
||||
* 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp,
|
||||
@@ -191,10 +206,17 @@ struct Dflash2 {
|
||||
* MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step.
|
||||
* Quantisation can only change acceptance, since every draft is verified. */
|
||||
DenseFP8 w_fc{};
|
||||
/* fc split by rows (see SHARDING): w_fc is this rank's fc_rows block-aligned rows, holding its
|
||||
* fc_share output columns at row fc_off. fc_rows 0: w_fc is the whole fc, replicated. */
|
||||
int64_t fc_share = 0, fc_rows = 0, fc_off = 0;
|
||||
rad_weight w_hnorm = 0, w_norm = 0;
|
||||
rad_weight w_selp = 0, w_pred = 0, w_succ = 0;
|
||||
rad_weight w_tok = 0; /* the target's embedding table */
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */
|
||||
rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit (or 8-bit) copy of the target's lm_head */
|
||||
/* The copy is int8 with an f16 scale per (row, 128 of K) where the recipe made it so (the
|
||||
* 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and
|
||||
* the 2-bit grid otherwise. Set by declare from the copy's encoding. */
|
||||
bool head_i8 = false;
|
||||
|
||||
/* per-layer weights */
|
||||
rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {};
|
||||
@@ -209,6 +231,7 @@ struct Dflash2 {
|
||||
|
||||
/* context-pass ops */
|
||||
rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0;
|
||||
rad_op op_cgath = 0; /* the split fc's all-gather */
|
||||
rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {};
|
||||
|
||||
/* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration
|
||||
@@ -284,9 +307,38 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
if (qrows <= 0 || srows <= 0) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- model-scope weights */
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd,
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(),
|
||||
{ nm.ckpt("%s.fc.weight", ck) }));
|
||||
{
|
||||
const int64_t K = cfg.n_taps * g.n_embd;
|
||||
const char* fwn = nm.f("dflash.fc.weight");
|
||||
RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) }));
|
||||
/* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole
|
||||
* 16-byte words (the gather's unit). */
|
||||
RadEncoding fe{};
|
||||
const RadEncPlane* fsc = nullptr;
|
||||
const bool fp8 = weight_enc(b, fwn, &fe) && rad_enc_is(&fe, "affine") && fe.n_planes == 2 &&
|
||||
!fe.transform[0] && fe.plane[0].dtype == RAD_F8E4M3 &&
|
||||
(fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_FP8_BLOCK &&
|
||||
fsc->block[1] == RAD_FP8_BLOCK;
|
||||
const int64_t share = (g.world > 1 && g.n_embd % RAD_FP8_BLOCK == 0 &&
|
||||
g.n_embd % g.world == 0 && (g.n_embd / g.world) % 8 == 0)
|
||||
? g.n_embd / g.world : 0;
|
||||
if (fp8 && share > 0) {
|
||||
const int64_t B = RAD_FP8_BLOCK;
|
||||
const int64_t lo = share * g.rank / B * B;
|
||||
const int64_t hi = (share * (g.rank + 1) + B - 1) / B * B;
|
||||
fc_share = share;
|
||||
fc_rows = hi - lo;
|
||||
fc_off = share * g.rank - lo;
|
||||
RAD_ARCH_TRY(w_fc.declare_slice(b, nm, nm.f("dflash.fc"), fwn, lo, hi, K,
|
||||
RAD_ACCESS_PER_TOKEN, grp_model()));
|
||||
if (!w.cpart)
|
||||
w.cpart = decl_b(b, nm.f("df_cpart"), g.act_dtype, { g.max_tok, fc_rows });
|
||||
} else {
|
||||
RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, K, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) },
|
||||
{}, true));
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"),
|
||||
@@ -321,10 +373,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE;
|
||||
const char* dhn = nm.f("dflash.draft_head.weight");
|
||||
RAD_ARCH_TRY(map_copy(b, dhn, ck_lm));
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
/* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q
|
||||
* reads at w8a8 against the same quant_act_i8 activation (without its asum). */
|
||||
{
|
||||
RadEncoding e{};
|
||||
const RadEncPlane* sc = nullptr;
|
||||
head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 &&
|
||||
!e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 &&
|
||||
(sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 &&
|
||||
sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP;
|
||||
}
|
||||
if (head_i8) {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16,
|
||||
{head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split,
|
||||
grp_model());
|
||||
} else {
|
||||
w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16,
|
||||
{head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model());
|
||||
}
|
||||
if (!w_dh || !w_dhs) return RAD_E_INVAL;
|
||||
|
||||
/* ---------------------------------------------------------------- per-layer weights */
|
||||
@@ -422,7 +492,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.src}, {w.srcq, w.srcs});
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
if (fc_rows) {
|
||||
/* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of
|
||||
* them gathered into `c`. The GEMM takes its K split from the whole width. The gather
|
||||
* rides the trunk's all-reduce instance (the same numel bound, so the same instance). */
|
||||
op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart},
|
||||
g.n_embd);
|
||||
op_cgath = rw(b, RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_INT("numel", crows * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.cpart}, {w.c});
|
||||
} else {
|
||||
op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c});
|
||||
}
|
||||
/* In place, like the per-head q/k norms below: a row's scale is computed before the row is
|
||||
* written. */
|
||||
op_cnorm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
@@ -643,12 +727,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.sel_h}, {w.dq, w.ds, w.dsum});
|
||||
op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
|
||||
RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
op_dlogits = head_i8
|
||||
? rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
|
||||
RAD_STR("dtype", "w8a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds}, {w.dlog})
|
||||
: rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP),
|
||||
RAD_STR("dtype", "w2a8")),
|
||||
RAD_WEIGHTS(w_dh, w_dhs)),
|
||||
{w.dq, w.ds, w.dsum}, {w.dlog});
|
||||
/* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair
|
||||
* plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present
|
||||
* with value 0 is a different declaration from an absent one. */
|
||||
@@ -731,8 +822,14 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */
|
||||
RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T));
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
if (fc_rows) {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.cpart, T), RAD_NONE, w_fc.bref());
|
||||
RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s),
|
||||
brows(w.c, T), RAD_NONE, w_fc.bref());
|
||||
}
|
||||
RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T));
|
||||
RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T));
|
||||
|
||||
@@ -843,9 +940,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* whole. */
|
||||
RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum));
|
||||
/* The trailing operand is mxfp4's optional reference, absent here. Operands are positional,
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. */
|
||||
* so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and
|
||||
* takes no asum. */
|
||||
RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs),
|
||||
brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE);
|
||||
brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE);
|
||||
/* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and
|
||||
* the merge overwrites `cand`/`unary`. */
|
||||
if (op_dmerge) {
|
||||
|
||||
+34
-2
@@ -1521,15 +1521,47 @@ struct DenseFP8 {
|
||||
int access, int shard, RadWeightGroup grp,
|
||||
std::initializer_list<const char*> src,
|
||||
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. */
|
||||
/* Rows [lo, hi) of the stored block-fp8 weight `src_wn` (codes and scale plane; mapped by
|
||||
* whoever declared it), read as an [hi - lo, K] weight named `<base>`: a row slice that need
|
||||
* not be a rank's even share, and may be the same rows on every rank. Whole 128-row blocks,
|
||||
* so each slice's codes and scales are the stored ones. fp8 only: an MXFP4 linear's GEMM
|
||||
* splits K by its own rule. A slice issued with `gemm(..., split_n)` set to the stored width
|
||||
* computes the stored linear's outputs to the bit. */
|
||||
int declare_slice(RadBuilder* b, Names& nm, const char* base, const char* src_wn, int64_t lo,
|
||||
int64_t hi, int64_t K, int access, RadWeightGroup grp) {
|
||||
if (lo < 0 || hi <= lo || lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK)
|
||||
return RAD_E_INVAL;
|
||||
mx = false;
|
||||
ref = 0;
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const bool own = !std::strcmp(wn, src_wn); /* the stored weight's own name */
|
||||
w = decl_view(b, wn, own ? nullptr : src_wn, "codes", RAD_F8E4M3, { hi - lo, K }, access,
|
||||
RAD_SHARD_ROW, grp);
|
||||
s = decl_view(b, sn, src_wn, "scale", RAD_BF16, { fp8_blocks(hi - lo), fp8_blocks(K) },
|
||||
access, RAD_SHARD_ROW, grp);
|
||||
if (!w || !s) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi));
|
||||
return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK);
|
||||
}
|
||||
/* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi.
|
||||
* `split_n`, when set, is the stored width a row slice takes its K split from (docs/OPS.md). */
|
||||
rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K,
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes) const {
|
||||
std::initializer_list<rad_buf> reads, std::initializer_list<rad_buf> writes,
|
||||
int64_t split_n = 0) const {
|
||||
if (mx)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, s, ref)),
|
||||
reads, writes);
|
||||
if (split_n > 0)
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"),
|
||||
RAD_INT("split_n", split_n)),
|
||||
RAD_WEIGHTS(w, s)),
|
||||
reads, writes);
|
||||
return rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")),
|
||||
|
||||
@@ -159,6 +159,54 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its
|
||||
* anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). */
|
||||
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 2) return false;
|
||||
const long long bs = dflash_block(meta);
|
||||
if (bs <= 1) return false;
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A DFlash2 drafter's trunk taps, as the layers whose output the trunk copies into `dflash_src`.
|
||||
*
|
||||
* vLLM's speculators format names them `aux_hidden_state_layer_ids`, counted as vLLM captures
|
||||
* them: id i is the residual stream entering layer i, so the output of layer i - 1 (id n_layer,
|
||||
* which `--include-last-layer` emits, is the last layer's output). z-lab's `target_layer_ids` count
|
||||
* the layer whose output is taken. RedHatAI's 1 17 29 47 59 are this trunk's layers 0 16 28 46
|
||||
* 58. Id 0 would be the embedding, which no layer outputs, and is refused. */
|
||||
inline int dflash2_taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, int* out,
|
||||
int max) {
|
||||
if (ctx->max_spec <= 0 || dflash_kind(meta) != 2) return 0;
|
||||
const char* aux = rad_meta_gets(meta, "draft.aux_hidden_state_layer_ids", nullptr);
|
||||
int n = 0;
|
||||
if (aux) {
|
||||
int raw[16];
|
||||
const int m = parse_layer_ids(aux, n_layer + 1, raw, max < 16 ? max : 16);
|
||||
for (int i = 0; i < m; ++i) {
|
||||
if (raw[i] < 1) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter taps aux hidden state 0, the "
|
||||
"embedding, which no trunk layer outputs\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out[n++] = raw[i] - 1;
|
||||
}
|
||||
} else {
|
||||
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);
|
||||
n = parse_layer_ids(ids, n_layer, out, max);
|
||||
}
|
||||
if (n <= 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter names no trunk layer this model has; "
|
||||
"it is paired with a different target\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ============================================================== the block */
|
||||
|
||||
struct Dflash1 {
|
||||
|
||||
@@ -18,8 +18,10 @@
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
#include <arch/rad_gemma4_dflash.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cmath>
|
||||
@@ -117,8 +119,24 @@ struct G4Linear {
|
||||
void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const;
|
||||
/* the GEMM alone, for a caller that wrote the int8 pair itself (a fused norm + quantiser) */
|
||||
void gemm(RadCtx* c, rad_buf y, int64_t T) const;
|
||||
/* The same two over rows [r0, r0 + n) of the step: a slice of the prefill overlap. The
|
||||
* quantiser and the GEMM are a row at a time above their bands, so a slice's rows are the
|
||||
* whole step's (see "the prefill overlap" below). */
|
||||
void step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const;
|
||||
void gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const;
|
||||
};
|
||||
|
||||
/* A weight on the w4a8 / w8a8 grid: i4 or i8 codes with an f16 scale per [1 x 128], the encoding
|
||||
* gemm_nt_q reads against quant_act_i8's pair. */
|
||||
static bool g4_grid_w4(const RadEncoding& enc) {
|
||||
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
|
||||
const uint32_t cdt = enc.n_planes > 0 ? enc.plane[0].dtype : 0;
|
||||
return rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] &&
|
||||
(cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 &&
|
||||
sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128;
|
||||
}
|
||||
|
||||
/* An empty `src` means the caller made the weight's name map (a probe asked it first). */
|
||||
inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src,
|
||||
int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp,
|
||||
@@ -126,10 +144,10 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
std::initializer_list<int64_t> row_parts,
|
||||
const G4Linear* in_from) {
|
||||
N = n_out; K = n_in;
|
||||
if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL;
|
||||
if (N <= 0 || K <= 0) return RAD_E_INVAL;
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin()));
|
||||
else RAD_ARCH_TRY(map_concat(b, wn, src, 0));
|
||||
if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin()));
|
||||
else if (src.size() > 1) RAD_ARCH_TRY(map_concat(b, wn, src, 0));
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
/* A builder with no model behind it (a test, a synthetic tool) answers RAD_E_NOTFOUND, and
|
||||
@@ -153,16 +171,11 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
/* A w4 weight: i4 codes and an f16 scale per [1 x 128]. gemm_nt_q at w4a8 reads an int8
|
||||
* activation and an f32 per-row scale, so a quantiser over the bf16 plane `a` writes the int8
|
||||
* pair (q8, s8). The codes + scale layout is the same as w4a16's, so containers serve
|
||||
* unchanged. */
|
||||
const RadEncPlane* sc = rad_enc_plane(&enc, "scale");
|
||||
/* An 8-bit weight on the same grid (i8 codes, f16 scale per [1 x 128]): gemm_nt_q at w8a8
|
||||
* reads the same int8 activation and per-row scale as w4a8, so the quantiser is shared. A
|
||||
* recipe uses it for linears int4 hurts (attention, down_proj). */
|
||||
* unchanged. An 8-bit weight on the same grid (i8 codes, f16 scale per [1 x 128]): gemm_nt_q
|
||||
* at w8a8 reads the same int8 activation and per-row scale as w4a8, so the quantiser is
|
||||
* shared. A recipe uses it for linears int4 hurts (attention, down_proj). */
|
||||
const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0;
|
||||
const bool w4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] &&
|
||||
(cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 &&
|
||||
sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128;
|
||||
if (w4) {
|
||||
if (known && g4_grid_w4(enc)) {
|
||||
if (N % 16 || K % 128) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in "
|
||||
"16s and K in whole 128-column scale groups.\n", base,
|
||||
@@ -225,9 +238,27 @@ inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
brows(y, T), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
inline void G4Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (!quant) {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(a, r0, n, K), RAD_W(w), brow_slice(y, r0, n, N));
|
||||
return;
|
||||
}
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, 1), RAD_NONE);
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
|
||||
inline void G4Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, 1), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
/* ---- one attention block, parameterised by class. */
|
||||
struct Gemma4Attn {
|
||||
struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; };
|
||||
/* `qkv` is the fused projection's row, [max_tok, q | k | v], declared by the first layer of its
|
||||
* class that has one (the model's slot passed to declare). */
|
||||
struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0, qkv = 0; };
|
||||
|
||||
Wire w{};
|
||||
Geom g{};
|
||||
@@ -237,23 +268,46 @@ struct Gemma4Attn {
|
||||
|
||||
rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; /* the norms (always bf16) */
|
||||
G4Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; /* the GEMM weights (bf16 or w4a8) */
|
||||
/* q, k and v as one linear, where the container holds them so (blk.N.attn_qkv): one GEMM a
|
||||
* layer instead of three. q, k and v are then column slices of `w.qkv`. */
|
||||
G4Linear ln_qkv{};
|
||||
bool fused = false;
|
||||
rad_op op_norm = 0, op_vn = 0, op_qn = 0, op_kn = 0,
|
||||
op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0;
|
||||
/* the five prologue ops (v norm, q norm, k norm, two rotaries) as one, where it resolves */
|
||||
rad_op op_qnr = 0;
|
||||
/* Fused only: attention reading q where it lies in the row (attn_paged_qrow), where it resolves
|
||||
* to the kernel attn_paged would take anyway; else the copy of q into its own rows (`cast`) that
|
||||
* a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope the copies of
|
||||
* k and v too, ahead of the unfused prologue, which reads them dense. */
|
||||
rad_op op_attn_row = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0;
|
||||
|
||||
/* The linear whose int8 pair a junction writes, and whether every projection reads it. */
|
||||
const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; }
|
||||
bool reads_pair() const {
|
||||
return fused ? ln_qkv.quant
|
||||
: ln_q.quant && ln_k.shared_in && (!cls.has_v || ln_v.shared_in);
|
||||
}
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, const char* pre);
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot);
|
||||
/* `entry_done`: a junction op already wrote this block's quantised input (ln_q's pair).
|
||||
* `tail_fused`: the caller issues the post-norm and the add as a junction op. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
bool ar_fused = false) const;
|
||||
/* step()'s parts, for the prefill overlap: the projections over rows [r0, r0 + n) from the
|
||||
* pair a junction wrote, everything between the projections and o_proj over the whole step
|
||||
* (it reads every row's keys), and o_proj over rows [r0, r0 + n). */
|
||||
void project(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
void attend(RadCtx* c, const RadBatch* batch) const;
|
||||
void out_proj(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
};
|
||||
|
||||
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, const char* pre) {
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot) {
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
|
||||
|
||||
/* The norms: always bf16 (no rule matches them), name map first. */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
|
||||
@@ -271,18 +325,50 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
/* The GEMM weights: bf16 or w4a8, probed by G4Linear. */
|
||||
RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) },
|
||||
qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q));
|
||||
const G4Linear* qin = &ln_q; /* k and v read q's int8 pair */
|
||||
RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l) },
|
||||
kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin));
|
||||
if (cls.has_v)
|
||||
RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l) },
|
||||
kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin));
|
||||
/* The GEMM weights: bf16 or w4a8, probed by G4Linear.
|
||||
*
|
||||
* q, k and v are one linear, `blk.N.attn_qkv` (q | k | v, or q | k on a k_eq_v class), where
|
||||
* the weight is on the w4a8 / w8a8 grid: a recipe that names it (rad-convert answers the
|
||||
* probe from the recipe) or a container converted with one. Each rank takes its slice of each
|
||||
* part, so the row holds this rank's q, k and v heads. The rows are q's, k's and v's rows, and
|
||||
* the grid's groups never cross a row, so the codes are the three linears' codes (libr4d's
|
||||
* skinny GEMM picks its K split from N, so on a card k and v may round differently in the last
|
||||
* bit). One GEMM a layer reads the three weights in one pass where three paid the skinny GEMM's
|
||||
* fixed cost each: on the R9700 at decode (--profile-ops, tp 4) q, k and v take 17 + 13.5 +
|
||||
* 13.5 us and a 4096-row GEMM of the same K 25 us. A container that holds the three apart, or
|
||||
* bf16 weights, keeps three linears reading q's int8 pair. */
|
||||
const char* q_src = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l);
|
||||
const char* k_src = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l);
|
||||
const char* v_src = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l);
|
||||
const char* qkv_wn = nm.f("blk.%d.attn_qkv.weight", l);
|
||||
if (cls.has_v) RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src, v_src }));
|
||||
else RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src }));
|
||||
{
|
||||
RadEncoding e{};
|
||||
fused = weight_enc(b, qkv_wn, &e) && g4_grid_w4(e);
|
||||
}
|
||||
if (fused) {
|
||||
if (!qkv_slot) return RAD_E_INVAL;
|
||||
if (!*qkv_slot)
|
||||
*qkv_slot = decl_b(b, nm.f(cls.has_v ? "attn_qkvs" : "attn_qkvg"), g.act_dtype,
|
||||
{g.max_tok, qkvd});
|
||||
w.qkv = *qkv_slot;
|
||||
if (cls.has_v)
|
||||
RAD_ARCH_TRY(ln_qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), {}, qkvd, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), w.h, w.qkv, {qd, kvd, kvd}));
|
||||
else
|
||||
RAD_ARCH_TRY(ln_qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), {}, qkvd, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), w.h, w.qkv, {qd, kvd}));
|
||||
} else {
|
||||
RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), { q_src },
|
||||
qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q));
|
||||
const G4Linear* qin = &ln_q; /* k and v read q's int8 pair */
|
||||
RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), { k_src },
|
||||
kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin));
|
||||
if (cls.has_v)
|
||||
RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), { v_src },
|
||||
kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin));
|
||||
}
|
||||
RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) },
|
||||
g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h));
|
||||
@@ -340,22 +426,27 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
/* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
|
||||
* use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
|
||||
* so 1.0 is passed explicitly. */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window),
|
||||
RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd) {
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
rd, {w.attn});
|
||||
};
|
||||
|
||||
/* The prologue as one op: libr4d's `qkv_norm_rope` is rmsnorm_p + rmsnorm + rmsnorm + rope +
|
||||
* rope over the three projections, byte-identical, one workgroup per (token, head). Declared
|
||||
* beside the unfused five and used only where it resolves; a multi-component or YaRN rotary
|
||||
* keeps the five, as does an engine whose libraries do not declare it (CPU-only), where asking
|
||||
* for it would stop the declare. */
|
||||
if (!g.rope_mc && g.yarn.factor == 0.0f && rad_op_declared(b, "qkv_norm_rope")) {
|
||||
* for it would stop the declare. It reads q, k and v at their own row pitches, so on a fused
|
||||
* layer it works in place on the row's column slices. */
|
||||
auto decl_qnr = [&]() {
|
||||
if (g.rope_mc || g.yarn.factor != 0.0f || !rad_op_declared(b, "qkv_norm_rope")) return;
|
||||
op_qnr = RAD_OP(b, "qkv_norm_rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv),
|
||||
@@ -367,17 +458,60 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn, w_kn));
|
||||
/* A k_eq_v class derives v from the raw k: v is written, never read. */
|
||||
op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v})
|
||||
: rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v});
|
||||
if (fused)
|
||||
op_qnr = cls.has_v ? rw(b, op_qnr, {w.qkv}, {w.qkv})
|
||||
: rw(b, op_qnr, {w.qkv}, {w.qkv, w.v});
|
||||
else
|
||||
op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v})
|
||||
: rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v});
|
||||
};
|
||||
|
||||
/* A column slice of the fused row copied into its own rows (`cast`, bf16 to bf16, which every
|
||||
* library takes with pitched operands). */
|
||||
auto lift = [&](int64_t n, rad_buf dst) {
|
||||
return rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.qkv}, {dst});
|
||||
};
|
||||
|
||||
if (!fused) {
|
||||
op_attn = attn("attn_paged", {w.q});
|
||||
decl_qnr();
|
||||
} else {
|
||||
/* The prologue first: what attention reads depends on it. Without it the unfused five read
|
||||
* q, k and v dense, so all three are copied out of the row ahead of them. */
|
||||
decl_qnr();
|
||||
if (!op_qnr) {
|
||||
op_lift_k = lift(kvd, w.k);
|
||||
if (cls.has_v) op_lift_v = lift(kvd, w.v);
|
||||
}
|
||||
/* With it attention reads q in the row where that costs nothing. libr4d's dedicated paged
|
||||
* kernels stop at head_dim 256; at 512 (the global class) attn_paged takes the windowed
|
||||
* kernel, which is the kernel attn_paged_qrow takes, so the row is read in place. At 256 the
|
||||
* dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed kernel's time
|
||||
* (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW), so the sliding class keeps attn_paged: a step
|
||||
* of one row reads q in place (one row of a slice is dense), a taller one copies q out. */
|
||||
if (op_qnr && cls.head_dim > 256 && rad_op_declared(b, "attn_paged_qrow"))
|
||||
op_attn_row = attn("attn_paged_qrow", {w.qkv});
|
||||
if (!op_attn_row) {
|
||||
op_lift_q = lift(qd, w.q);
|
||||
op_attn = attn("attn_paged", {w.q, w.qkv});
|
||||
}
|
||||
}
|
||||
|
||||
op_kv = rw(b, RAD_OP(b, "kv_store",
|
||||
/* On a fused layer with the one-op prologue, k and v are stored from the row (kv_store takes
|
||||
* them at their own pitches); a k_eq_v class's v is its own buffer either way. */
|
||||
op_kv = RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("n_head_kv", cls.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}, {});
|
||||
RAD_NOWEIGHTS);
|
||||
if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {});
|
||||
else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {});
|
||||
else op_kv = rw(b, op_kv, {w.qkv, w.v}, {});
|
||||
|
||||
/* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */
|
||||
if (g.world > 1)
|
||||
@@ -404,13 +538,13 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
|
||||
void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) 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 (entry_done) {
|
||||
if (fused) {
|
||||
if (!entry_done) RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
if (entry_done) ln_qkv.gemm(c, w.qkv, T);
|
||||
else ln_qkv.step(c, w.h, w.qkv, T);
|
||||
} else if (entry_done) {
|
||||
ln_q.gemm(c, w.q, T);
|
||||
ln_k.gemm(c, w.k, T);
|
||||
if (cls.has_v) ln_v.gemm(c, w.v, T);
|
||||
@@ -420,11 +554,53 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
ln_k.step(c, w.h, w.k, T);
|
||||
if (cls.has_v) ln_v.step(c, w.h, w.v, T);
|
||||
}
|
||||
attend(c, batch);
|
||||
|
||||
ln_o.step(c, w.attn, w.h, T);
|
||||
/* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a
|
||||
* partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (tail_fused) return;
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
void Gemma4Attn::project(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
if (fused) {
|
||||
ln_qkv.gemm_rows(c, w.qkv, r0, n);
|
||||
return;
|
||||
}
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
ln_k.gemm_rows(c, w.k, r0, n);
|
||||
if (cls.has_v) ln_v.gemm_rows(c, w.v, r0, n);
|
||||
}
|
||||
|
||||
void Gemma4Attn::out_proj(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
ln_o.step_rows(c, w.attn, w.h, r0, n);
|
||||
}
|
||||
|
||||
void Gemma4Attn::attend(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 qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
|
||||
* one-op prologue the row's column slices (a k_eq_v class's v is its own buffer either way). */
|
||||
const bool row = fused && op_qnr;
|
||||
const RadOperand Q = row ? bcol(w.qkv, 0, qd, T) : brows(w.q, T);
|
||||
const RadOperand K = row ? bcol(w.qkv, qd, kvd, T) : brows(w.k, T);
|
||||
const RadOperand V = row && cls.has_v ? bcol(w.qkv, qd + kvd, kvd, T) : brows(w.v, T);
|
||||
|
||||
if (op_qnr) {
|
||||
RAD_ISSUE(c, op_qnr, brows(w.q, T), brows(w.k, T), brows(w.v, T), rope_posmc(g, batch, T),
|
||||
RAD_W(w_qn), RAD_W(w_kn));
|
||||
RAD_ISSUE(c, op_qnr, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn));
|
||||
} else {
|
||||
if (fused) { /* the unfused five read q, k and v dense */
|
||||
RAD_ISSUE_N(c, op_lift_q, T, bcol(w.qkv, 0, qd, T), brows(w.q, T));
|
||||
RAD_ISSUE_N(c, op_lift_k, T, bcol(w.qkv, qd, kvd, T), brows(w.k, T));
|
||||
if (cls.has_v) RAD_ISSUE_N(c, op_lift_v, T, bcol(w.qkv, qd + kvd, kvd, T), brows(w.v, T));
|
||||
}
|
||||
/* Normalise v first: on a k_eq_v class v derives from the raw k, before k_norm rewrites it. */
|
||||
RAD_ISSUE_N(c, op_vn, T * cls.n_head_kv, brows(cls.has_v ? w.v : w.k, T), brows(w.v, T));
|
||||
RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T));
|
||||
@@ -434,23 +610,25 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, op_kv, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, layer),
|
||||
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
|
||||
rad_op a_op = op_attn;
|
||||
RadOperand a_q = brows(w.q, T);
|
||||
if (op_attn_row) {
|
||||
a_op = op_attn_row;
|
||||
a_q = Q;
|
||||
} else if (row) {
|
||||
if (T == 1) a_q = Q;
|
||||
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, a_op, batch->max_q_len,
|
||||
a_q, 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, T));
|
||||
|
||||
ln_o.step(c, w.attn, w.h, T);
|
||||
/* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a
|
||||
* partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */
|
||||
if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
if (tail_fused) return;
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
/* ---- the feed-forward: GELU (not SwiGLU), with a second norm on the down-projection output. */
|
||||
@@ -469,8 +647,32 @@ struct Gemma4Mlp {
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre);
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
bool ar_fused = false) const;
|
||||
/* For the prefill overlap, over rows [r0, r0 + n): the arm from the pair a junction wrote to
|
||||
* down_proj's partial in `h`, and the post-norm and add the last layer takes unfused. */
|
||||
void arm(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
void tail(RadCtx* c, int64_t r0, int64_t n) const;
|
||||
};
|
||||
|
||||
void Gemma4Mlp::arm(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
const int64_t F = g.n_ff;
|
||||
ln_gu.gemm_rows(c, w.gu, r0, n);
|
||||
if (op_gq) {
|
||||
RAD_ISSUE_N(c, op_gq, n, brow_slice(w.gu, r0, n, 2 * F), brow_slice(ln_down.q8, r0, n, F),
|
||||
brow_slice(ln_down.s8, r0, n, 1), RAD_NONE);
|
||||
ln_down.gemm_rows(c, w.h, r0, n);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * F), brow_slice(w.ffn, r0, n, F));
|
||||
ln_down.step_rows(c, w.ffn, w.h, r0, n);
|
||||
}
|
||||
}
|
||||
|
||||
void Gemma4Mlp::tail(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
const int64_t E = g.n_embd;
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, E), RAD_W(w_post), brow_slice(w.h, r0, n, E));
|
||||
RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, E), brow_slice(w.h, r0, n, E),
|
||||
brow_slice(w.x, r0, n, E));
|
||||
}
|
||||
|
||||
int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre) {
|
||||
g = geom; layer = l; w = wire;
|
||||
|
||||
@@ -627,6 +829,13 @@ struct G4Junction {
|
||||
brows(q8, T), brows(s8, T), RAD_NONE,
|
||||
wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE);
|
||||
}
|
||||
/* Rows [r0, r0 + n), without the all-reduce: a slice of the prefill overlap, whose reduction
|
||||
* rode the second lane. */
|
||||
void step_rows(RadCtx* c, int64_t E, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(x, r0, n, E), res ? brow_slice(res, r0, n, E) : RAD_NONE,
|
||||
RAD_W(w), brow_slice(q8, r0, n, E), brow_slice(s8, r0, n, 1), RAD_NONE,
|
||||
wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
/* ==================================================================== the assistant head
|
||||
@@ -1088,6 +1297,13 @@ void Gemma4Head::step(RadCtx* c, const RadBatch* batch) const {
|
||||
ln_post.step(c, b_hd, b_hn, T);
|
||||
}
|
||||
|
||||
/* The prefill overlap's smallest slice (trunk_overlap). It is above every row band the sliced
|
||||
* kernels have, with room to spare: the int8 GEMMs' skinny band (64) and r4d_act_threads' last
|
||||
* width change at these widths (120 rows), which fixes the norms' and the quantisers'
|
||||
* sum-of-squares partition. And it is large enough that a slice's reduction is worth a second
|
||||
* lane. */
|
||||
static constexpr int64_t kOverlapRows = 512;
|
||||
|
||||
struct Layer {
|
||||
bool global = false;
|
||||
Gemma4Attn attn{};
|
||||
@@ -1115,6 +1331,7 @@ struct Model {
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
rad_buf b_qs = 0, b_ks = 0, b_vs = 0, b_attns = 0; /* sliding rows */
|
||||
rad_buf b_qg = 0, b_kg = 0, b_vg = 0, b_atting = 0; /* global rows */
|
||||
rad_buf b_qkvs = 0, b_qkvg = 0; /* the fused projections' rows, where a layer has one */
|
||||
rad_buf b_gu = 0, b_ffn = 0;
|
||||
|
||||
rad_weight w_tok = 0, w_out = 0, w_lm = 0;
|
||||
@@ -1136,6 +1353,9 @@ 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) */
|
||||
/* A prefill step of 2 * kOverlapRows rows or more runs as two slices, each slice's
|
||||
* all-reduces on the second lane beside the other's compute (trunk_overlap). Set at declare. */
|
||||
bool overlap = false;
|
||||
|
||||
/* 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
|
||||
@@ -1147,10 +1367,214 @@ struct Model {
|
||||
gemma4::Dflash1 df{};
|
||||
rad_kvgroup kv_draft = 0;
|
||||
bool have_df = false;
|
||||
/* Or a DFlash2 drafter (arch/common/rad_block_dflash2.h): RedHatAI's speculators-format one
|
||||
* for the 31B. Same taps and plane; its own block, buffers and KV group. */
|
||||
Dflash2 df2{};
|
||||
Dflash2::Wire df2w{};
|
||||
bool have_df2 = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* A DFlash2 drafter's config key, from vLLM's speculators layout (the speculator's keys at the
|
||||
* top of `draft.`) or z-lab's (under `draft.dflash_config.`), whichever the checkpoint has. */
|
||||
static long long df2_geti(const RadModelMeta* meta, const char* key, long long dflt) {
|
||||
char k[160];
|
||||
std::snprintf(k, sizeof k, "draft.%s", key);
|
||||
const long long v = rad_meta_geti(meta, k, LLONG_MIN);
|
||||
if (v != LLONG_MIN) return v;
|
||||
std::snprintf(k, sizeof k, "draft.dflash_config.%s", key);
|
||||
return rad_meta_geti(meta, k, dflt);
|
||||
}
|
||||
|
||||
/* The DFlash2 drafter: RedHatAI/gemma-4-31B-it-speculator.dflash2, a speculators-format DFlash2
|
||||
* (z-lab's architecture, trained by Red Hat on gemma-4-31B-it's outputs) in place of z-lab's
|
||||
* DFlash. rad_block_dflash2.h is the block; this reads its config and wires it to the trunk.
|
||||
*
|
||||
* From the checkpoint and speculators' code (models/dflash2, models/dflash/core.py):
|
||||
*
|
||||
* - five Qwen3-shaped layers at the trunk's width, every one sliding (2048) and non-causal;
|
||||
* - the target's table as a plain nn.Embedding: no Gemma sqrt(hidden) scale (z-lab's DFlash
|
||||
* goes through the target's scaled module; this one does not), so the block's unscaled
|
||||
* lookup is right;
|
||||
* - the target's head as a plain linear, no soft-cap, which the block's head is;
|
||||
* - taps counted as vLLM captures them, the residual entering a layer (gemma4::dflash2_taps);
|
||||
* - block 8: the anchor predicts nothing, seven drafts (sample_from_anchor false).
|
||||
*
|
||||
* The head reads the 8-bit copy the -df2 recipe makes (rad_block_dflash2.h, head_i8), so the
|
||||
* selector ranks what an 8-bit head proposes. Nothing here is defaulted quietly: a config this
|
||||
* block does not implement is refused by name. */
|
||||
static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx,
|
||||
Model& m) {
|
||||
Names& nm = m.nm;
|
||||
Geom dg{};
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash2"));
|
||||
const char* lp = drafter_layer_prefix(meta);
|
||||
char key[160];
|
||||
std::snprintf(key, sizeof key, "%shidden_size", lp);
|
||||
if (rad_meta_geti(meta, key, dg.n_embd) != dg.n_embd) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter is %lld wide and the trunk %lld; its "
|
||||
"fc and residual stream are the trunk's width\n",
|
||||
rad_meta_geti(meta, key, 0), (long long)dg.n_embd);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::snprintf(key, sizeof key, "%shidden_act", lp);
|
||||
const char* act = rad_meta_gets(meta, key, "silu");
|
||||
if (std::strcmp(act, "silu")) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter's MLP uses %s; the block's is silu\n",
|
||||
act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (df2_geti(meta, "sample_from_anchor", 0)) {
|
||||
fprintf(stderr, "radiance: gemma4: this DFlash2 drafter samples from its anchor row; the "
|
||||
"block's anchor predicts nothing\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = df2_geti(meta, "conv_kernel_size", 2);
|
||||
dc.group = df2_geti(meta, "conv_group_size", 16);
|
||||
dc.sel_rank = df2_geti(meta, "selector_rank", 0);
|
||||
dc.sel_topk = df2_geti(meta, "selector_top_k", 0);
|
||||
if (dc.sel_rank <= 0 || dc.sel_topk <= 0) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter states no selector geometry (rank "
|
||||
"%lld, top_k %lld)\n", (long long)dc.sel_rank, (long long)dc.sel_topk);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Attention: one window for every layer, since the block issues one attention op. A sliding
|
||||
* window non-causal within the block is speculators' sliding_window_non_causal; z-lab's
|
||||
* layout says is_causal. */
|
||||
{
|
||||
std::snprintf(key, sizeof key, "%slayer_types", lp);
|
||||
std::vector<int> sliding;
|
||||
if (const char* lt = rad_meta_gets(meta, key, nullptr))
|
||||
RAD_ARCH_TRY(parse_layer_kinds("gemma4 DFlash2", lt, {"sliding_attention"},
|
||||
"full_attention", &sliding));
|
||||
const bool any_full = std::find(sliding.begin(), sliding.end(), 0) != sliding.end();
|
||||
const bool any_slide = std::find(sliding.begin(), sliding.end(), 1) != sliding.end();
|
||||
if (any_full && any_slide) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash2 drafter mixes sliding and full layers; "
|
||||
"the block takes one attention width for all of them\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::snprintf(key, sizeof key, "%ssliding_window", lp);
|
||||
const long long win = rad_meta_geti(meta, key, 0);
|
||||
std::snprintf(key, sizeof key, "%suse_sliding_window", lp);
|
||||
if (any_slide || rad_meta_geti(meta, key, 0))
|
||||
dc.window = df2_geti(meta, "swa_window_size", win);
|
||||
const long long nc = rad_meta_geti(meta, "draft.sliding_window_non_causal", -1);
|
||||
dc.causal = nc >= 0 ? (nc ? 0 : 1) : (rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0);
|
||||
}
|
||||
|
||||
/* The query block must be a power of two (the convolution masks a row's position with
|
||||
* block_size - 1), and the depth the probe named is the trained one. */
|
||||
const long long trained = gemma4::dflash_block(meta);
|
||||
if (dc.block < 2 || (dc.block & (dc.block - 1))) {
|
||||
fprintf(stderr, "radiance: gemma4: DFlash2's convolution masks the block position with "
|
||||
"block_size - 1, so the query block must be a power of two; %d draft "
|
||||
"tokens make it %lld (trained at %lld)\n",
|
||||
ctx->max_spec, (long long)dc.block, trained);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (trained > 0 && trained != dc.block)
|
||||
rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at %lld; "
|
||||
"it accepts less away from its trained block", trained, trained - 1,
|
||||
(long long)dc.block);
|
||||
/* The three scalars rad_block_dflash2.h does not apply (z-lab's names; speculators has none). */
|
||||
if (rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0) != 1.0 ||
|
||||
rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0) != 1.0 ||
|
||||
rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0) != 0.0) {
|
||||
fprintf(stderr, "radiance: gemma4: this DFlash2 checkpoint scales its embedding or its "
|
||||
"logits, or soft-caps them; the block applies none of the three\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, (int)m.n_main, &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 spad = ((sr + 15) / 16) * 16;
|
||||
|
||||
Dflash2::Wire& dw = m.df2w;
|
||||
dw.src = m.b_dfsrc;
|
||||
dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, 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.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd});
|
||||
dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(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.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.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd});
|
||||
dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32,
|
||||
{dg.max_tok, fp8_blocks(dc.n_taps * 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.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd});
|
||||
dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)});
|
||||
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.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.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank});
|
||||
dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd});
|
||||
dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1});
|
||||
dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad});
|
||||
dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)});
|
||||
/* No rescoring against the trunk's head: the -df2 recipe's head is already 8-bit, so the
|
||||
* candidates are the ones an 8-bit head ranks (rad_block_dflash2.h, head_i8). */
|
||||
const int64_t tw = dc.sel_topk;
|
||||
dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw});
|
||||
dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw});
|
||||
if (Dflash2::head_sharded(dg)) {
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
|
||||
|
||||
/* The head copy comes from the tied table, under the block's own name; the recipe makes it
|
||||
* 8-bit. */
|
||||
RAD_ARCH_TRY(m.df2.declare(b, nm, dg, dc, (int)m.n_main, m.kv_draft, m.w_tok, "draft",
|
||||
nm.ckpt("model.language_model.embed_tokens.weight"), dw));
|
||||
m.have_df2 = true;
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dflash2";
|
||||
drf.kind = RAD_DRAFT_BLOCK;
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = dc.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = dc.steps();
|
||||
drf.window = dc.window;
|
||||
drf.mask_token = (int32_t)df2_geti(meta, "mask_token_id", -1);
|
||||
if (drf.mask_token < 0) {
|
||||
fprintf(stderr, "radiance: gemma4: this DFlash2 checkpoint declares no mask_token_id, and "
|
||||
"every drafted position embeds it\n");
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %lld.., %lld heads / %lld kv x %lld, ffn "
|
||||
"%lld, %s attention with a %lld-token window, %d trunk taps; one forward proposes "
|
||||
"%lld tokens through the candidate selector, its head %s",
|
||||
(long long)dg.n_layer, (long long)m.n_main, (long long)dg.n_head_all,
|
||||
(long long)dg.n_head_kv_all, (long long)dg.head_dim, (long long)dg.n_ff_all,
|
||||
dc.causal ? "causal" : "non-causal", (long long)dc.window, m.n_taps,
|
||||
(long long)dc.steps(), m.df2.head_i8 ? "8-bit" : "2-bit");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
@@ -1273,7 +1697,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* 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);
|
||||
const int n = gemma4::dflash_kind(meta) == 2
|
||||
? gemma4::dflash2_taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS)
|
||||
: 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)
|
||||
@@ -1342,7 +1768,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre,
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre));
|
||||
|
||||
/* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */
|
||||
@@ -1378,10 +1805,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.n_main > 0) {
|
||||
bool ok = true;
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in &&
|
||||
(!lay.attn.cls.has_v || lay.attn.ln_v.shared_in) && lay.mlp.ln_gu.quant;
|
||||
ok = ok && lay.attn.reads_pair() && lay.mlp.ln_gu.quant;
|
||||
if (ok) {
|
||||
RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, 0, m.layers[0].attn.ln_q));
|
||||
RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, 0,
|
||||
m.layers[0].attn.ln_in()));
|
||||
ok = m.j0.op != 0;
|
||||
for (int64_t l = 0; ok && l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
@@ -1391,7 +1818,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ok && l + 1 < m.n_main) {
|
||||
const Layer& nx = m.layers[(size_t)l + 1];
|
||||
RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post,
|
||||
lay.w_scalar, nx.attn.ln_q));
|
||||
lay.w_scalar, nx.attn.ln_in()));
|
||||
ok = lay.j_ma.op != 0;
|
||||
}
|
||||
}
|
||||
@@ -1409,6 +1836,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.ar_rows = ar ? rows : 0;
|
||||
}
|
||||
|
||||
/* ---- the prefill overlap (trunk_overlap). It needs a reduction to hide, every junction fused
|
||||
* (the slices issue only the fused forms), and the exact wire, the one shown to give a slice
|
||||
* the bits it gives the whole. The buffer the second lane reduces in place is taken out of the
|
||||
* arena's sharing, which the runtime asks of every buffer a second lane touches; it lives
|
||||
* across the whole trunk already. */
|
||||
const char* ov = std::getenv("RADIANCE_GEMMA4_OVERLAP"); /* 0: every step whole */
|
||||
const bool ov_off = ov && !std::strcmp(ov, "0");
|
||||
m.overlap = !ov_off && g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows;
|
||||
for (const Layer& lay : m.layers)
|
||||
m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar;
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
|
||||
/* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */
|
||||
m.op_final = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
@@ -1457,7 +1896,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* 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) {
|
||||
if (m.n_taps > 0 && gemma4::dflash_kind(meta) == 2) {
|
||||
RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m));
|
||||
} else if (m.n_taps > 0) {
|
||||
gemma4::Dflash1::Trunk t{};
|
||||
t.n_taps = m.n_taps;
|
||||
t.escale = gemma4::embed_scale(g.n_embd);
|
||||
@@ -1478,6 +1919,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
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);
|
||||
else if (gemma4::dflash_kind(meta) == 2) {
|
||||
char k[160];
|
||||
std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta));
|
||||
head_groups = rad_meta_geti(meta, k, 0);
|
||||
}
|
||||
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
|
||||
"model.", "gemma4_bf16"));
|
||||
}
|
||||
@@ -1487,6 +1933,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)n_global,
|
||||
(long long)(g.n_layer - n_global), (long long)sliding_win,
|
||||
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g);
|
||||
{
|
||||
int64_t n_fused = 0, n_row = 0;
|
||||
for (const Layer& lay : m.layers) {
|
||||
n_fused += lay.attn.fused ? 1 : 0;
|
||||
n_row += lay.attn.op_attn_row ? 1 : 0;
|
||||
}
|
||||
if (n_fused)
|
||||
rad_note(b, "q, k and v as one linear (blk.*.attn_qkv) on %lld of %lld layers; attention "
|
||||
"reads q in the row on %lld, copies it out above one row on the rest",
|
||||
(long long)n_fused, (long long)m.layers.size(), (long long)n_row);
|
||||
else
|
||||
rad_note(b, "q, k and v as three linears (a container converted before attn_qkv, or "
|
||||
"bf16 weights): convert with a recipe naming blk.*.attn_qkv.weight for one");
|
||||
}
|
||||
if (g.world > 1) {
|
||||
if (m.overlap)
|
||||
rad_note(b, "prefill overlap: a step of %lld rows or more runs as two slices, each "
|
||||
"slice's all-reduces on a second stream beside the other's compute",
|
||||
(long long)(2 * kOverlapRows));
|
||||
else
|
||||
rad_note(b, "prefill overlap: off (%s)",
|
||||
ov_off ? "RADIANCE_GEMMA4_OVERLAP=0"
|
||||
: !g.wire_exact ? "the lossy all-reduce wire"
|
||||
: !m.fuse ? "the residual junctions are not fused"
|
||||
: "a step holds fewer than two slices");
|
||||
}
|
||||
if (m.fuse && (g.world == 2 || g.world == 4)) {
|
||||
if (!m.fuse_ar)
|
||||
rad_note(b, "residual junctions: the all-reduce in front of each issued apart");
|
||||
@@ -1500,6 +1972,109 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ==================================================================== the prefill overlap
|
||||
*
|
||||
* A prefill step in two slices, each slice's all-reduces on the runtime's second lane (rad_lane)
|
||||
* beside the other slice's compute: arch/gemma4's trunk_overlap, on this trunk. A layer reduces
|
||||
* T x n_embd twice, after o_proj and after down_proj, both column-sharded; run whole, the
|
||||
* reductions and the compute take turns. Cut in two, a slice's reduction runs while the other
|
||||
* slice computes:
|
||||
*
|
||||
* lane 0 o(A) o(B) . jam(A) arm(A) . jam(B) arm(B) . jma(A) qkv(A) . jma(B) qkv(B) attn o(A) ..
|
||||
* lane 1 ar(A) ar(B) ar(A) ar(B)
|
||||
*
|
||||
* Attention runs whole (the prologue, the cache write and attn_paged): it reads every row's keys,
|
||||
* and its batch bounds describe the whole step. The rest is a row at a time: the projections, the
|
||||
* junctions, the feed-forward arm and the reductions.
|
||||
*
|
||||
* The same kernels give the same bits (core/runtime/ctx.h, the second lane's rule four). Both slices
|
||||
* are at least kOverlapRows rows: above the int8 GEMMs' skinny band, whose prefill and tiled
|
||||
* kernels take each row's K in order whatever M is; above r4d_act_threads' last width change, so
|
||||
* every junction, quantiser and norm folds a row's sum of squares as the whole step's does; and the
|
||||
* exact all-reduce folds a word in fp32 in ascending rank order whatever message carries it. On
|
||||
* the exact wire only.
|
||||
*
|
||||
* One buffer carries both reductions: o_proj and down_proj both write `h`, and the junctions read
|
||||
* it. So the order below never lets lane 0 write rows of `h` lane 1 is reducing: slice A's arm
|
||||
* writes h[A] only after A's attention reduction was waited for, while lane 1 reduces h[B]. Every
|
||||
* reduction rides lane 1 behind a join from lane 0, which holds its producer; lane 0 waits for lane
|
||||
* 1 before the reduction's consumer; each wait goes in after the lane-0 work that does not need it.
|
||||
* The embedding's reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so
|
||||
* the collectives keep one order on every rank. At two ranks the junctions here carry no
|
||||
* all-reduce (the reduction rode lane 1); a step that runs whole keeps the fused one. */
|
||||
static int64_t split_at(const Model& m, int64_t T) {
|
||||
if (!m.overlap || T < 2 * kOverlapRows) return 0;
|
||||
return (T / 2) / 128 * 128; /* slice A whole 128-row tiles; both slices >= kOverlapRows */
|
||||
}
|
||||
|
||||
static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int64_t cut) {
|
||||
const int64_t T = batch->n_tok, E = m.g.n_embd;
|
||||
const int64_t a0 = 0, an = cut, b0 = cut, bn = T - cut;
|
||||
bool lanes_ok = true;
|
||||
/* An all-reduce in place over rows [r0, r0 + n) of `h`, on lane 1 behind everything lane 0
|
||||
* has issued -- its producer among it. */
|
||||
auto reduce = [&](rad_op op, int64_t r0, int64_t n) {
|
||||
lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK;
|
||||
RAD_ISSUE_N(c, op, n * E, brow_slice(m.b_h, r0, n, E), RAD_NONE);
|
||||
lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok;
|
||||
};
|
||||
/* Lane 0 behind every reduction issued so far. */
|
||||
auto join_back = [&] { lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; };
|
||||
/* Rows [r0, r0 + n) of layer li's end, once their feed-forward reduction is in: the junction
|
||||
* into the next layer -- or the last layer's post-norm, add and scalar -- and the drafter's
|
||||
* taps of those rows. */
|
||||
auto join_ff = [&](size_t li, int64_t r0, int64_t n) {
|
||||
const Layer& y = m.layers[li];
|
||||
if (li + 1 < m.layers.size()) {
|
||||
y.j_ma.step_rows(c, E, r0, n);
|
||||
} else {
|
||||
y.mlp.tail(c, r0, n);
|
||||
RAD_ISSUE_N(c, y.op_scale, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_scalar),
|
||||
brow_slice(m.b_x, r0, n, E));
|
||||
}
|
||||
for (int t = 0; t < m.n_taps && y.op_tap; ++t)
|
||||
if (m.tap_layer[t] == (int)li)
|
||||
RAD_ISSUE_N(c, y.op_tap, n, brow_slice(m.b_x, r0, n, E),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * E, (int64_t)t * E, E, n));
|
||||
};
|
||||
|
||||
m.j0.step(c, T);
|
||||
const size_t L = m.layers.size();
|
||||
for (size_t li = 0; li < L; ++li) {
|
||||
const Layer& y = m.layers[li];
|
||||
if (li == 0) {
|
||||
y.attn.project(c, a0, an);
|
||||
y.attn.project(c, b0, bn);
|
||||
} else {
|
||||
join_ff(li - 1, a0, an); /* its reduction was waited for last layer */
|
||||
y.attn.project(c, a0, an);
|
||||
join_back(); /* the last layer's feed-forward, slice B */
|
||||
join_ff(li - 1, b0, bn);
|
||||
y.attn.project(c, b0, bn);
|
||||
}
|
||||
y.attn.attend(c, batch);
|
||||
y.attn.out_proj(c, a0, an);
|
||||
reduce(y.attn.op_ar, a0, an);
|
||||
y.attn.out_proj(c, b0, bn);
|
||||
join_back(); /* attention, slice A */
|
||||
reduce(y.attn.op_ar, b0, bn);
|
||||
y.j_am.step_rows(c, E, a0, an);
|
||||
y.mlp.arm(c, a0, an);
|
||||
join_back(); /* attention, slice B */
|
||||
reduce(y.mlp.op_ar, a0, an);
|
||||
y.j_am.step_rows(c, E, b0, bn);
|
||||
y.mlp.arm(c, b0, bn);
|
||||
join_back(); /* the feed-forward, slice A */
|
||||
reduce(y.mlp.op_ar, b0, bn);
|
||||
}
|
||||
join_ff(L - 1, a0, an);
|
||||
join_back(); /* the last feed-forward, slice B */
|
||||
join_ff(L - 1, b0, bn);
|
||||
if (!lanes_ok)
|
||||
rad_step_fail(c, "gemma4_bf16: the prefill overlap could not order its second lane against "
|
||||
"the first");
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
@@ -1517,6 +2092,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
if (m.have_df2) {
|
||||
if (batch->draft_pass > 0) m.df2.step(c, batch);
|
||||
else m.df2.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 DFlash drafter, or declare "
|
||||
@@ -1538,10 +2118,12 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok));
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
if (m.fuse) m.j0.step(c, T);
|
||||
const int64_t cut = split_at(m, T);
|
||||
if (cut > 0) trunk_overlap(c, m, batch, cut);
|
||||
else if (m.fuse) m.j0.step(c, T);
|
||||
/* the junctions carry the reductions in front of them in a step their fold serves */
|
||||
const bool far = m.fuse_ar && T <= m.ar_rows;
|
||||
for (size_t li = 0; li < m.layers.size(); ++li) {
|
||||
for (size_t li = 0; cut == 0 && li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, far);
|
||||
@@ -1595,8 +2177,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
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). */
|
||||
/* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h); a
|
||||
* DFlash2 one too (rad_block_dflash2.h). */
|
||||
(void)gemma4::dflash_probe(meta, out);
|
||||
(void)gemma4::dflash2_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);
|
||||
|
||||
Reference in new issue
Block a user