Archived
merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across
conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
commit
7c3b5ab7d5
285 files changed
+30500
-2898
No files matched your search
+37
-24
@@ -596,25 +596,30 @@ inline rad_op rw(RadBuilder* b, rad_op h,
|
||||
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
|
||||
*
|
||||
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
|
||||
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
|
||||
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
|
||||
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
|
||||
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
|
||||
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
|
||||
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
|
||||
* reads touch. The reads stay off prompt steps all the same. */
|
||||
* z-lab DFlash verify's 16, a plain decode's one. Prompt steps never take the reads: beside the
|
||||
* prefill all-reduces they made a fresh server's first greedy reply differ, the slot-reuse race
|
||||
* that libr4d's full fence on prefill-sized four-rank messages (kArFenceFromElems) also cures. */
|
||||
constexpr int64_t kPrefetchRows = 16;
|
||||
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
|
||||
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
|
||||
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
|
||||
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
|
||||
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
|
||||
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
|
||||
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
|
||||
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
|
||||
/* Where launches chain (rad_chain_on, the core's decision) the read goes on lane 0 itself, right
|
||||
* after the GEMM: its chained form (libr4d r4dchain_prefetch) waits for that GEMM and then reads
|
||||
* beside the collective after it without holding the collective, so there is no join between the
|
||||
* lanes and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1 (on
|
||||
* 4x R9700, the 31B with DFlash2 decoded 6-8% faster than with the read on lane 1). A plain launch
|
||||
* would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane
|
||||
* 0. */
|
||||
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
|
||||
/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card
|
||||
* the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two
|
||||
* servers have queues, and the join puts a queue switch into every decode step. */
|
||||
inline bool prefetch_beside_on() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE");
|
||||
return !(e && e[0] == '0' && e[1] == 0);
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (!op || T > kPrefetchRows) return;
|
||||
if (!op || T > kPrefetchRows || !prefetch_beside_on()) return;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, op, RAD_W(w));
|
||||
return;
|
||||
@@ -622,15 +627,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
|
||||
inline bool prefetch_enabled() {
|
||||
const char* e = std::getenv("RADIANCE_PREFETCH");
|
||||
return !(e && !std::strcmp(e, "0"));
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
|
||||
* otherwise. */
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
@@ -687,6 +686,9 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
float eps = 1e-6f;
|
||||
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
|
||||
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
|
||||
@@ -957,6 +959,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
@@ -1163,6 +1166,16 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -124,7 +124,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
|
||||
@@ -157,6 +157,21 @@ struct AttnGatedFP8 {
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
|
||||
/* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's
|
||||
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
|
||||
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) &&
|
||||
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
|
||||
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
|
||||
kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused;
|
||||
}
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -293,7 +308,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = RAD_OP(b, "attn_paged",
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
@@ -477,6 +492,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
/* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the
|
||||
* projections, prologue, cache store, attention, gate and out projection of the first piece,
|
||||
* then the second's, so the first piece's reduction runs beside all of the second piece's
|
||||
* work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an
|
||||
* attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end --
|
||||
* the first piece's position after its last row, the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim();
|
||||
const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd;
|
||||
const int64_t tpitch = kvb->block_table_pitch;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0;
|
||||
qg.step(c, w.h, w.qg, T, r0, n);
|
||||
kp.step(c, w.h, w.k, T, r0, n);
|
||||
vp.step(c, w.h, w.v, T, r0, n);
|
||||
RAD_ISSUE_N(c, op_q_norm, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm),
|
||||
brow_slice(w.q, r0, n, qw));
|
||||
RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv,
|
||||
brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm),
|
||||
brow_slice(w.k, r0, n, kvw));
|
||||
RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_kv_store, n,
|
||||
brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n,
|
||||
brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? batch->positions + R : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2),
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* Attention-zero rank: zero output, then the reduce and the residual. */
|
||||
|
||||
@@ -130,6 +130,11 @@ struct Dflash2 {
|
||||
/* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
|
||||
/* Also declare the short block's query pass (kShortBlock rows) for --draft-short-from; an
|
||||
* architecture that does not call rad_drafter_short_block leaves it off and its graph as
|
||||
* it was. */
|
||||
int short_block = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
|
||||
@@ -260,6 +265,10 @@ struct Dflash2 {
|
||||
rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {};
|
||||
rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */
|
||||
rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {};
|
||||
/* The short block's (block_lo rows a sequence): the convolutions mask at the block's first row
|
||||
* and the selector strides by it, so each has an op of its own; every other op is per row. */
|
||||
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
|
||||
int64_t block_lo = 0;
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
@@ -287,6 +296,9 @@ struct Dflash2 {
|
||||
static constexpr int64_t kRerankR = 32;
|
||||
int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */
|
||||
rad_op op_hp = 0, op_sel = 0;
|
||||
/* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when
|
||||
* the drafter's own block is longer (rad_drafter_short_block). */
|
||||
static constexpr int64_t kShortBlock = 4;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer,
|
||||
rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix,
|
||||
@@ -695,7 +707,26 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* layers. Planned from those alone, its range would end before the coefficients' begins and
|
||||
* the plan could lay one over the other. Read by the last convolution as well, it is live
|
||||
* wherever the coefficients are. */
|
||||
block_lo = cfg.short_block && cfg.block > kShortBlock ? kShortBlock : 0;
|
||||
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_acb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
op_fconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd),
|
||||
RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group),
|
||||
RAD_INT("NG", NG), RAD_INT("block_size", block_lo),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
if (block_lo && rad_op_reads(b, op_fconv_lo[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL;
|
||||
op_qrope = rope(qrows, g.n_head, w.q);
|
||||
op_krope = rope(qrows, g.n_head_kv, w.k);
|
||||
op_store = rw(b, RAD_OP(b, "kv_store",
|
||||
@@ -909,6 +940,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
if (block_lo)
|
||||
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
|
||||
/* The reads beside the all-reduces, after every weight they read is declared. */
|
||||
if (op_ar && cfg.prefetch > 0)
|
||||
@@ -983,6 +1022,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t NG = cfg.ng(g.n_embd);
|
||||
const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */
|
||||
|
||||
/* The block this pass was staged at: every drafting sequence carries the same number of rows,
|
||||
* the drafter's own block or its short one (rad_drafter_short_block). */
|
||||
const int64_t blk = batch->n_seq > 0 && T % batch->n_seq == 0 ? T / batch->n_seq : 0;
|
||||
const bool lo = block_lo > 0 && blk == block_lo;
|
||||
if (!lo && blk != cfg.block) {
|
||||
rad_step_fail(c, "dflash2: a query pass staged at a block this drafter has no ops for");
|
||||
return;
|
||||
}
|
||||
const rad_op* aconv = lo ? op_aconv_lo : op_aconv;
|
||||
const rad_op* fconv = lo ? op_fconv_lo : op_fconv;
|
||||
|
||||
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);
|
||||
@@ -1005,7 +1055,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
/* ---- attention, wrapped in the two halves of one convolution */
|
||||
norm(op_anorm[i], op_aan[i], w_anorm[i]);
|
||||
RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
@@ -1044,14 +1094,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* replicated norm, so either order gives the same result; reducing first keeps x's
|
||||
* update agreed across ranks. */
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
|
||||
/* ---- the feed-forward, wrapped in the other convolution */
|
||||
norm(op_fnorm[i], op_afn[i], w_fnorm[i]);
|
||||
RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T));
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T),
|
||||
wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T));
|
||||
if (op_gug[i] && T <= gated_rows) {
|
||||
@@ -1068,7 +1118,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref());
|
||||
for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T);
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T),
|
||||
wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T));
|
||||
add_pending = true;
|
||||
}
|
||||
@@ -1107,7 +1157,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
|
||||
@@ -139,6 +139,13 @@ struct GdnFP8 {
|
||||
* trailing add, which would read the delta before the reduction. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
|
||||
* (its piece path), asked by a caller that must know before it commits to a schedule. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
|
||||
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
|
||||
}
|
||||
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
|
||||
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
@@ -389,10 +396,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
|
||||
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
|
||||
* and out projection), so the first piece's reduction runs beside all of the second piece's
|
||||
* work. The second piece reads the history the first left in the convolution slot: a spanned
|
||||
* step is past the prompt's first interval, so its context length is never zero. */
|
||||
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
|
||||
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
|
||||
* work. The second piece reads the history the first left in the convolution slot, so each
|
||||
* piece passes its own context length, its first row's position: the step's would tell the
|
||||
* second piece of a prompt's first chunk that it has none. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t in_w = conv_dim + v_dim;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p * pieces->rows;
|
||||
@@ -405,7 +412,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
|
||||
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE_N(c, op_kkt, n,
|
||||
|
||||
@@ -19,6 +19,15 @@
|
||||
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
|
||||
* image rows are not scaled).
|
||||
*
|
||||
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
|
||||
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
|
||||
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
|
||||
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
|
||||
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
|
||||
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
|
||||
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
|
||||
* element each, read by `clamp`.
|
||||
*
|
||||
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
|
||||
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
|
||||
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
|
||||
@@ -41,8 +50,12 @@ struct Gemma4Vision {
|
||||
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
|
||||
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
|
||||
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
|
||||
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
|
||||
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
|
||||
rad_weight lo[C_N] = {}, hi[C_N] = {};
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false;
|
||||
bool on = false, standardize = false, clip = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
@@ -88,15 +101,14 @@ struct Gemma4Vision {
|
||||
(long long)pool, (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
|
||||
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
|
||||
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
|
||||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
|
||||
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
std::strcmp(act, "gelu_pytorch_tanh")) {
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
|
||||
"a '%s' activation, which it does not serve\n", who, rt, act);
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
|
||||
"activation, which it does not serve\n", who, rt, act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t kk = pool * pool;
|
||||
@@ -154,6 +166,27 @@ struct Gemma4Vision {
|
||||
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
|
||||
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
|
||||
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
if (clip) {
|
||||
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
|
||||
static const char* const proj[Layer::C_N] = {
|
||||
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
|
||||
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
|
||||
"mlp.down_proj" };
|
||||
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
|
||||
false, true, false };
|
||||
for (int k = 0; k < Layer::C_N; ++k) {
|
||||
const char* side = in_side[k] ? "input" : "output";
|
||||
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
|
||||
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
|
||||
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
|
||||
proj[k], side)));
|
||||
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
|
||||
proj[k], side)));
|
||||
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
|
||||
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
|
||||
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
@@ -198,6 +231,11 @@ struct Gemma4Vision {
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
|
||||
@@ -212,6 +250,19 @@ struct Gemma4Vision {
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
for (Layer& l : L) {
|
||||
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
|
||||
* is read by that linear alone, or by what follows it) */
|
||||
if (clip) {
|
||||
using C = Layer;
|
||||
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
|
||||
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
|
||||
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
|
||||
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
|
||||
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
|
||||
{ C::C_DN_OUT, width, b_o } };
|
||||
for (const auto& e : cl)
|
||||
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
|
||||
}
|
||||
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
|
||||
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
@@ -272,10 +323,11 @@ struct Gemma4Vision {
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
|
||||
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
|
||||
(long long)patch, (long long)pool, (long long)pool,
|
||||
standardize ? ", standardised" : "", (long long)P, (long long)R,
|
||||
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
|
||||
(long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
@@ -299,20 +351,33 @@ struct Gemma4Vision {
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
|
||||
/* a clamp of operand `x` in place, when the tower clips */
|
||||
auto cl = [&](const Layer& l, int k, RadOperand x) {
|
||||
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
|
||||
};
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
|
||||
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
|
||||
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
|
||||
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
|
||||
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
cl(l, Layer::C_O_IN, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
|
||||
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
|
||||
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
|
||||
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
|
||||
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
|
||||
brows(b_ff, Pn));
|
||||
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
|
||||
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
}
|
||||
|
||||
@@ -151,7 +151,8 @@ struct GlmKda {
|
||||
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
|
||||
w.forget_low == w.gate_low)
|
||||
return RAD_E_INVAL;
|
||||
// All seven projections are plain BF16 in the pinned checkpoint.
|
||||
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
|
||||
// LinearFP8::declare refuses a quantised one by name.
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
|
||||
@@ -193,9 +194,6 @@ struct GlmKda {
|
||||
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
|
||||
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
|
||||
act(w.core.out), w.out));
|
||||
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
|
||||
!gate_b.bf16 || !output.bf16)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
|
||||
@@ -3,14 +3,23 @@
|
||||
* complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent
|
||||
* for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual.
|
||||
*
|
||||
* Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and
|
||||
* kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are
|
||||
* replicated. */
|
||||
* Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the
|
||||
* rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent
|
||||
* cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead
|
||||
* (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b,
|
||||
* absorption, attention, expansion and the output projection with all 64 heads, then an
|
||||
* all_gather lays the runs out as the whole step. The latent cache and the selection are whole on
|
||||
* every rank already, so the split needs no other exchange. The gather moves half the bytes of
|
||||
* the head form's all-reduce, and the attention loads each key once for all 64 heads of a row.
|
||||
* The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q
|
||||
* unset declares neither them nor the form. */
|
||||
#ifndef RAD_BLOCK_GLM_MLA_H
|
||||
#define RAD_BLOCK_GLM_MLA_H
|
||||
#include "rad_fp8.h"
|
||||
#include "rad_glm_tp.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
@@ -88,11 +97,28 @@ struct MlaLatent {
|
||||
};
|
||||
|
||||
struct GlmMla {
|
||||
/* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every
|
||||
* step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin
|
||||
* chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given
|
||||
* RowsWire buffers. */
|
||||
enum class Form { heads, rows };
|
||||
/* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold
|
||||
* world * rows_for(T) rows, since every rank's run is gathered at full length. */
|
||||
struct RowsWire {
|
||||
rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0;
|
||||
ActFP8 attn{};
|
||||
};
|
||||
struct Wire {
|
||||
ActFP8 input{}, q_low{}, attn{};
|
||||
rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0;
|
||||
MlaLatent::Wire core{};
|
||||
RowsWire rows{};
|
||||
};
|
||||
/* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */
|
||||
static constexpr int64_t kOutRowBytes = 4096 * 2;
|
||||
static int64_t rows_for(int64_t T, int world) {
|
||||
return GlmTp::run_rows(T, world, kOutRowBytes);
|
||||
}
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
@@ -103,6 +129,10 @@ struct GlmMla {
|
||||
MlaLatent core{};
|
||||
rad_weight q_gain = 0, kv_gain = 0;
|
||||
rad_op op_kv_norm = 0, op_store = 0, op_ar = 0;
|
||||
LinearFP8 rows_q_b{}, rows_output{};
|
||||
QuantFP8 rows_quant{};
|
||||
rad_weight rows_kv_b = 0;
|
||||
rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0;
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
const char* prefix, rad_kvgroup group, bool reduce = true,
|
||||
bool defer_finish = false) {
|
||||
@@ -160,7 +190,69 @@ struct GlmMla {
|
||||
GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer),
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out));
|
||||
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL;
|
||||
return reduce ? declare_rows(b, nm, prefix) : RAD_OK;
|
||||
}
|
||||
/* Declared whatever the step size, as every TP split here is: arena levels declare again at a
|
||||
* smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's,
|
||||
* so both share one exchange instance and its scratch. */
|
||||
int declare_rows(RadBuilder* b, Names& nm, const char* prefix) {
|
||||
const auto& r = w.rows;
|
||||
if (!r.q || g.world < 2) return RAD_OK;
|
||||
if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL;
|
||||
const int64_t R = rows_for(g.max_tok, g.world);
|
||||
const auto wg = grp_layer(layer);
|
||||
/* Whole views of the head form's container entries: one stored weight each, whose
|
||||
* encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */
|
||||
rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer);
|
||||
RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536,
|
||||
RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) },
|
||||
w.q_low, r.q, R));
|
||||
rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer),
|
||||
nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16,
|
||||
{ 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg);
|
||||
if (!rows_kv_b) return RAD_E_INVAL;
|
||||
auto project = [&](const char* mode, rad_buf in, rad_buf out) {
|
||||
return rw(b,
|
||||
RAD_OP(b, "mla_project",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64),
|
||||
RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512),
|
||||
RAD_STR("mode", mode), RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(rows_kv_b)),
|
||||
{ in }, { out });
|
||||
};
|
||||
op_rows_absorb = project("absorb", r.q, r.q_latent);
|
||||
op_rows_attn =
|
||||
rw(b,
|
||||
RAD_OP(b, "mla_attn",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512),
|
||||
RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks),
|
||||
RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.q_latent, w.core.selected, w.core.length }, { r.attn_latent });
|
||||
op_rows_expand = project("expand", r.attn_latent, r.attn.x);
|
||||
RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384));
|
||||
rows_output.stored = nm.f("blk.%d.attn_output.weight", layer);
|
||||
RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096,
|
||||
16384, RAD_SHARD_NONE, wg,
|
||||
{ nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out,
|
||||
R));
|
||||
op_rows_gather = rw(b,
|
||||
RAD_OP(b, "all_gather",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", 4096, g.max_tok * 4096),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ r.out }, { w.out });
|
||||
return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK
|
||||
: RAD_E_INVAL;
|
||||
}
|
||||
/* From the TP split threshold, and while the last rank's run is not empty (always at that
|
||||
* threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */
|
||||
bool rows_take(int64_t T) const {
|
||||
return op_rows_gather && GlmTp::splits(T, g.world) &&
|
||||
(g.world - 1) * rows_for(T, g.world) < T;
|
||||
}
|
||||
void prepare(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const auto* kb = kv_batch(batch, kv);
|
||||
@@ -173,17 +265,39 @@ struct GlmMla {
|
||||
kv_a.step(ctx, w.input, w.kv_raw, T);
|
||||
q_norm.step(ctx, T);
|
||||
RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T));
|
||||
q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T);
|
||||
RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T),
|
||||
praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer));
|
||||
}
|
||||
void finish(RadCtx* ctx, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (rows_take(T)) {
|
||||
finish_rows(ctx, T);
|
||||
return;
|
||||
}
|
||||
core.step(ctx, T);
|
||||
attn_quant.step(ctx, T);
|
||||
output.step(ctx, w.attn, w.out, T);
|
||||
if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE);
|
||||
}
|
||||
/* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the
|
||||
* gather sends its unwritten tail rows, which land past T. */
|
||||
void finish_rows(RadCtx* ctx, int64_t T) const {
|
||||
const auto& r = w.rows;
|
||||
const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes);
|
||||
const int64_t first = run.first, n = run.rows;
|
||||
rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0);
|
||||
RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer),
|
||||
brow_slice(w.core.selected, first, n, core.c.blocks),
|
||||
brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n));
|
||||
RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b),
|
||||
brows(r.attn.x, n));
|
||||
rows_quant.step(ctx, n);
|
||||
rows_output.step(ctx, r.attn, r.out, n);
|
||||
RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run),
|
||||
brows(w.out, g.world * run.run));
|
||||
}
|
||||
};
|
||||
}
|
||||
} // namespace rad::arch
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
|
||||
* glm5next.
|
||||
*
|
||||
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
|
||||
* What it computes, per encoder pass (RadBatch::enc):
|
||||
*
|
||||
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
|
||||
* patch row is (channel, frame, y, x), no position
|
||||
|
||||
+20
-27
@@ -365,36 +365,25 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
|
||||
* every block leaves its delta in the activation its norm produced, and the input is dead by
|
||||
* then. */
|
||||
/* ================================================================== the control-vector projection
|
||||
*
|
||||
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
|
||||
* for a request, a steered layer's wide stream is projected off that layer's direction right after
|
||||
* the feed-forward's write:
|
||||
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a
|
||||
* request that takes it, a steered layer's wide stream loses its component along that layer's
|
||||
* direction right after the feed-forward's write:
|
||||
*
|
||||
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
|
||||
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
|
||||
*
|
||||
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
|
||||
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
|
||||
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
|
||||
* This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as
|
||||
* llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone.
|
||||
*
|
||||
* Two properties the architecture plugin does not have to think about, both here:
|
||||
* The switch is per request: `on` is a derived buffer of one int32 per row
|
||||
* (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation
|
||||
* with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero
|
||||
* row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm
|
||||
* the file stored for the layer times the package's own scale.
|
||||
*
|
||||
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
|
||||
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
|
||||
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
|
||||
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
|
||||
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
|
||||
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
|
||||
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
|
||||
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
|
||||
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
|
||||
* the table at issue, so nothing is configured per deployment or scanned per layer.
|
||||
*
|
||||
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
|
||||
* deployment without a vector declares no op, no buffer and no branch in the step. */
|
||||
* One instance per layer; `declare` emits an op only where the vector steers, so a deployment
|
||||
* without a vector declares no op and no buffer. */
|
||||
struct HcProject {
|
||||
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
|
||||
const float* dir = nullptr; /* this layer's row of the device direction table */
|
||||
@@ -456,9 +445,10 @@ struct HcProject {
|
||||
}
|
||||
|
||||
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
|
||||
* call per piece, in the same place in the graph. */
|
||||
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
|
||||
if (!op) return;
|
||||
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
|
||||
* takes the vector (RadBatch::control_vector): every row would be skipped. */
|
||||
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
|
||||
if (!op || !batch || !batch->control_vector) return;
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brow_slice(h, r0, rows, hc * n),
|
||||
praw(dir, RAD_F32, n),
|
||||
@@ -466,6 +456,9 @@ struct HcProject {
|
||||
}
|
||||
};
|
||||
|
||||
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
|
||||
* every block leaves its delta in the activation its norm produced, and the input is dead by
|
||||
* then. */
|
||||
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (!op_write) return;
|
||||
if (takes_gather(T)) {
|
||||
|
||||
@@ -75,6 +75,20 @@ struct MlpFP8 {
|
||||
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
|
||||
* pipelined prefill puts both on the second lane): the projections from the normed input to
|
||||
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
|
||||
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
|
||||
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
|
||||
* (a caller that runs it beside other work). */
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
@@ -129,6 +143,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
|
||||
* it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
@@ -149,6 +174,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
body(c, T, r0, rows);
|
||||
tail(c, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
@@ -160,6 +190,9 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
#include "rad_block_hc.h"
|
||||
#include "rad_block_moe_fp8.h"
|
||||
#include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */
|
||||
#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */
|
||||
#include "rad_qsa.h"
|
||||
#include "rad_block_vit.h"
|
||||
|
||||
@@ -108,6 +109,9 @@ struct MtpHcBlock {
|
||||
/* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value)
|
||||
* pairs stored as f32, this rank's top-R and the all-gathered world * R. */
|
||||
rad_buf dpair = 0, dgath = 0;
|
||||
/* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across
|
||||
* the serial passes (round 1 resets the logical stream, not the plane). */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
AttnGatedFP8::Wire attn{};
|
||||
MoeFP8::Wire mlp{};
|
||||
QsaIndexer::Wire qsa{};
|
||||
@@ -158,6 +162,9 @@ struct MtpHcBlock {
|
||||
rad_op op_dsel = 0, op_dback = 0;
|
||||
rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0;
|
||||
rad_op op_dgather = 0, op_dmerge = 0;
|
||||
/* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round
|
||||
* cannot be an operand and each gets its own declared op. */
|
||||
rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {};
|
||||
|
||||
/* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair
|
||||
* planes. */
|
||||
@@ -422,6 +429,25 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
if (!op_dgather || !op_dmerge) return RAD_E_INVAL;
|
||||
}
|
||||
if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL;
|
||||
/* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist
|
||||
* whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads
|
||||
* column 0 as a parent index. The engine refuses other drafters; this check keeps a
|
||||
* mismatched declaration from writing tokens into a tree plane. */
|
||||
if (w.couple_draws || w.couple_state) {
|
||||
if (!w.couple_draws || !w.couple_state || depth < 1 ||
|
||||
depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
for (int round = 1; round <= depth; ++round) {
|
||||
op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose",
|
||||
/* The whole vocabulary: `row_topk` reports global ids and the merge keeps
|
||||
* them, while `g.n_vocab` is this rank's shard. */
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("round", round), RAD_INT("max_rounds", depth)),
|
||||
RAD_NOWEIGHTS),
|
||||
{ w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state });
|
||||
if (!op_couple[round - 1]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Keep the carry `hin` live through the head's last op: it is written before the mixer and
|
||||
* lm_head run, and the planner could otherwise give its bytes to them (silently lowering
|
||||
@@ -429,6 +455,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
{
|
||||
rad_op last = op_logits;
|
||||
if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk;
|
||||
if (op_couple[0]) last = op_couple[depth - 1];
|
||||
if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -524,6 +551,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L),
|
||||
brows(w.didx, L), brows(w.dval, L), RAD_NONE);
|
||||
}
|
||||
/* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row
|
||||
* replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their
|
||||
* own passes. */
|
||||
if (op_couple[0]) {
|
||||
const int round = r < 0 ? 1 : r;
|
||||
if (round < 1 || round > depth) {
|
||||
rad_step_fail(c, "MTP coupled round exceeds the declared draft depth");
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L),
|
||||
praw(batch->seq_ids, RAD_I32, batch->n_seq),
|
||||
brows(w.couple_draws, L), RAD_B(w.couple_state));
|
||||
}
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+67
-16
@@ -296,6 +296,10 @@ struct ArPieces {
|
||||
* chunk a span of 1 makes, the state carried through the cache) and hand off the first
|
||||
* piece's reduction before the second piece's projection. Null for any other step. */
|
||||
const int32_t* cu = nullptr;
|
||||
/* The caller normed each piece's input itself (qwen35_fp8's pipelined prefill, on the second
|
||||
* lane behind the previous block's piece), so a block with its own norm takes the piece path
|
||||
* as one with an external input does and skips that norm. */
|
||||
bool in_ready = false;
|
||||
bool cuts(int64_t T) const { return done && rows > 0 && T > rows; }
|
||||
void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; }
|
||||
};
|
||||
@@ -395,6 +399,9 @@ struct NormQuantFP8 {
|
||||
}
|
||||
/* Asked by the preceding block before issuing its own collective. */
|
||||
bool takes_ar(int64_t T) const { return pick(T) != op; }
|
||||
/* The plain op whatever the wire, for a caller that issued the preceding all-reduce itself
|
||||
* (qwen35_fp8's pipelined prefill, which runs it narrow beside compute). */
|
||||
void step_plain(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
|
||||
};
|
||||
|
||||
inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x,
|
||||
@@ -472,6 +479,16 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* step() below with the plain op, whatever the wire. */
|
||||
inline void NormQuantFP8::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(a.q, r0, rows, n),
|
||||
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
}
|
||||
|
||||
/* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals
|
||||
* `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in
|
||||
* the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a
|
||||
@@ -755,6 +772,10 @@ struct LinearFP8 {
|
||||
* this is set; otherwise the linear reads unwritten arena bytes. */
|
||||
bool reads_x = false;
|
||||
bool mapped = false; /* probe() made the name map; declare() does not make it again */
|
||||
/* The stored weight this linear's views take when it is not `<base>.weight`: a second linear
|
||||
* over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set
|
||||
* before declare(); no name map is made, and only block fp8 is served this way. */
|
||||
const char* stored = nullptr;
|
||||
/* The weight's access class (rad_builder.h): read every pass by default; a linear run once a
|
||||
* request (an encoder's) says so, which lets placement keep it off the card. Set before
|
||||
* declare(). */
|
||||
@@ -808,8 +829,10 @@ struct LinearFP8 {
|
||||
rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc,
|
||||
int64_t K,
|
||||
RadWeightGroup grp);
|
||||
/* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when
|
||||
* that is set: a rank's run of a step's rows written to a buffer sized for the run. */
|
||||
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
|
||||
int64_t rows = 0) const;
|
||||
int64_t rows = 0, int64_t y0 = -1) const;
|
||||
/* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane
|
||||
* gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and
|
||||
* total must be whole scale blocks. */
|
||||
@@ -1047,9 +1070,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
|
||||
/* Name map first: the weight's encoding, looked up through it, picks the branch below. */
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sw = stored ? stored : wn;
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
const bool known = weight_enc(b, sw, &enc);
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
|
||||
@@ -1059,11 +1083,17 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* constraints. */
|
||||
bf16 = g.w_bf16 || plain;
|
||||
if (bf16) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (known && !plain) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a "
|
||||
"bf16 container is served bf16 throughout\n", wn, en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, but this linear runs as a plain bf16 GEMM "
|
||||
"(a bf16 model, or a block that keeps its linears bf16); the "
|
||||
"container must store it bf16\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
/* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not
|
||||
@@ -1097,6 +1127,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const bool rot8 = known && linear_is_w8h(enc);
|
||||
i8 = known && (linear_is_w8(enc) || rot8);
|
||||
if (i8) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Upstream's rot guard: fed codes must match the weight's rotation form. */
|
||||
if (a.q8_fed && rot8 != a.q8_rot) {
|
||||
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
|
||||
@@ -1161,6 +1196,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* codes, and (scale, zero) as `b_scale`. */
|
||||
paro5 = known && linear_is_paro_w5(enc);
|
||||
if (paro5) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's "
|
||||
@@ -1227,6 +1267,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* whole 128s, the scale group. */
|
||||
w4 = known && linear_is_w4(enc);
|
||||
if (w4) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, "
|
||||
"and its input has none\n", wn);
|
||||
@@ -1297,6 +1342,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
paro = known && linear_is_paro_mxfp4(enc);
|
||||
mx = known && (linear_is_mxfp4(enc) || paro);
|
||||
if (mx) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (paro) {
|
||||
/* The rotation is applied to the activation, so this linear needs the input's bf16
|
||||
* plane (probe() set reads_x) and quantises it itself. */
|
||||
@@ -1408,10 +1458,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
|
||||
/* One stored weight, two operands: the codes and scale plane of `<base>.weight`, block fp8 in
|
||||
* the checkpoint or made so by rad-convert's recipe. */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
|
||||
w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K },
|
||||
access, shard, grp, rp.w, rp.n);
|
||||
ws_row_div = RAD_FP8_BLOCK;
|
||||
ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16,
|
||||
ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16,
|
||||
{ fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
/* An uneven slice; the scale plane takes the same slice in blocks. */
|
||||
@@ -1443,10 +1493,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks
|
||||
* the operand count against the schema (core/runtime/issue.cpp). */
|
||||
inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0,
|
||||
int64_t rows) const {
|
||||
int64_t rows, int64_t y0) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
const int64_t yr = y0 < 0 ? r0 : y0;
|
||||
if (bf16) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N));
|
||||
return;
|
||||
}
|
||||
if (i8) {
|
||||
@@ -1455,7 +1506,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
/* The 4-bit weight's copies of the input start at their buffers' first row: they live only
|
||||
@@ -1465,13 +1516,13 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K),
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (w4) {
|
||||
RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5 && rot_split && rows > rot_split) {
|
||||
@@ -1480,14 +1531,14 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K),
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5) {
|
||||
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs),
|
||||
RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE,
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (mx) {
|
||||
@@ -1501,12 +1552,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak),
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
|
||||
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================== an fp8 weight with no op of its own
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
* 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.
|
||||
* each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter:
|
||||
* false, all five layers sliding) sets the sliding layers' causality.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
@@ -115,18 +116,15 @@ inline double embed_scale(int64_t hidden) {
|
||||
/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes
|
||||
* into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0
|
||||
* as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's
|
||||
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With
|
||||
* the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose;
|
||||
* 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */
|
||||
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB: on 4x
|
||||
* R9700 with the reads on lane 0, 16 and 24 MB decoded 1-2% slower and 12 MB about 6%. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)20 << 20;
|
||||
|
||||
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It
|
||||
* took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply
|
||||
* identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14
|
||||
* and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the
|
||||
* feed-forward reduction, slower than either alone. The reads beside a reduction are one queue,
|
||||
* and a longer one beside the attention pushes gate_up's read past the reduction it should hide
|
||||
* in. */
|
||||
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention, in
|
||||
* place of a read of o_proj there (about 3.5% faster on the 31B at tp 4 on 4x R9700; 10-20 MB of
|
||||
* down_proj were slower, as were two reads beside one reduction). The reads beside a reduction
|
||||
* are one queue, and a longer one beside the attention pushes gate_up's read past the reduction
|
||||
* it should hide in. */
|
||||
constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20;
|
||||
|
||||
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
|
||||
@@ -166,8 +164,8 @@ inline long long dflash_block(const RadModelMeta* meta) {
|
||||
|
||||
/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
|
||||
* the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the
|
||||
* container carries one and `out` now names its depth. Chained launches measured a gain with it
|
||||
* (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them
|
||||
* container carries one and `out` names its depth. Chained launches pay with it (the 26B-A4B's
|
||||
* speculative step is 1% faster on 4x R9700), so the probe asks for them
|
||||
* (RadArchProbe::chain_pays). */
|
||||
inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 1) return false;
|
||||
@@ -181,8 +179,8 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
/* 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). Chained launches measured a gain with it (the
|
||||
* 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches pay with it (the 31B's
|
||||
* speculative step is 13% faster on 4x R9700), so the probe asks for them. */
|
||||
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 2) return false;
|
||||
const long long bs = dflash_block(meta);
|
||||
@@ -238,6 +236,7 @@ struct Dflash1 {
|
||||
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 causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */
|
||||
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 kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */
|
||||
@@ -519,7 +518,12 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t q : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) {
|
||||
fprintf(stderr, "radiance: '%s' has a %lld-row part per rank; an int8 weight takes at "
|
||||
"most %d parts, each a multiple of 16 rows.\n", base, (long long)q,
|
||||
(int)RAD_MAX_ROW_PARTS);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np);
|
||||
@@ -582,7 +586,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dc.block = trained;
|
||||
if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED;
|
||||
if (dg.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash drafter has %lld layers; this block carries "
|
||||
"at most %d\n", (long long)dg.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
{
|
||||
std::vector<int> full;
|
||||
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
|
||||
@@ -610,6 +618,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
"window\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's
|
||||
* (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer
|
||||
* sliding and non-causal over its window. */
|
||||
dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal",
|
||||
rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (!head_sharded(dg) && dg.world > 1) {
|
||||
@@ -664,11 +677,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
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 "
|
||||
"sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld "
|
||||
"tokens; the head is %s, argmax %s",
|
||||
(long long)dg.n_layer, t.base_layer, t.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_layer - nfull), (long long)dc.window,
|
||||
dc.causal ? "causal" : "non-causal", (long long)dg.n_head,
|
||||
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff,
|
||||
(long long)t.n_taps,
|
||||
df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)",
|
||||
@@ -849,7 +863,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
};
|
||||
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_swa) op_attn_swa = attn(cfg.causal, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* row-interleaved all_gather, bit for bit the replicated projection
|
||||
*
|
||||
* The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered
|
||||
* row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside
|
||||
* its page tables, so its runs are multiples of four rows. The last rank's run may be short, or
|
||||
* lie wholly past a small step (`run_of`). */
|
||||
* row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs
|
||||
* are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its
|
||||
* runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small
|
||||
* step (`run_of`). */
|
||||
#ifndef RAD_GLM_TP_H
|
||||
#define RAD_GLM_TP_H
|
||||
#include "rad_arch.h"
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* rad_resample.h -- fp32 bicubic resampling reproducing torch's
|
||||
* F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel,
|
||||
* operation for operation, for the Unlimited-OCR DeepEncoder's position tables.
|
||||
*
|
||||
* The reference resamples two fixed tables (deepencoder.py):
|
||||
* get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and
|
||||
* interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid,
|
||||
* interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C]
|
||||
* with C innermost and each of the C channels is interpolated over the (h, w) grid
|
||||
* independently; the cls split/catenation is the caller's job.
|
||||
*
|
||||
* The float32 antialias path (upsample_bicubic2d_aa_kernel_impl ->
|
||||
* upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true,
|
||||
* aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for
|
||||
* operation, scalar_t = float:
|
||||
* per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale =
|
||||
* 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1;
|
||||
* the output-pixel centre center = scale * (i + 0.5f);
|
||||
* the taps run over xmin = max((int64)(center - support + 0.5), 0) ..
|
||||
* min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative
|
||||
* start truncates toward zero before the clamp to 0; border taps are simply absent,
|
||||
* the row normalization below absorbs the lost mass;
|
||||
* each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic
|
||||
* with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the
|
||||
* -0.75 OpenCV-compatible one belongs to the non-antialias path);
|
||||
* the axis weights are normalized by their float running sum total_w, exactly as
|
||||
* _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w;
|
||||
* the resize is separable: the width pass over every input row first, then the height
|
||||
* pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap
|
||||
* accumulating acc = (float)(acc + w * v) in float.
|
||||
* Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10,
|
||||
* 16x20->10x13, and both checkpoint tables).
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef RAD_RESAMPLE_H
|
||||
#define RAD_RESAMPLE_H
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
namespace resample_detail {
|
||||
|
||||
/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75
|
||||
* OpenCV-compatible kernel belongs to the non-antialias path), in float. */
|
||||
inline float cubic_aa(float x) {
|
||||
const float ax = std::fabs(x);
|
||||
if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f;
|
||||
if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
struct Axis {
|
||||
int n = 0; /* tap slots per output pixel (max_interp_size) */
|
||||
std::vector<int32_t> size; /* [out] taps this output pixel reads */
|
||||
std::vector<int32_t> idx; /* [out*n] input index per tap (xmin + j) */
|
||||
std::vector<float> w; /* [out*n] weights, normalized by the tap sum */
|
||||
};
|
||||
|
||||
/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */
|
||||
inline Axis make_axis(int in, int out) {
|
||||
Axis a;
|
||||
const float scale = (float)((double)in / (double)out);
|
||||
const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f;
|
||||
const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f;
|
||||
a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */
|
||||
a.size.resize((size_t)out, 0);
|
||||
a.idx.assign((size_t)out * (size_t)a.n, 0);
|
||||
a.w.assign((size_t)out * (size_t)a.n, 0.0f);
|
||||
for (int i = 0; i < out; ++i) {
|
||||
const float c = ((float)i + 0.5f) * scale;
|
||||
int xmin = (int)(c - support + 0.5f);
|
||||
if (xmin < 0) xmin = 0;
|
||||
int xsize = (int)(c + support + 0.5f);
|
||||
if (xsize > in) xsize = in;
|
||||
xsize -= xmin;
|
||||
if (xsize < 0) xsize = 0;
|
||||
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
|
||||
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
|
||||
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
|
||||
* clamp is a no-op safety net, never a silent tap truncation. */
|
||||
if (xsize > a.n) xsize = a.n;
|
||||
int* idx = &a.idx[(size_t)i * (size_t)a.n];
|
||||
float* w = &a.w[(size_t)i * (size_t)a.n];
|
||||
float total = 0.0f;
|
||||
for (int j = 0; j < xsize; ++j) {
|
||||
w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale);
|
||||
idx[j] = xmin + j;
|
||||
total = (float)(total + w[j]);
|
||||
}
|
||||
a.size[i] = xsize;
|
||||
if (total != 0.0f)
|
||||
for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step
|
||||
* `tap_stride` floats along the resized axis, and outputs land at
|
||||
* dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation
|
||||
* follow ATen's separable 1D resize. */
|
||||
inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride,
|
||||
float* dst, int64_t dst_row_stride, int64_t out_stride, int rows,
|
||||
const Axis& ax, int out_n, int channels) {
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const float* srow = src + (size_t)r * (size_t)src_row_stride;
|
||||
float* drow = dst + (size_t)r * (size_t)dst_row_stride;
|
||||
for (int i = 0; i < out_n; ++i) {
|
||||
const int n = ax.size[i];
|
||||
const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n];
|
||||
const float* w = &ax.w[(size_t)i * (size_t)ax.n];
|
||||
for (int c = 0; c < channels; ++c) {
|
||||
if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; }
|
||||
float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]);
|
||||
for (int j = 1; j < n; ++j)
|
||||
acc = (float)(acc +
|
||||
srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]);
|
||||
drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace resample_detail
|
||||
|
||||
/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to
|
||||
* [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass
|
||||
* over every input row, then the height pass. Runs once at load. */
|
||||
inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w,
|
||||
int channels, float* dst) {
|
||||
if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0)
|
||||
return;
|
||||
if (in_h == out_h && in_w == out_w) {
|
||||
std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float));
|
||||
return;
|
||||
}
|
||||
const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h);
|
||||
const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w);
|
||||
const float* work = src;
|
||||
int work_w = in_w;
|
||||
std::vector<float> wide;
|
||||
if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */
|
||||
wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f);
|
||||
resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(),
|
||||
(int64_t)out_w * channels, channels, in_h, ax, out_w,
|
||||
channels);
|
||||
work = wide.data();
|
||||
work_w = out_w;
|
||||
}
|
||||
if (in_h == out_h) {
|
||||
if (work != dst)
|
||||
std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float));
|
||||
return;
|
||||
}
|
||||
/* height pass over the widened rows: one scan per output-width column */
|
||||
resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels,
|
||||
(int64_t)out_w * channels, work_w, ay, out_h, channels);
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif // RAD_RESAMPLE_H
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(fishomni LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp)
|
||||
File diff suppressed because it is too large.
Load diff
+448
-14
@@ -22,6 +22,7 @@
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cmath>
|
||||
@@ -94,7 +95,18 @@ struct G3Linear {
|
||||
bool i8g = false;
|
||||
bool mx = false;
|
||||
bool a4 = false; /* asymmetric int4 over the per-(row, 128) int8 activation */
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
int64_t a4_split = 0;
|
||||
rad_buf a16 = 0;
|
||||
rad_op op_a16 = 0, op_dec = 0;
|
||||
bool shared_in = false;
|
||||
/* Set before declare: an E4M3 (MXFP4) linear's input pair given by the caller (the pipelined
|
||||
* prefill's one pair for every block) instead of one of its own. It keeps its own quantiser
|
||||
* into it, so a step that does not write the pair by a fused junction still fills it. */
|
||||
rad_buf q8_into = 0, s8_into = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src,
|
||||
@@ -104,6 +116,9 @@ struct G3Linear {
|
||||
const G3Linear* in_from = nullptr);
|
||||
void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const;
|
||||
void gemm(RadCtx* c, rad_buf y, int64_t T) const;
|
||||
/* The same over rows [r0, r0 + n) of an E4M3 (MXFP4) linear, for the pipelined prefill. */
|
||||
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;
|
||||
};
|
||||
|
||||
inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
@@ -198,7 +213,8 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (in_from && (in_from->i8g || in_from->a4) && in_from->q8 && in_from->K == K) {
|
||||
/* not an a4 linear's pair: below its decode band it writes none */
|
||||
if (in_from && in_from->i8g && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
@@ -218,7 +234,21 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a8i8_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op) return RAD_E_INVAL;
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
return (op_a16 && op_dec) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (i8g || mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
@@ -239,13 +269,13 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
}
|
||||
if (in_from && in_from->mx == mx && (in_from->i8g || in_from->a4) == i8g && in_from->q8 && in_from->K == K) {
|
||||
if (in_from && in_from->mx == mx && in_from->i8g == i8g && !in_from->a4 && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
q8 = mx && q8_into ? q8_into : decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = mx && s8_into ? s8_into : decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, mx ? "quant_act_fp8" : "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
@@ -281,6 +311,10 @@ inline void G3Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
} else if (i8g || mx || a4) {
|
||||
/* quant_act_i8g / quant_act_fp8 take x, q, scale: no optional `asum`. */
|
||||
if (!shared_in)
|
||||
@@ -295,6 +329,24 @@ inline void G3Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
brows(y, T), RAD_NONE, mx ? RAD_W(wref) : RAD_NONE);
|
||||
}
|
||||
|
||||
inline void G3Linear::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, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, n, N), RAD_NONE, RAD_W(wref));
|
||||
}
|
||||
|
||||
inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (a4 && n <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n));
|
||||
RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
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, K / RAD_FP8_BLOCK));
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
|
||||
/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input,
|
||||
* summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set,
|
||||
* for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's
|
||||
@@ -343,6 +395,12 @@ struct Gemma3Attn {
|
||||
/* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */
|
||||
G3Tap tap_in{}, tap_o{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a
|
||||
* launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every
|
||||
* block (the junctions write it a piece at a time on the second lane). */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, double scale);
|
||||
@@ -352,6 +410,17 @@ struct Gemma3Attn {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces,
|
||||
* its input pair already written; hands the first piece behind its out projection. */
|
||||
void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const;
|
||||
/* The tail a piece at a time on the second lane: the overlap all-reduce and the post-norm. */
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
@@ -359,6 +428,7 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire; attn_scale = scale;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_q.q8_into = pipe_in->q8; ln_q.s8_into = pipe_in->s8; }
|
||||
|
||||
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)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l)));
|
||||
@@ -460,6 +530,13 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
@@ -474,6 +551,49 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Each piece is the chunk a span of 1 makes: its rows, positions and slots, and an attention over
|
||||
* its own query bounds (ArPieces::cu) seeing the cache up to its own end -- `used0`, the group's
|
||||
* seqused less the second piece's rows, for the first; the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would (the sliding window included:
|
||||
* a window group's seqused counts from its rebased first block). */
|
||||
void Gemma3Attn::step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc,
|
||||
const int32_t* used0) 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, R = pc->rows;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = batch->positions + r0;
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
ln_k.gemm_rows(c, w.k, r0, n);
|
||||
ln_v.gemm_rows(c, w.v, r0, n);
|
||||
if (op_qnr) {
|
||||
RAD_ISSUE_N(c, op_qnr, n, brow_slice(w.q, r0, n, qd), brow_slice(w.k, r0, n, kvd),
|
||||
brow_slice(w.v, r0, n, kvd), praw(pos, RAD_I32, n), RAD_W(w_qn), RAD_W(w_kn));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_qn, n * cls.n_head, brow_slice(w.q, r0, n, qd), RAD_W(w_qn),
|
||||
brow_slice(w.q, r0, n, qd));
|
||||
RAD_ISSUE_N(c, op_kn, n * cls.n_head_kv, brow_slice(w.k, r0, n, kvd), RAD_W(w_kn),
|
||||
brow_slice(w.k, r0, n, kvd));
|
||||
RAD_ISSUE_N(c, op_rq, n, brow_slice(w.q, r0, n, qd), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rk, n, brow_slice(w.k, r0, n, kvd), praw(pos, RAD_I32, n));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_kv, n, brow_slice(w.k, r0, n, kvd), brow_slice(w.v, r0, n, kvd),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? used0 : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pc->cu + p, RAD_I32, 2), brows(w.attn, T));
|
||||
ln_o.step_rows(c, w.attn, w.h, r0, n);
|
||||
if (p == 0) pc->hand(r0, n);
|
||||
}
|
||||
}
|
||||
|
||||
void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
@@ -538,6 +658,10 @@ struct Gemma3Mlp {
|
||||
/* Calibration: gate|up's input and down's (this rank's columns). */
|
||||
G3Tap tap_gu{}, tap_dn{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment, as Gemma3Attn's. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire);
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
@@ -545,11 +669,30 @@ struct Gemma3Mlp {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up
|
||||
* to the down projection; then the tail a piece at a time on the second lane. */
|
||||
void body_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
ln_gu.gemm_rows(c, w.gu, r0, n);
|
||||
RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * g.n_ff), brow_slice(w.ffn, r0, n, g.n_ff));
|
||||
ln_down.step_rows(c, w.ffn, w.h, r0, n);
|
||||
}
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
void add_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, g.n_embd), brow_slice(w.h, r0, n, g.n_embd),
|
||||
brow_slice(w.x, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire) {
|
||||
g = geom; layer = l; w = wire;
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_gu.q8_into = pipe_in->q8; ln_gu.s8_into = pipe_in->s8; }
|
||||
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
@@ -589,6 +732,13 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -651,7 +801,7 @@ struct G3Junction {
|
||||
const rad_buf wr[3] = { q8, s8, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
|
||||
@@ -678,8 +828,11 @@ struct G3Junction {
|
||||
* embedding stream. */
|
||||
struct G3JunctionFP8 {
|
||||
rad_op op = 0;
|
||||
/* At two ranks on the exact wire: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. */
|
||||
/* At two ranks: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. The kernel
|
||||
* sends the exact wire only, so under --tp-wire it is declared all the same and taken by the
|
||||
* steps whose message goes out exact anyway (ar_wire_is_exact: a decode step of a few rows,
|
||||
* under --tp-wire-min-kb); a wider step keeps the lossy all-reduce, unfused. */
|
||||
rad_op op_ar = 0;
|
||||
rad_buf x = 0, res = 0, q = 0, s = 0;
|
||||
rad_weight w = 0, wp = 0;
|
||||
@@ -700,7 +853,7 @@ struct G3JunctionFP8 {
|
||||
const rad_buf wr[3] = { q, s, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && wp && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
if (res && wp && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
const rad_weight ws[2] = { w, wp };
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("world_size", g.world),
|
||||
@@ -723,6 +876,12 @@ struct G3JunctionFP8 {
|
||||
RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w),
|
||||
brows(q, T), brows(s, T), RAD_NONE);
|
||||
}
|
||||
/* Rows [r0, r0 + n), without the all-reduce: the pipelined prefill's second lane. */
|
||||
void step_rows(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(x, r0, rows, n), res ? brow_slice(res, r0, rows, n) : RAD_NONE,
|
||||
RAD_W(w), brow_slice(q, r0, rows, n), brow_slice(s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
@@ -773,10 +932,31 @@ struct Model {
|
||||
bool calib = false, tap_live = false;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
long long calib_rows = 0;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the input pair every
|
||||
* block's q|k|v and gate|up read (the junctions write it); the bounds buffer and its pinned
|
||||
* table of {0, pipe_rows(T), T}; whether rank 0 has said it pipelines, or why not. */
|
||||
bool pipe_on = false;
|
||||
G3Linear pipe_in{};
|
||||
rad_buf b_pipe_cu = 0;
|
||||
/* Each KV group's seqused for the first piece, [2] (sliding, global): the step's less the
|
||||
* second piece's rows (sub_i32 from b_pipe_cu[3] = T - R). A window group's seqused counts from
|
||||
* its rebased first block, not from position 0, so the first piece's position cannot stand in. */
|
||||
rad_buf b_pipe_used = 0;
|
||||
rad_op op_pipe_used = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows (qwen35_fp8 says why). */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
|
||||
/* ================================================================== the DFlash2 drafter
|
||||
*
|
||||
* A second model at absolute layers n_layer.. with its own KV group (rad_block_dflash2.h), as
|
||||
@@ -793,6 +973,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma3 DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -904,6 +1085,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d.., %lld heads / %lld kv x %lld, ffn %lld, "
|
||||
"%s attention with a %lld-token window, %d trunk taps, embedding x %g, %s head",
|
||||
(long long)dg.n_layer, base_layer, (long long)dg.n_head, (long long)dg.n_head_kv,
|
||||
@@ -917,6 +1099,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -1034,6 +1217,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("mult", emult)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The second lane's window (rad_lane1_window_begin): from the embedding's reduction to the final
|
||||
* norm, where the pipelined prefill runs its boundaries; the drafter and the heads lie outside it
|
||||
* and can share the concurrent buffers' bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -1042,6 +1229,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough, on
|
||||
* an MXFP4 trunk with fused junctions (decided below); two ranks only, as in qwen35_fp8. Its
|
||||
* second lane touches the stream, the branch output, the shared input pair and the bounds, so
|
||||
* those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the first lane,
|
||||
* pipe_taps). The pair is one for every block so that this costs one pair, not one a
|
||||
* linear. */
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows && !calib_dir();
|
||||
if (m.pipe_on) {
|
||||
m.pipe_in.mx = true;
|
||||
m.pipe_in.K = g.n_embd;
|
||||
m.pipe_in.q8 = decl_b(b, nm.f("pipe_in.q8"), RAD_F8E4M3, {g.max_tok, g.n_embd});
|
||||
m.pipe_in.s8 = decl_b(b, nm.f("pipe_in.s8"), RAD_F32, {g.max_tok, g.n_embd / RAD_FP8_BLOCK});
|
||||
if (!m.pipe_in.q8 || !m.pipe_in.s8) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
Gemma3Attn::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
|
||||
Gemma3Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
|
||||
|
||||
@@ -1052,6 +1254,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
if (m.pipe_on) {
|
||||
lay.attn.ar_overlap = lay.mlp.ar_overlap = 1;
|
||||
lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in;
|
||||
}
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw));
|
||||
}
|
||||
@@ -1119,6 +1325,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
m.fuse_mx_ar = ar;
|
||||
}
|
||||
/* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */
|
||||
if (m.pipe_on) {
|
||||
bool ok = m.fuse_mx;
|
||||
/* ... and the pieces' row-sliced linears are the E4M3 (MXFP4) path throughout. */
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.op_ar_ov && lay.mlp.op_ar_ov && lay.attn.ln_o.mx && lay.mlp.ln_down.mx;
|
||||
if (!ok)
|
||||
rad_note(b, "the pipelined prefill is off: it needs an MXFP4 trunk with the fused fp8 "
|
||||
"junctions and an overlap all-reduce for every block");
|
||||
m.pipe_on = ok;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.q8));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.s8));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
m.b_pipe_used = decl_b(b, nm.f("pipe_used"), RAD_I32, {2});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_used));
|
||||
m.op_pipe_used = rad_op_declared(b, "sub_i32")
|
||||
? RAD_OP(b, "sub_i32", RAD_PARAMS(RAD_RANGE("M", 1, 1)), RAD_NOWEIGHTS) : 0;
|
||||
if (m.op_pipe_used) {
|
||||
const rad_buf rd[1] = { m.b_pipe_cu };
|
||||
const rad_buf wr[1] = { m.b_pipe_used };
|
||||
rad_op_reads (b, m.op_pipe_used, rd, 1);
|
||||
rad_op_writes(b, m.op_pipe_used, wr, 1);
|
||||
} else {
|
||||
m.pipe_on = false; /* no way to put the first piece's seqused on the card */
|
||||
rad_note(b, "the pipelined prefill is off: no plugin serves sub_i32");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions
|
||||
* never write, so under it none is declared (above): any container calibrates, unfused. */
|
||||
@@ -1154,6 +1392,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out)),
|
||||
{m.b_x}, {m.b_h});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -1180,6 +1419,191 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* qwen35_fp8's step_pipelined on Gemma 3's trunk: at two ranks every layer of a prefill chunk makes
|
||||
* two all-reduces, each in a hard chain behind its block (all-reduce, post-norm, the junction's add
|
||||
* and next norm, then the next block). A step of one prefill sequence of at least kPipeMinRows tokens
|
||||
* is cut into two pieces of about half; every block runs a piece at a time on the first lane, and
|
||||
* the work between two blocks -- the block's all-reduce at `overlap` 1, its post-norm and the fp8
|
||||
* junction, and after the last block its add and the final norm -- runs a
|
||||
* piece at a time on the second; the drafter taps run on the first (pipe_taps). The ops are the serial step's at a narrower width, so a pipelined
|
||||
* step is bit for bit the serial one where a chunk's rows do not depend on its width.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold as in qwen35_fp8: every collective of the step
|
||||
* is on it, the embedding's included; none carries a device-wide arrival counter; the buffers it
|
||||
* touches left the sharing pool at declare, the per-linear input pairs replaced by one shared pair. */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the attention of layer l, 2l + 1 its feed-forward), rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
const bool last = li + 1 == (int64_t)m.layers.size();
|
||||
if (s % 2 == 0) {
|
||||
l.attn.ar_rows(c, r0, n);
|
||||
l.attn.post_rows(c, r0, n);
|
||||
l.jf_am.step_rows(c, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.ar_rows(c, r0, n);
|
||||
l.mlp.post_rows(c, r0, n);
|
||||
if (!last) l.jf_ma.step_rows(c, r0, n);
|
||||
else l.mlp.add_rows(c, r0, n);
|
||||
if (last)
|
||||
RAD_ISSUE_N(c, m.op_final, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out),
|
||||
brow_slice(m.b_h, r0, n, g.n_embd));
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its junction is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* An attention block's first piece is done (ArPieces): lane 0 takes the previous block's second
|
||||
* boundary before the second piece (and the previous layer's second-piece taps behind it), and
|
||||
* lane 1 this block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t s = 0;
|
||||
int64_t T = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed (a rank-local
|
||||
* failure past the batch's own conditions: the other rank would pipeline). */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions || batch->rope_pos) return serial("no one-component positions");
|
||||
const RadKVGroupBatch* kvs = kv_batch(batch, m.kv_s);
|
||||
const RadKVGroupBatch* kvg = kv_batch(batch, m.kv_g);
|
||||
if (!kvs || !kvg || !kvs->slot_mapping || !kvg->slot_mapping || !kvs->block_table ||
|
||||
!kvg->block_table || !kvs->seqused || !kvg->seqused)
|
||||
return serial("a KV group without slots, tables or lengths");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d || !rad_buf_ptr(c, m.b_pipe_used)) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(4 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl)
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[4 * t] = 0;
|
||||
m.pipe_tbl[4 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[4 * t + 2] = (int32_t)t;
|
||||
m.pipe_tbl[4 * t + 3] = (int32_t)(t - pipe_rows(t));
|
||||
}
|
||||
}
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 4 * T, 4 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
int32_t* u = (int32_t*)rad_buf_ptr(c, m.b_pipe_used);
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvs->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u, RAD_I32, 1));
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvg->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u + 1, RAD_I32, 1));
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every other
|
||||
* collective. */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
m.jf0.step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, 2 * li, T};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
const int32_t* used0 = (const int32_t*)rad_buf_ptr(c, m.b_pipe_used) + (l.global ? 1 : 0);
|
||||
l.attn.step_pieces(c, batch, &pc, used0);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "gemma3: an attention block did not run its two pieces");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li, R, T - R); });
|
||||
l.mlp.body_rows(c, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, 0, R); });
|
||||
l.mlp.body_rows(c, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_lm),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
if (batch->enc) {
|
||||
@@ -1197,6 +1621,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
{
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
/* The drafter conditions on a tapped layer's output, which the next layer overwrites: copy it
|
||||
* into the tap's column slice once the layer's residual is complete. */
|
||||
@@ -1217,7 +1649,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
const bool far = m.fuse_mx_ar;
|
||||
/* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */
|
||||
const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T);
|
||||
l.attn.step(c, batch, true, true, far);
|
||||
if (!far) l.attn.post(c, T);
|
||||
l.jf_am.step(c, T, far);
|
||||
@@ -1233,10 +1666,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; !m.fuse_mx && 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, m.fuse_ar);
|
||||
if (m.fuse) l.j_am.step(c, T, m.fuse_ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, m.fuse_ar);
|
||||
const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, ar);
|
||||
if (m.fuse) l.j_am.step(c, T, ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, ar);
|
||||
tap(li);
|
||||
}
|
||||
/* With fused junctions the last layer's tail ran unfused (tail_fused false), so the stream is
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
* 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
|
||||
* Three draft models, whichever the container carries under `draft.`: Google's assistant head (a
|
||||
* serial head over the trunk's own cache, the Gemma4Head below), 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.
|
||||
* arch/common/rad_gemma4_dflash.h; 15 tokens a pass on the 31B), or a DFlash2 drafter such as
|
||||
* RedHatAI's gemma-4-31B-it-speculator.dflash2 (arch/common/rad_block_dflash2.h; 7 a pass).
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
@@ -104,7 +104,25 @@ struct G4Linear {
|
||||
rad_op op = 0, op_q = 0; /* the quantised GEMM and, for w4a8, its activation quantiser */
|
||||
rad_buf q8 = 0, s8 = 0; /* the int8 pair (i8 codes + f32 row scale) the quantiser writes */
|
||||
int64_t N = 0, K = 0;
|
||||
bool quant = false; /* true: w4a8 */
|
||||
bool quant = false; /* true: w4a8 / w8a8 over a per-row int8 activation */
|
||||
/* true: i8a8 as arch/gemma3's G3Linear: int8 codes with a bf16 scale per [1 x 128] (libquant
|
||||
* `codes=i8 group=128 scale=bf16`) over quant_act_i8g, an activation scale per (row, 128).
|
||||
* Gemma 4 E4B's activations carry a few channels 40-200 times the row's median (the down
|
||||
* projection's input most), and one int8 scale a row spends its codes on them. There is no
|
||||
* fused norm/quantiser at this grid, so the junctions stay off for a model that uses it. */
|
||||
bool i8g = false;
|
||||
/* true: asymmetric int4 as arch/gemma3's G3Linear: u4 codes, a u8 zero point and an f16 scale
|
||||
* per [1 x 128] (libquant `codes=u4 zero=u8 group=128 scale=f16`), gemm_nt_q at w4a8i8_asym
|
||||
* over the same per-(row, 128) int8 activation as i8g. */
|
||||
bool a4 = false;
|
||||
bool grouped() const { return i8g || a4; }
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work and reads its weight a quarter as fast. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
int64_t a4_split = 0; /* rows up to which op_dec serves; 0: no decode band */
|
||||
rad_buf a16 = 0;
|
||||
rad_op op_a16 = 0, op_dec = 0;
|
||||
/* Reads another linear's int8 pair. q, k and v quantise the same norm output on the same
|
||||
* per-row grid, so with `in_from` set at declare this linear reads that linear's pair and
|
||||
* declares no quantiser of its own: one dispatch instead of three. */
|
||||
@@ -175,6 +193,73 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
* 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;
|
||||
i8g = known && linear_is_w8(enc);
|
||||
{
|
||||
const RadEncPlane* sp = rad_enc_plane(&enc, "scale");
|
||||
const RadEncPlane* zp = rad_enc_plane(&enc, "zero");
|
||||
a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] &&
|
||||
cdt == RAD_U4 && enc.plane[0].block[1] == 1 && sp && sp->dtype == RAD_F16 &&
|
||||
sp->block[0] == 1 && sp->block[1] == RAD_FP8_BLOCK && zp && zp->dtype == RAD_U8 &&
|
||||
zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
if (i8g || a4) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in "
|
||||
"whole %d-column activation scale groups\n", base, (long long)N,
|
||||
(long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (a4) {
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
} else {
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
}
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
/* not an a4 linear's pair: below its decode band it writes none */
|
||||
if (in_from && in_from->grouped() && !in_from->a4 && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { q8, s8 });
|
||||
if (!op_q) return RAD_E_INVAL;
|
||||
}
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", a4 ? "w4a8i8_asym" : "i8a8")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (a4) {
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
if (!op_a16 || !op_dec) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
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 "
|
||||
@@ -216,8 +301,8 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8 or w8a8 -- "
|
||||
"neither matches\n", wn, en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8, w8a8, "
|
||||
"int8 a 128 (i8a8) or asymmetric int4 a 128 -- none matches\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -229,6 +314,16 @@ inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
/* the decode band: f16 copy of the input, the skinny kernel; operands as LinearFP8's w4 */
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
} else if (grouped()) {
|
||||
/* quant_act_i8g takes x, q, scale: no optional `asum`. */
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T));
|
||||
gemm(c, y, T);
|
||||
} else
|
||||
RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T));
|
||||
}
|
||||
@@ -239,18 +334,29 @@ inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
}
|
||||
|
||||
inline void G4Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (!quant) {
|
||||
if (a4 && n <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n));
|
||||
RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (!quant && !grouped()) {
|
||||
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)
|
||||
const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1; /* the scale plane's row width */
|
||||
if (!shared_in && grouped())
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, sw));
|
||||
else 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),
|
||||
const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1;
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, sw), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
@@ -265,6 +371,11 @@ struct Gemma4Attn {
|
||||
ClassGeom cls{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
/* KV sharing (num_kv_shared_layers, Gemma 4 E2B/E4B): a shared layer has no k or v of its own
|
||||
* and attends over the cache of `kv_layer`, the last earlier layer of its class that keeps
|
||||
* one. A layer with its own cache has kv_layer == layer. */
|
||||
bool shared = false;
|
||||
int kv_layer = 0;
|
||||
|
||||
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) */
|
||||
@@ -297,12 +408,16 @@ struct Gemma4Attn {
|
||||
/* 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 {
|
||||
if (shared) return ln_q.quant;
|
||||
return fused ? ln_qkv.quant
|
||||
: ln_q.quant && ln_k.shared_in && (!cls.has_v || ln_v.shared_in);
|
||||
}
|
||||
|
||||
/* `kv_src` < 0: the layer keeps its own cache; else the layer whose cache it reads. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot);
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot,
|
||||
int kv_src = -1);
|
||||
int declare_shared(RadBuilder* b, Names& nm, const char* pre);
|
||||
/* `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,
|
||||
@@ -323,8 +438,12 @@ struct Gemma4Attn {
|
||||
};
|
||||
|
||||
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_buf* qkv_slot) {
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot,
|
||||
int kv_src) {
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire;
|
||||
shared = kv_src >= 0;
|
||||
kv_layer = shared ? kv_src : l;
|
||||
if (shared) return declare_shared(b, nm, pre);
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
|
||||
|
||||
@@ -363,13 +482,18 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
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 }));
|
||||
{
|
||||
/* one q|k|v GEMM wherever the weight is on a quantised grid: w4a8 / w8a8, i8a8 or a4 */
|
||||
RadEncoding e{};
|
||||
fused = weight_enc(b, qkv_wn, &e) && g4_grid_w4(e);
|
||||
fused = weight_enc(b, qkv_wn, &e) && (g4_grid_w4(e) || linear_is_w8(e) ||
|
||||
(rad_enc_is(&e, "affine") && e.n_planes == 3 &&
|
||||
e.plane[0].dtype == RAD_U4));
|
||||
}
|
||||
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,
|
||||
/* named by class, not by the value path: a global class with its own v (E2B/E4B,
|
||||
* attention_k_eq_v false) has one too, and the two rows differ in width */
|
||||
*qkv_slot = decl_b(b, nm.f(cls.head_ladder ? "attn_qkvg" : "attn_qkvs"), g.act_dtype,
|
||||
{g.max_tok, qkvd});
|
||||
w.qkv = *qkv_slot;
|
||||
if (cls.has_v)
|
||||
@@ -589,6 +713,78 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A KV-shared layer (transformers' Gemma4TextAttention with is_kv_shared_layer): q_proj, the per-head
|
||||
* q norm and the class's rotary, attention over the source layer's cache, o_proj and the two norms.
|
||||
* No k or v projection, no k or v norm and no cache store: the source layer, earlier in the same
|
||||
* step, wrote the keys and values these queries read. The checkpoint's k_proj / v_proj / k_norm of
|
||||
* these layers (the "frozen shared kv" file) are unused, as in the reference. */
|
||||
int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
|
||||
const int l = layer;
|
||||
const int64_t qd = cls.q_dim();
|
||||
fused = false;
|
||||
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)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l)));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
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));
|
||||
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));
|
||||
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));
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
op_qn = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head), RAD_INT("n", cls.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn)),
|
||||
{w.q}, {w.q});
|
||||
op_rq = rw(b, RAD_OP(b, "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", 0),
|
||||
RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale),
|
||||
RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.n_rot),
|
||||
RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
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});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_post)),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
return (op_norm && op_qn && op_rq && op_attn && op_post && op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- Prefetch beside the reductions (prefetch_beside, rad_arch.h). The all-reduce in front of
|
||||
* each GEMM leaves the card's memory idle for its round trip (~20 us at a DFlash2 verify's rows on
|
||||
* 4x R9700), so the trunk reads the next GEMM's leading bytes in that window -- gate_up's after
|
||||
@@ -609,7 +805,13 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
bool ar_fused) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
if (fused) {
|
||||
if (shared) {
|
||||
if (entry_done) ln_q.gemm(c, w.q, T);
|
||||
else {
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
ln_q.step(c, w.h, w.q, T);
|
||||
}
|
||||
} else 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);
|
||||
@@ -637,6 +839,10 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
}
|
||||
|
||||
void Gemma4Attn::project(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
if (shared) {
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
return;
|
||||
}
|
||||
if (fused) {
|
||||
ln_qkv.gemm_rows(c, w.qkv, r0, n);
|
||||
return;
|
||||
@@ -657,6 +863,19 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
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();
|
||||
if (shared) {
|
||||
/* q only: its norm and rotary, then attention over the source layer's cache. */
|
||||
RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T));
|
||||
RAD_ISSUE(c, op_rq, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, 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));
|
||||
return;
|
||||
}
|
||||
/* 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;
|
||||
@@ -869,43 +1088,24 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
/* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the
|
||||
* layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With
|
||||
* `res` null it is the plain norm of `x`, the first block's entry. */
|
||||
/* The four-rank fold's band. libr4d's exact all-reduce is a one-shot up to this many elements
|
||||
* (R4D_AR_WIDE_ONESHOT_MAX_ELEMS) and a two-shot above, and the fused junction at four ranks is
|
||||
* that one-shot with the junction as its epilogue: three times the message per rank on the link,
|
||||
* which pays at decode heights and not at a prefill's. So at four ranks op_ar serves the rows a
|
||||
* one-shot would, 97 at 5376, and a taller step issues the all-reduce and the junction apart.
|
||||
*
|
||||
* Within that band the fold pays only at the bottom. On 4x R9700 (2026-10-17, same image) a plain
|
||||
* decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify
|
||||
* (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact
|
||||
* two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs
|
||||
* cross near 4-5 rows. From 5 rows libr4d's four-rank row takes its tail form instead (axis
|
||||
* `tail`): the standalone two-shot with the junction run after it in the same launch, behind a
|
||||
* card-local count, so the junction costs neither a handshake nor a launch. With it a DFlash2
|
||||
* verify (8 rows) folds and gains ~1% (348 / 258 / 187 / 516 against 345 / 255 / 185 / 511 tok/s,
|
||||
* code / prose / story / long, 4x R9700; replies identical), where the one-shot fold there lost
|
||||
* 6%. So the fold serves up to kAr4FoldRows rows, a z-lab DFlash verify's 16 included, and a
|
||||
* taller step issues the pair. */
|
||||
static constexpr int64_t kArOneShotElems = 524288;
|
||||
/* The four-rank fold's band. libr4d's four-rank row serves it in three forms, all byte-identical
|
||||
* to all_reduce + rmsnorm_quant_i8. Up to 4 rows it is the exact one-shot with the junction as its
|
||||
* epilogue: three times the message per rank and one fenced handshake a row, which wins at one row
|
||||
* (plain decode about 5% faster on 4x R9700) and loses to the standalone two-shot by 16. From 5
|
||||
* rows it is that two-shot with the junction as its tail (axis `tail`), behind a card-local count,
|
||||
* so the junction costs neither a handshake nor a launch. Above kAr4FoldRows a step issues the
|
||||
* pair. */
|
||||
static constexpr int64_t kAr4FoldRows = 16;
|
||||
/* From kArSpMinRows rows to the same band's top, libr4d's four-rank row takes `sp` instead: the
|
||||
* all-reduce split around the junction. Each rank reduces only the rows it owns (a quarter, in
|
||||
* rank order), runs the junction on them and gathers the int8 codes the next GEMM reads, so the
|
||||
* second hop carries a byte a column instead of two and the junction a quarter of the rows. The
|
||||
* fold and the sums are the whole form's, so q and the scales are byte for byte the same; the
|
||||
* residual stream then holds this rank's rows only, which is all the next junction reads. A
|
||||
* junction whose stream anything else reads next asks for the residual on every row too (sp 2):
|
||||
/* From kArSpMinRows rows to kArSpMaxRows, libr4d's four-rank row takes `sp`: the all-reduce split
|
||||
* around the junction. Each rank reduces only the rows it owns (a quarter, in rank order), runs the
|
||||
* junction on them and gathers the int8 codes the next GEMM reads, so the second hop carries a byte
|
||||
* a column instead of two and the junction runs on a quarter of the rows. q and the scales are
|
||||
* the whole form's bytes; the residual stream then holds this rank's rows only, which is all the
|
||||
* next junction reads. A junction whose stream anything else reads next asks for every row (sp 2):
|
||||
* the layers the drafter taps, and the last layer's attention junction, since that layer's
|
||||
* feed-forward closes with its own all-reduce, post-norm and add over every row. One launch at a
|
||||
* time on 4x R9700 (2026-10-19): 19.8 against 21.9 us at 4 rows of 5376 (the one-shot fold), 22.9
|
||||
* against 24.5 at 8 and 30.8 against 34.9 at 16 (the tail), 72.3 against 89.2 at 64. Below 4 rows
|
||||
* a rank would idle (31.7 against 18.7 us at one).
|
||||
*
|
||||
* In the engine it pays only where it replaces the fold: a DFlash2 verify (8 rows) ran 402 / 297 /
|
||||
* 216 / 603 tok/s code / prose / story / long against 392 / 290 / 210 / 585, replies identical,
|
||||
* but steps of 24-64 rows, where the pair runs instead, lost ~10% under load (4 users 588 against
|
||||
* 698 aggregate, 8 users 781 against 867; 12 users even; 4x R9700, 2026-10-19). So it serves to
|
||||
* kArSpMaxRows, the fold's band, within the one-shot's. */
|
||||
* feed-forward closes with its own all-reduce, post-norm and add over every row. Below 4 rows a
|
||||
* rank would idle (on 4x R9700, 31.7 against 18.7 us at one row); at 24-64 rows, where the pair
|
||||
* runs, the split form lost about 10% of aggregate throughput under load. */
|
||||
static constexpr int64_t kArSpMinRows = 4;
|
||||
static constexpr int64_t kArSpMaxRows = 16;
|
||||
|
||||
@@ -941,11 +1141,10 @@ struct G4Junction {
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
/* With the all-reduce in front, at two or four ranks on the exact wire: `x` is then a
|
||||
* rank's partial sum of a column-sharded linear. With the lossy wire allowed, the
|
||||
* standalone all-reduce is kept, since it may choose that wire. At four ranks the fold is
|
||||
* the one-shot's and serves only its band (kArOneShotElems, kAr4FoldRows). */
|
||||
* standalone all-reduce is kept, since it may choose that wire. At four ranks the fold
|
||||
* serves steps of up to kAr4FoldRows rows. */
|
||||
const bool four = g.world == 4;
|
||||
const int64_t hi = four ? std::min<int64_t>(kAr4FoldRows, std::min<int64_t>(g.max_tok, kArOneShotElems / g.n_embd))
|
||||
: g.max_tok;
|
||||
const int64_t hi = four ? std::min<int64_t>(kAr4FoldRows, g.max_tok) : g.max_tok;
|
||||
if (res && g.wire_exact && (g.world == 2 || four) && hi >= 1 &&
|
||||
rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, hi), RAD_INT("n", g.n_embd),
|
||||
@@ -960,8 +1159,7 @@ struct G4Junction {
|
||||
}
|
||||
/* The split form from kArSpMinRows to kArSpMaxRows rows. It needs the post-norm, as
|
||||
* every trunk junction past the first has; `x` is declared written, as the fold's. */
|
||||
const int64_t top = std::min<int64_t>(
|
||||
std::min<int64_t>(g.max_tok, kArOneShotElems / g.n_embd), kArSpMaxRows);
|
||||
const int64_t top = std::min<int64_t>(g.max_tok, kArSpMaxRows);
|
||||
if (op_ar && four && wp && top >= kArSpMinRows) {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, top), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
@@ -1468,6 +1666,11 @@ struct Layer {
|
||||
Gemma4Mlp mlp{};
|
||||
rad_weight w_scalar = 0; /* the per-layer [1] residual scalar, `cur = cur * scalar` */
|
||||
rad_op op_scale = 0;
|
||||
/* Per-layer embeddings (Gemma 4 E2B/E4B), after the feed-forward's residual add and before the
|
||||
* scalar: x += norm(proj(gelu(gate(x)) * pli[l])). `ple_post` is the norm's gain. */
|
||||
G4Linear ln_pg{}, ln_pp{};
|
||||
rad_weight w_ple_post = 0;
|
||||
rad_op op_ple_act = 0, op_ple_post = 0, op_ple_add = 0;
|
||||
/* The fused junctions (see "Residual junctions" above): attention -> this layer's
|
||||
* feed-forward, and this layer's feed-forward -> the next layer's attention, scalar included.
|
||||
* The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not
|
||||
@@ -1506,6 +1709,22 @@ struct Model {
|
||||
rad_weight w_tok = 0, w_out = 0, w_lm = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0, op_cap = 0;
|
||||
|
||||
/* Per-layer embeddings (hidden_size_per_layer_input > 0): the token-identity table
|
||||
* (embed_tokens_per_layer, n_layer x n_ple wide), the context projection of the scaled
|
||||
* embedding and its per-(token, layer) norm, combined into `b_ple` [max_tok, n_layer * n_ple]
|
||||
* that every layer reads its slice of. */
|
||||
int64_t n_ple = 0;
|
||||
rad_weight w_ple_tok = 0, w_ple_norm = 0;
|
||||
G4Linear ln_ple_proj{};
|
||||
rad_buf b_ple = 0, b_ple_tok = 0, b_pg = 0;
|
||||
rad_op op_ple_tok = 0, op_ple_norm = 0, op_ple_add = 0;
|
||||
/* An image's placeholder positions take the token-identity row of pad_token_id, as the
|
||||
* reference looks them up (Gemma4Model.forward: llm_input_ids = pad where multimodal): that row
|
||||
* times sqrt(n_ple), made as fill(sqrt(n_ple)) * the row, scattered over the image rows. */
|
||||
rad_weight w_ple_pad = 0;
|
||||
rad_buf b_ple_pad = 0;
|
||||
rad_op op_ple_pfill = 0, op_ple_pmul = 0, op_ple_pscat = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* The assistant head, declared only when the container carries one and the deployment
|
||||
@@ -1768,7 +1987,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* ---- geometry RadModelMeta does not name. */
|
||||
const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads", 0);
|
||||
/* num_global_key_value_heads may be null (Gemma 4 E2B/E4B): the global layers then take the
|
||||
* model's num_key_value_heads, as transformers' per-layer config does. */
|
||||
const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads",
|
||||
meta_text_geti(meta, "num_key_value_heads", 0));
|
||||
const int64_t head_g = meta_text_geti(meta, "global_head_dim", 0);
|
||||
const int64_t sliding_win = meta_text_geti(meta, "sliding_window", 0);
|
||||
const int64_t kv_shared = meta_text_geti(meta, "num_kv_shared_layers", 0);
|
||||
@@ -1798,12 +2020,28 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
if (!(softcap > 0.0)) { fprintf(stderr, "radiance: gemma4: final_logit_softcapping is required\n"); return RAD_E_INVAL; }
|
||||
if (kv_shared < 0) { fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld is negative\n", (long long)kv_shared); return RAD_E_INVAL; }
|
||||
if (kv_shared > 0) {
|
||||
fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld needs a shared-KV reuse path; refusing\n",
|
||||
(long long)kv_shared);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (kv_shared >= g.n_layer) {
|
||||
fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld leaves no layer with a cache of "
|
||||
"its own (%lld layers)\n", (long long)kv_shared, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (sliding_win <= 0) { fprintf(stderr, "radiance: gemma4: sliding_window %lld is required\n", (long long)sliding_win); return RAD_E_INVAL; }
|
||||
m.n_ple = meta_text_geti(meta, "hidden_size_per_layer_input", 0);
|
||||
if (m.n_ple < 0) { fprintf(stderr, "radiance: gemma4: hidden_size_per_layer_input %lld is negative\n", (long long)m.n_ple); return RAD_E_INVAL; }
|
||||
if (m.n_ple > 0) {
|
||||
const int64_t v_ple = meta_text_geti(meta, "vocab_size_per_layer_input", g.n_vocab_all);
|
||||
if (g.world > 1) {
|
||||
fprintf(stderr, "radiance: gemma4: per-layer embeddings (hidden_size_per_layer_input %lld) "
|
||||
"are served at one rank only; this model is small enough for one card\n",
|
||||
(long long)m.n_ple);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (v_ple != g.n_vocab_all) {
|
||||
fprintf(stderr, "radiance: gemma4: vocab_size_per_layer_input %lld differs from the "
|
||||
"vocabulary (%lld)\n", (long long)v_ple, (long long)g.n_vocab_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
if (!(prf > 0.0)) prf = 1.0;
|
||||
const int64_t n_rot_g = (int64_t)(head_g * prf + 0.5);
|
||||
if (n_rot_g <= 0 || n_rot_g > head_g || (n_rot_g & 1)) {
|
||||
@@ -1828,6 +2066,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
int n_global = 0;
|
||||
for (int v : is_global) n_global += v;
|
||||
|
||||
/* KV sharing: from layer n_layer - num_kv_shared_layers on, a layer keeps no cache and reads the
|
||||
* last earlier non-shared layer of its own class (transformers' store_full_length_kv; E4B:
|
||||
* sliding layers read 22, full layers 23). kv_src[l] is that layer, or -1 for an own cache. */
|
||||
const int64_t first_shared = g.n_layer - kv_shared;
|
||||
std::vector<int> kv_src((size_t)g.n_layer, -1);
|
||||
if (kv_shared > 0) {
|
||||
int last_s = -1, last_f = -1;
|
||||
for (int64_t l = 0; l < first_shared; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
for (int64_t l = first_shared; l < g.n_layer; ++l) {
|
||||
const int src = is_global[(size_t)l] ? last_f : last_s;
|
||||
if (src < 0) {
|
||||
fprintf(stderr, "radiance: gemma4: KV-shared layer %lld is %s and no earlier layer of "
|
||||
"that class keeps a cache\n", (long long)l,
|
||||
is_global[(size_t)l] ? "full" : "sliding");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
kv_src[(size_t)l] = src;
|
||||
}
|
||||
}
|
||||
|
||||
/* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s);
|
||||
* the global class is built from the container header. */
|
||||
m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim;
|
||||
@@ -1929,6 +2187,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* ---- per-layer embeddings (transformers' get_per_layer_inputs / project_per_layer_inputs):
|
||||
* tok = embed_tokens_per_layer[id] * sqrt(n_ple) (bf16, sqrt(256) = 16)
|
||||
* ctx = rmsnorm( (e @ W_proj^T) * n_embd^-0.5 ) per (token, layer) over n_ple, gain w_norm
|
||||
* pli = (ctx + tok) * 2^-0.5
|
||||
* `e` is the scaled embedding (after any image rows are scattered in). The projection's scale
|
||||
* is folded into the norm's eps, as embgemma2 does: rmsnorm(s x, eps) = rmsnorm(x, eps / s^2),
|
||||
* so no bf16 rounding of s x. The table is read a row a token, so the placement puts it in the
|
||||
* pinned host pool by default (--embedding-placement ram), off the card. */
|
||||
if (m.n_ple > 0) {
|
||||
const int64_t P = g.n_layer * m.n_ple;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_token_embd.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens_per_layer.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj_norm.weight"),
|
||||
nm.ckpt("model.language_model.per_layer_projection_norm.weight")));
|
||||
m.w_ple_tok = decl_w(b, nm.f("ple_token_embd.weight"), RAD_BF16, {g.n_vocab, P},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_ple_norm = decl_w(b, nm.f("ple_proj_norm.weight"), RAD_BF16, {m.n_ple},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.b_ple = decl_b(b, nm.f("ple_in"), g.act_dtype, {g.max_tok, P});
|
||||
m.b_ple_tok = decl_b(b, nm.f("ple_tok"), g.act_dtype, {g.max_tok, P});
|
||||
m.b_pg = decl_b(b, nm.f("ple_gate"), g.act_dtype, {g.max_tok, m.n_ple});
|
||||
if (!m.w_ple_tok || !m.w_ple_norm || !m.b_ple || !m.b_ple_tok || !m.b_pg) return RAD_E_INVAL;
|
||||
m.op_ple_tok = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", P),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off),
|
||||
RAD_F64("mult", std::sqrt((double)m.n_ple))),
|
||||
RAD_WEIGHTS(m.w_ple_tok)),
|
||||
{}, {m.b_ple_tok});
|
||||
RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"),
|
||||
{ nm.ckpt("model.language_model.per_layer_model_projection.weight") },
|
||||
P, g.n_embd, RAD_SHARD_NONE, grp_model(), m.b_x, m.b_ple));
|
||||
m.op_ple_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_layer), RAD_INT("n", m.n_ple),
|
||||
RAD_F64("eps", (double)g.eps * (double)g.n_embd),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_ple_norm)),
|
||||
{m.b_ple}, {m.b_ple});
|
||||
m.op_ple_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("div", std::sqrt(2.0))),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple, m.b_ple_tok}, {m.b_ple});
|
||||
if (!m.op_ple_tok || !m.op_ple_norm || !m.op_ple_add) return RAD_E_INVAL;
|
||||
if (m.op_mm) {
|
||||
const int pad = (int)meta_text_geti(meta, "pad_token_id", 0);
|
||||
RAD_ARCH_TRY(map_slice(b, nm.f("ple_pad_row.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens_per_layer.weight"), pad));
|
||||
m.w_ple_pad = decl_w(b, nm.f("ple_pad_row.weight"), RAD_BF16, {P}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.b_ple_pad = decl_b(b, nm.f("ple_pad"), g.act_dtype, {g.max_tok, P});
|
||||
if (!m.w_ple_pad || !m.b_ple_pad) return RAD_E_INVAL;
|
||||
m.op_ple_pfill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("value", std::sqrt((double)m.n_ple))),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {m.b_ple_pad});
|
||||
m.op_ple_pmul = rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("scalar", 0)),
|
||||
RAD_WEIGHTS(m.w_ple_pad)),
|
||||
{m.b_ple_pad}, {m.b_ple_pad});
|
||||
m.op_ple_pscat = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple_pad, m.b_ple_tok}, {m.b_ple_tok});
|
||||
if (!m.op_ple_pfill || !m.op_ple_pmul || !m.op_ple_pscat) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the layers. */
|
||||
Gemma4Attn::Wire sw{}; sw.x = m.b_x; sw.h = m.b_h; sw.q = m.b_qs; sw.k = m.b_ks; sw.v = m.b_vs; sw.attn = m.b_attns;
|
||||
Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting;
|
||||
@@ -1941,9 +2271,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
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));
|
||||
/* A KV-shared layer is not bound: the group's pages hold only the layers that write. */
|
||||
if (kv_src[(size_t)l] < 0) 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,
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs));
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l]));
|
||||
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. */
|
||||
@@ -1957,11 +2288,48 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_WEIGHTS(lay.w_scalar)),
|
||||
{mw.x}, {mw.x});
|
||||
|
||||
/* The per-layer embedding branch (transformers' Gemma4TextDecoderLayer, after the
|
||||
* feed-forward's residual add): gate n_embd -> n_ple, gelu_tanh times this layer's slice of
|
||||
* `ple_in`, projection back to n_embd into `h`, its norm, the residual add. The scalar
|
||||
* follows it. */
|
||||
if (m.n_ple > 0) {
|
||||
RAD_ARCH_TRY(lay.ln_pg.declare(b, nm, g, nm.f("blk.%d.ple_gate", (int)l),
|
||||
{ nm.ckpt("%s.%lld.per_layer_input_gate.weight", pre, (long long)l) },
|
||||
m.n_ple, g.n_embd, RAD_SHARD_NONE, grp_layer((int)l),
|
||||
m.b_x, m.b_pg));
|
||||
RAD_ARCH_TRY(lay.ln_pp.declare(b, nm, g, nm.f("blk.%d.ple_proj", (int)l),
|
||||
{ nm.ckpt("%s.%lld.per_layer_projection.weight", pre, (long long)l) },
|
||||
g.n_embd, m.n_ple, RAD_SHARD_NONE, grp_layer((int)l),
|
||||
m.b_pg, m.b_h));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_post_norm.weight", (int)l),
|
||||
nm.ckpt("%s.%lld.post_per_layer_input_norm.weight", pre, (long long)l)));
|
||||
lay.w_ple_post = decl_w(b, nm.f("blk.%d.ple_post_norm.weight", (int)l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer((int)l));
|
||||
lay.op_ple_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", m.n_ple),
|
||||
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_pg, m.b_ple}, {m.b_pg});
|
||||
lay.op_ple_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_ple_post)),
|
||||
{m.b_h}, {m.b_h});
|
||||
lay.op_ple_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
if (!lay.w_ple_post || !lay.op_ple_act || !lay.op_ple_post || !lay.op_ple_add)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
* after, because the buffer planner's liveness is declaration order. Declared after the
|
||||
* trunk, `dflash_src` would look born at its end and free to share with what every layer
|
||||
* writes: the drafts would fail while the reply stays 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",
|
||||
@@ -1996,7 +2364,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ok = lay.j_am.op != 0;
|
||||
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,
|
||||
/* With per-layer embeddings the junction closes the PLE branch instead of the
|
||||
* feed-forward (whose post-norm and add then run apart): the branch's norm,
|
||||
* its add, the scalar, the next norm and quantiser, in the reference's order. */
|
||||
RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm,
|
||||
m.n_ple > 0 ? lay.w_ple_post : lay.mlp.w_post,
|
||||
lay.w_scalar, nx.attn.ln_in(), tapped));
|
||||
ok = lay.j_ma.op != 0;
|
||||
}
|
||||
@@ -2019,8 +2391,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last
|
||||
* layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's
|
||||
* first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank,
|
||||
* where there are reductions to sit beside. RADIANCE_PREFETCH=0 declares none
|
||||
* (decl_prefetch). */
|
||||
* where there are reductions to sit beside. */
|
||||
if (g.world > 1 && rad_op_declared(b, "prefetch")) {
|
||||
for (size_t l = 0; l < m.layers.size(); ++l) {
|
||||
Layer& lay = m.layers[l];
|
||||
@@ -2046,9 +2417,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* 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;
|
||||
m.overlap = 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));
|
||||
@@ -2081,11 +2450,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* feed-forward reduction only slice A's junction and q|k|v. Per slice (A's projection,
|
||||
* prologue, attention and o_proj, then B's), each of the four reductions sits beside a whole
|
||||
* block: on 4x R9700 the exact two-shot of a 1024-row slice takes ~1.05 ms alone and ~1.4x
|
||||
* that beside any card-filling compute (a four-card microbenchmark, 2026-10-18). Slice A's
|
||||
* attention reads its context end from kv_len_trim, one a KV group. A one-sequence step only
|
||||
* (the slices' rows are then one sequence's), with the one-launch prologue and no
|
||||
* multi-component rotary. Byte-identical: every greedy reply matches the whole attention's
|
||||
* (4x R9700, two rounds, and 16 of 16 fresh starts on a 5310-token prompt); prefill +5%. */
|
||||
* that beside card-filling compute, so the reductions want whole blocks to hide behind. Slice
|
||||
* A's attention reads its context end from kv_len_trim, one a KV group. A one-sequence step
|
||||
* only (the slices' rows are then one sequence's), with the one-launch prologue and no
|
||||
* multi-component rotary. A slice's attention rows see exactly the keys they see in the whole
|
||||
* step, so the output is the whole attention's byte for byte. */
|
||||
if (m.overlap) {
|
||||
bool ok = !g.rope_mc && rad_op_declared(b, "kv_len_trim");
|
||||
for (const Layer& lay : m.layers) ok = ok && lay.attn.slicable();
|
||||
@@ -2136,7 +2505,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the deployment speculates; otherwise its ~0.5 GB of weights stay off the card. */
|
||||
if (ctx->max_spec > 0 && has_assistant(meta)) {
|
||||
int last_s = -1, last_f = -1;
|
||||
for (int64_t l = 0; l < m.n_main; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
/* the last layer of each class that keeps a cache (a KV-shared layer reads another's) */
|
||||
for (int64_t l = 0; l < m.n_main; ++l)
|
||||
if (kv_src[(size_t)l] < 0) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
RAD_ARCH_TRY(m.head.declare(b, nm, meta, g, m.cs, m.cg, m.kv_s, m.kv_g, last_s, last_f,
|
||||
m.n_main, m.w_tok, m.b_h, m.b_logits));
|
||||
m.have_head = true;
|
||||
@@ -2196,6 +2567,15 @@ 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);
|
||||
if (kv_shared > 0) {
|
||||
int src_s = -1, src_f = -1;
|
||||
for (int64_t l = first_shared; l < g.n_layer; ++l)
|
||||
(is_global[(size_t)l] ? src_f : src_s) = kv_src[(size_t)l];
|
||||
rad_note(b, "KV sharing: layers %lld..%lld keep no cache and read the last earlier layer of "
|
||||
"their class (sliding %d, full %d); %lld of %lld layers hold KV",
|
||||
(long long)first_shared, (long long)(g.n_layer - 1), src_s, src_f,
|
||||
(long long)first_shared, (long long)g.n_layer);
|
||||
}
|
||||
{
|
||||
int64_t n_fused = 0, n_row = 0, n_dec = 0, dec_hi = 0;
|
||||
for (const Layer& lay : m.layers) {
|
||||
@@ -2220,8 +2600,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(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"
|
||||
!g.wire_exact ? "the lossy all-reduce wire"
|
||||
: !m.fuse ? "the residual junctions are not fused"
|
||||
: "a step holds fewer than two slices");
|
||||
}
|
||||
@@ -2445,6 +2824,23 @@ 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.n_ple > 0) {
|
||||
RAD_ISSUE(c, m.op_ple_tok, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_ple_tok),
|
||||
brows(m.b_ple_tok, T));
|
||||
if (m.op_ple_pscat && batch->n_mm_rows > 0) {
|
||||
const int64_t nm_rows = batch->n_mm_rows;
|
||||
RAD_ISSUE_N(c, m.op_ple_pfill, nm_rows, brows(m.b_ple_pad, nm_rows));
|
||||
RAD_ISSUE_N(c, m.op_ple_pmul, nm_rows, brows(m.b_ple_pad, nm_rows), RAD_W(m.w_ple_pad),
|
||||
brows(m.b_ple_pad, nm_rows));
|
||||
RAD_ISSUE_N(c, m.op_ple_pscat, nm_rows, brows(m.b_ple_pad, nm_rows),
|
||||
praw(batch->mm_rows, RAD_I32, nm_rows), brows(m.b_ple_tok, T));
|
||||
}
|
||||
m.ln_ple_proj.step(c, m.b_x, m.b_ple, T);
|
||||
/* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */
|
||||
RAD_ISSUE_N(c, m.op_ple_norm, T * m.g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm),
|
||||
brows(m.b_ple, T));
|
||||
RAD_ISSUE(c, m.op_ple_add, brows(m.b_ple, T), brows(m.b_ple_tok, T), brows(m.b_ple, 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);
|
||||
@@ -2455,7 +2851,18 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, far);
|
||||
if (m.fuse) l.j_am.step(c, T, far);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, far);
|
||||
const bool ple = m.n_ple > 0;
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last && !ple, far);
|
||||
if (ple) {
|
||||
l.ln_pg.step(c, m.b_x, m.b_pg, T);
|
||||
RAD_ISSUE(c, l.op_ple_act, brows(m.b_pg, T),
|
||||
bcol(m.b_ple, (int64_t)li * m.n_ple, m.n_ple, T), brows(m.b_pg, T));
|
||||
l.ln_pp.step(c, m.b_pg, m.b_h, T);
|
||||
if (!(m.fuse && !last)) {
|
||||
RAD_ISSUE(c, l.op_ple_post, brows(m.b_h, T), RAD_W(l.w_ple_post), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_ple_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
}
|
||||
}
|
||||
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);
|
||||
@@ -2521,7 +2928,7 @@ RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"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")
|
||||
"logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter")
|
||||
RAD_ARCH_CHAT_FORMAT(gemma4_bf16)
|
||||
RAD_ARCH_PROBE(gemma4_bf16)
|
||||
#endif
|
||||
|
||||
+64
-10
@@ -46,6 +46,10 @@ struct Layer {
|
||||
struct Model {
|
||||
Names nm{};
|
||||
Geom g{};
|
||||
/* The MLA's split of a prefill-sized step under TP (RadBuildCtx::tp_attn_rows). The head
|
||||
* form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks);
|
||||
* the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */
|
||||
GlmMla::Form form = GlmMla::Form::heads;
|
||||
std::vector<Layer> layers;
|
||||
rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0;
|
||||
/* The streams and the step's stream-wide buffers. */
|
||||
@@ -102,7 +106,11 @@ static int stream_buffers(RadBuilder* b, Model& m) {
|
||||
m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 });
|
||||
m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 });
|
||||
m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 });
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 });
|
||||
/* The MLA row form gathers every rank's run at full length, so its output is rounded up to
|
||||
* whole runs; the head form keeps the step's rows. */
|
||||
const bool rows = g.world > 1 && m.form == GlmMla::Form::rows;
|
||||
m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16,
|
||||
{ rows ? g.world * GlmMla::rows_for(T, g.world) : T, 4096 });
|
||||
m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 });
|
||||
m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 });
|
||||
m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 });
|
||||
@@ -132,9 +140,9 @@ static int kda_buffers(RadBuilder* b, Model& m) {
|
||||
kw.core.out = bf("recurrent_out", W);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under
|
||||
* TP the selection planes hold every rank's run of rows, which can reach past the step
|
||||
* (DsaCache::part_rows). */
|
||||
/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then
|
||||
* the row form's (Model::form). Under TP the selection planes hold every rank's run of rows,
|
||||
* which can reach past the step (DsaCache::part_rows). */
|
||||
static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
auto& g = m.g;
|
||||
auto& nm = m.nm;
|
||||
@@ -160,6 +168,16 @@ static int mla_buffers(RadBuilder* b, Model& m) {
|
||||
const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T;
|
||||
aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 });
|
||||
aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ });
|
||||
if (g.world > 1 && m.form == GlmMla::Form::rows) {
|
||||
auto& rows = aw.rows;
|
||||
const int64_t R = GlmMla::rows_for(T, g.world);
|
||||
rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 });
|
||||
rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 });
|
||||
rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 });
|
||||
RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R));
|
||||
rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 });
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
static int indexer_buffers(RadBuilder* b, Model& m) {
|
||||
@@ -292,7 +310,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra
|
||||
decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096));
|
||||
if (lay.full) {
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true));
|
||||
// The MTP layer keeps the head form: its row form would cost another 126 MB a card.
|
||||
auto aw = m.aw;
|
||||
if (draft) aw.rows = {};
|
||||
RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true));
|
||||
DsaCache::Config c;
|
||||
c.blocks = (g.max_ctx + 3) / 4 + 1;
|
||||
c.work = (g.max_tok + 3) / 4 + g.max_seqs;
|
||||
@@ -386,18 +407,50 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 ||
|
||||
meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 ||
|
||||
cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 ||
|
||||
cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 ||
|
||||
(ctx->kv_dtype && ctx->kv_dtype != RAD_BF16))
|
||||
if (!GlmTp::world_ok(world)) {
|
||||
fprintf(stderr, "radiance: glm5next: --tp %d; the head, KDA channel and expert splits of "
|
||||
"this plugin are built for 1, 2, 4 or 8 ranks\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The graph is written for the released GLM-5.3-Flash and reads none of these from the
|
||||
* checkpoint, so a checkpoint that differs in any of them is refused by name. */
|
||||
const struct {
|
||||
const char* what;
|
||||
int64_t got, want;
|
||||
} shape[] = { { "hidden_size", meta->n_embd, 4096 },
|
||||
{ "num_hidden_layers", meta->n_layers, 45 },
|
||||
{ "vocab_size", meta->n_vocab, 154880 },
|
||||
{ "num_nextn_predict_layers", cfg(meta, "num_nextn_predict_layers", 0), 1 },
|
||||
{ "hc_mult", cfg(meta, "hc_mult", 0), 4 },
|
||||
{ "n_routed_experts", cfg(meta, "n_routed_experts", 0), 288 },
|
||||
{ "index_topk", cfg(meta, "index_topk", 0), 2048 } };
|
||||
for (const auto& s : shape)
|
||||
if (s.got != s.want) {
|
||||
fprintf(stderr, "radiance: glm5next: the checkpoint's %s is %lld; this plugin serves "
|
||||
"the GLM-5.3-Flash geometry, where it is %lld\n",
|
||||
s.what, (long long)s.got, (long long)s.want);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_spec > 31) {
|
||||
fprintf(stderr, "radiance: glm5next: --num-speculative-tokens %d; the KDA verify pass "
|
||||
"takes at most 32 rows a sequence, so the MTP depth is at most 31\n",
|
||||
ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent "
|
||||
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so "
|
||||
"run it with --kv-cache-dtype bf16\n",
|
||||
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
@@ -547,6 +600,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
|
||||
+11
-5
@@ -139,6 +139,7 @@ struct Model {
|
||||
std::vector<TeLayer> te;
|
||||
rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */
|
||||
std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */
|
||||
std::string tap_add; /* chan_affine's `add`: zeros */
|
||||
|
||||
/* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks
|
||||
* over the mixed rows `b_ft` */
|
||||
@@ -383,7 +384,12 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* scaled copy goes through te.h2, free between a layer's add and the next layer's projections,
|
||||
* so the residual stream itself is never scaled. */
|
||||
enum { kGainCh = 64 };
|
||||
if (g.n_embd % kGainCh) return RAD_E_INVAL;
|
||||
if (g.n_embd % kGainCh) {
|
||||
fprintf(stderr, "radiance: krea2: the text encoder's hidden size %lld is not a multiple of "
|
||||
"%d, the rows the rebalance gains are applied in\n", (long long)g.n_embd,
|
||||
(int)kGainCh);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[t]);
|
||||
@@ -393,9 +399,8 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.tap_mul[t] += v;
|
||||
}
|
||||
}
|
||||
static std::string zeros64;
|
||||
if (zeros64.empty())
|
||||
for (int k = 0; k < kGainCh; ++k) zeros64 += k ? " 0" : "0";
|
||||
m.tap_add.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0";
|
||||
|
||||
/* Layers up to the last tap only. */
|
||||
const int n_run = kTaps[kNTaps - 1];
|
||||
@@ -480,7 +485,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
L.op_gain = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[L.tap].c_str()),
|
||||
RAD_STR("add", zeros64.c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -1181,6 +1186,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.cond_rows = kCondRows;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.rope_text_l = 0;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE;
|
||||
RAD_ARCH_TRY(rad_declare_generator(b, &d));
|
||||
}
|
||||
rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu "
|
||||
|
||||
@@ -193,10 +193,28 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
|
||||
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
|
||||
* {0, pipe_rows(T), T} for every T, made once; and whether rank 0 has said it pipelines. */
|
||||
bool pipe_on = false;
|
||||
rad_buf b_pipe_cu = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows, so both pieces sit in one bucket band (core/runtime/ctx.h) and the second is never
|
||||
* wider than the first. */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
#endif
|
||||
|
||||
/* Checks the container's statement of its format, since every mismatch is silent: a
|
||||
* `weight_block_size` of [64,64] against kernels that shift by 7 reads the right bytes with the
|
||||
* wrong gain, and e5m2 decoded as e4m3 gives merely implausible numbers. A container that states
|
||||
@@ -264,6 +282,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -414,6 +433,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
|
||||
@@ -430,6 +450,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -583,17 +604,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
|
||||
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
|
||||
|
||||
/* The SSM state cache is f32.
|
||||
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
|
||||
*
|
||||
* State reads and writes dominate the two GDN kernels: one [128,128] state is 64 KiB at f32,
|
||||
* and a speculative step writes one per candidate token per head, since the surviving
|
||||
* candidate is unknown until after the layer. At depth 7 that is hundreds of MB per rank per
|
||||
* step; f16 would halve it. libr4d compiles both widths (`SDT`) and the f16 round-trip error is
|
||||
* ~5e-4 relative (elements are O(0.1)); vLLM's `--mamba-ssm-cache-dtype` is commonly float16.
|
||||
* It stays f32 because f16 changes the generated text. */
|
||||
* and a step reads a sequence's state and writes it back (under the anchor form once, whatever
|
||||
* the draft depth). libr4d compiles both widths (`SDT`, from the cache's dtype); the f16
|
||||
* round trip is ~5e-4 relative (elements are O(0.1)). f16 halves the state pool, its host
|
||||
* checkpoints and the state traffic, and changes the generated text, so f32 is the default. */
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
sd.dtype = RAD_F32;
|
||||
sd.dtype = ctx->state_dtype == RAD_F16 ? RAD_F16 : RAD_F32;
|
||||
if (sd.dtype == RAD_F16) rad_note(b, "GDN state cache f16 (--state-cache-dtype f16)");
|
||||
sd.n_head_kv = gc.n_head_v;
|
||||
sd.state_dim[0] = gc.head_v;
|
||||
sd.state_dim[1] = gc.head_k;
|
||||
@@ -717,6 +738,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
/* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */
|
||||
mc.calib = calib_dir() != nullptr ? 1 : 0;
|
||||
/* Each rank holds a width slice of every expert (n_ff is per rank), so its down
|
||||
* projection's Hessian would be of the slice, without the cross terms between slices. */
|
||||
if (mc.calib && g.world > 1) {
|
||||
fprintf(stderr, "radiance: qwen35moe: calibration (RADIANCE_CALIB_DIR) runs at one "
|
||||
"rank; at %d ranks each holds a slice of every expert's width, and "
|
||||
"the down projection's Hessian would be of the slice\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a
|
||||
* container with four-bit experts is served in that format. */
|
||||
{
|
||||
@@ -846,7 +875,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
/* Always exact, not g.wire_exact: this all_reduce sums disjoint rows (each token's embedding
|
||||
* comes from one rank, the others contribute zero), so a lossy wire would only add error.
|
||||
* min_bytes stays 0 for the same reason. */
|
||||
* min_bytes stays 0 for the same reason.
|
||||
*
|
||||
* The second lane's window opens here and closes after the final norm (rad_lane1_window_begin):
|
||||
* the embedding's reduction and the pipelined prefill's boundaries are declared inside it, so
|
||||
* the concurrent buffers stay live only there and the drafter and the heads can share their
|
||||
* bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -854,6 +889,35 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough.
|
||||
* Its second lane needs a narrow `overlap` all-reduce beside the GEMMs; two ranks is the only
|
||||
* rank count where the step has been timed against the serial one, so elsewhere prefill stays
|
||||
* serial. The second lane touches the residual stream, the normed input in both forms and the
|
||||
* bounds, so those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the
|
||||
* first lane, pipe_taps); the bounds also because no declared op reads them, which would leave
|
||||
* a transient dead before the kernels that take them raw.
|
||||
*
|
||||
* Not on a trunk whose norms write rotated int8 codes (qwen35_w8a8 where libr4d serves the
|
||||
* `_had_quant_i8g` forms, a_h.q8_fed): the boundary norms on the second lane
|
||||
* (NormQuantFP8::step_plain) issue the E4M3 pair only, so such a trunk prefills serially. */
|
||||
if (m.a_h.q8_fed) {
|
||||
if (g.world == 2 && g.max_tok >= kPipeMinRows && ctx->rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: the pipelined prefill stays off on this trunk: its norms "
|
||||
"write rotated int8 codes, which the pipeline's boundary norms do not\n");
|
||||
} else {
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.q));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.s));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ---- the layers. */
|
||||
/* The rope table's fill, declared before the layers that read it. If it does not resolve,
|
||||
* `aw.cos_sin` is cleared and every attention block uses its unfused norm + rope pair. Its band
|
||||
@@ -896,6 +960,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill runs every block's all-reduce beside the other piece's work, so
|
||||
* each declares its collective a second time at `overlap` 1, a launch that leaves the CUs
|
||||
* to that work (the lane rows of libr4d/r4d_rows.cpp); the fused all-reduce and norm
|
||||
* would hold the card while it waits on the link. */
|
||||
lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = m.pipe_on ? 1 : 0;
|
||||
#endif
|
||||
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
|
||||
@@ -960,6 +1031,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.a_h.x});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
@@ -1130,6 +1202,235 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* At two ranks every layer of a prefill chunk makes two all-reduces, each folded into the next
|
||||
* block's norm (layer_fold) and each in a hard chain on one stream: block -> all-reduce + norm ->
|
||||
* block. On a 2048-token chunk they are about a fifth of the step, nearly all of it the link, with
|
||||
* nothing beside them.
|
||||
*
|
||||
* A step of one prefill sequence of at least kPipeMinRows tokens is cut into two pieces of about
|
||||
* half (pipe_rows), each the chunk a narrower batch makes. Every block runs a piece at a time on
|
||||
* the first lane, and the work between two blocks runs a piece at a time on the second: the
|
||||
* block's all-reduce at `overlap` 1 (a narrow launch that leaves the CUs to the compute beside it;
|
||||
* the fused all-reduce and norm would hold its blocks on the card while it waits on the link and
|
||||
* slow the GEMM beside it by a third), then the next block's plain norm, and after a feed-forward
|
||||
* that keeps its add, the add and the final norm (the drafter taps go on the first lane, pipe_taps).
|
||||
*
|
||||
* mixer the delta net and the dense attention run whole a piece at a time and hand the
|
||||
* first piece off behind its out projection (ArPieces), so its boundary runs beside
|
||||
* the second piece's mixer;
|
||||
* ffn its first piece runs beside the mixer's second boundary, its second beside its own
|
||||
* first boundary; the next mixer's first piece runs beside its second.
|
||||
*
|
||||
* A piece computes the bytes the narrower chunk does: every op is per row, both pieces sit in the
|
||||
* band of a whole step (pipe_rows), the all-reduce reduces within a row, the delta net carries its
|
||||
* state through the cache as between two chunks, and each attention piece sees the cache up to its
|
||||
* own end. The narrow all-reduce and the plain norm write the fused op's bytes, so a pipelined
|
||||
* step is bit for bit the serial one.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold: every collective of the step is on it, the
|
||||
* embedding's included; none carries a device-wide arrival counter (the all-reduce's sequence
|
||||
* counters order its own launches, which one lane keeps in order); and the buffers it touches left
|
||||
* the sharing pool at declare (the drafter taps it does not touch: pipe_taps). */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* Lane 0 waits for everything issued on lane 1 so far. */
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the mixer of layer l, 2l + 1 its feed-forward) for rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t T, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
if (s % 2 == 0) {
|
||||
if (l.full) l.attn.issue_ar(c, r0, n);
|
||||
else l.gdn.issue_ar(c, r0, n);
|
||||
l.mlp.nq_h.step_plain(c, T, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.issue_ar(c, r0, n);
|
||||
if (l.mlp.op_add)
|
||||
RAD_ISSUE_N(c, l.mlp.op_add, n, brow_slice(m.b_x, r0, n, g.n_embd),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd), brow_slice(m.b_x, r0, n, g.n_embd));
|
||||
if (li + 1 < (int64_t)m.layers.size()) {
|
||||
const Layer& nx = m.layers[(size_t)li + 1];
|
||||
(nx.full ? nx.attn.nq_h : nx.gdn.nq_h).step_plain(c, T, r0, n);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_final_norm, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out_norm),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd));
|
||||
}
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its add is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* A mixer's first piece is done (ArPieces): lane 0 takes the previous block's second boundary
|
||||
* before the second piece (and the previous layer's second-piece taps behind it), and lane 1 this
|
||||
* block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t T = 0, s = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.T, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed. Copied on the
|
||||
* step's stream ahead of every layer from the pinned table, whose rows never change, so a captured
|
||||
* step replays the same copy. */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
/* A prefill step wide enough that runs serially says why, once, so a deployment that never
|
||||
* pipelines does not look like one that gains nothing from it. */
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions) return serial("no positions");
|
||||
if (rope_mixed(batch) || batch->n_mm_rows > 0) return serial("media rows in the step");
|
||||
if (dbg_resid_on()) return serial("residual debugging is on");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d) {
|
||||
/* Not a rank-local fallback to the serial step: the other rank would pipeline, and the two
|
||||
* would issue different collectives. Fail the step, as gemma3 does. */
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
const int64_t R = pipe_rows(T);
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.cu = d; pc.in_ready = true;
|
||||
for (const Layer& l : m.layers) {
|
||||
if (!(l.full ? l.attn.takes_pieces(batch, &pc) : l.gdn.takes_pieces(batch, &pc)))
|
||||
return serial(l.full ? "an attention block cannot run in pieces"
|
||||
: "a delta-net block cannot run in pieces");
|
||||
/* Every boundary issues its block's all-reduce itself, narrow, then the plain norm. */
|
||||
if (!(l.full ? l.attn.op_ar_ov : l.gdn.op_ar_ov) || !l.mlp.op_ar_ov)
|
||||
return serial("a block declares no overlap all-reduce");
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(3 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl) {
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[3 * t] = 0;
|
||||
m.pipe_tbl[3 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[3 * t + 2] = (int32_t)t;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Everything above depends only on the batch and the build, the same on every rank; what
|
||||
* follows is this rank's own, and falling back to the serial step here would leave the other
|
||||
* rank pipelining, the two issuing different collectives on the shared all-reduce instance
|
||||
* (a hang or a wrong sum). So it fails the step. */
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 3 * T, 3 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every
|
||||
* other collective (the norm takes the reduction where the wire is exact). */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar && !ar_wire_is_exact(g, T))
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
if (L > 0) (m.layers[0].full ? m.layers[0].attn.nq_h : m.layers[0].gdn.nq_h).step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
|
||||
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, T, 2 * li};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
if (l.full) l.attn.step(c, batch, false, &pc);
|
||||
else l.gdn.step(c, batch, false, &pc);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "qwen35: a mixer did not run its two pieces in a pipelined prefill "
|
||||
"step (pipe_ready and the block's takes_pieces disagree)");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li, R, T - R); });
|
||||
l.mlp.body(c, T, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, 0, R); });
|
||||
l.mlp.body(c, T, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.a_h.x, T), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
@@ -1168,6 +1469,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
#endif
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
@@ -1242,6 +1552,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
|
||||
out->state_f16_ok = 1;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash2")) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its
|
||||
* Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR).
|
||||
*
|
||||
* ============================== THE SHAPE, AT 1.7B ==============================
|
||||
* ============================== The shape, at 1.7B ==============================
|
||||
*
|
||||
* audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three
|
||||
* Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel ->
|
||||
@@ -23,7 +23,7 @@
|
||||
* q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6,
|
||||
* vocab 151936, the lm_head tied to the embedding.
|
||||
*
|
||||
* ============================== WHAT IS EASY TO GET WRONG ==============================
|
||||
* ============================== What is easy to get wrong ==============================
|
||||
*
|
||||
* Each second is convolved on its own. The core lays a clip out so one convolution over it does
|
||||
* that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose
|
||||
|
||||
@@ -174,6 +174,10 @@ struct Model {
|
||||
rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0;
|
||||
rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0;
|
||||
rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0;
|
||||
/* --draft-coupling: [max_seqs] draws staged before the serial passes and [max_spec,
|
||||
* max_seqs] states read back after them. PERSIST: the engine writes them from the host and the
|
||||
* head writes the states on the card, across a step boundary. */
|
||||
rad_buf b_mtp_couple_draws = 0, b_mtp_couple_state = 0;
|
||||
rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0;
|
||||
|
||||
HcEnter enter;
|
||||
@@ -1261,6 +1265,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */
|
||||
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR});
|
||||
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR});
|
||||
|
||||
/* --draft-coupling (RadBuildCtx::draft_coupling). Q is the law of the 2-bit candidate
|
||||
* head's reranked top-8; a plain bf16 head leaves one candidate and nothing to couple
|
||||
* over. The engine checks the drafter shape (a linear serial chain). */
|
||||
if (ctx->draft_coupling) {
|
||||
if (!m.b_mtp_didx || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS) {
|
||||
rad_note(b, "--draft-coupling on requires the 2-bit candidate head's reranked "
|
||||
"top8 and max_spec 1..%d",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.b_mtp_couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_mtp_couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{g.max_spec, g.max_seqs,
|
||||
RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!m.b_mtp_couple_draws || !m.b_mtp_couple_state) return RAD_E_INVAL;
|
||||
rad_note(b, "MTP coupled: the head samples x~Q from its reranked top8 each round "
|
||||
"(FP64), and the sampler couples the target's own draw to it; %lld "
|
||||
"round(s), fixed-seed tokens are NOT preserved",
|
||||
(long long)g.max_spec);
|
||||
}
|
||||
}
|
||||
|
||||
MtpHcBlock::Wire tw{};
|
||||
@@ -1270,6 +1298,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum;
|
||||
tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
|
||||
tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath;
|
||||
tw.couple_draws = m.b_mtp_couple_draws; tw.couple_state = m.b_mtp_couple_state;
|
||||
/* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a
|
||||
* second set would be 150 MiB). Only the wide stream and the carry are its own, since
|
||||
* they must survive the round that produced them. */
|
||||
@@ -1555,7 +1584,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
if (p == K - 1) wait1();
|
||||
l.hc_ffn.write(c, T, r0(p), rn(p));
|
||||
/* The projection of this piece, before the next layer reads it. */
|
||||
l.proj.step(c, r0(p), rn(p));
|
||||
l.proj.step(c, batch, r0(p), rn(p));
|
||||
if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p));
|
||||
}
|
||||
if (ple_next) {
|
||||
@@ -1600,7 +1629,7 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
l.mlp.step(c, batch);
|
||||
l.hc_ffn.write(c, T, 0, T);
|
||||
/* The request's control vector, on the stream the write just finished. */
|
||||
l.proj.step(c, 0, T);
|
||||
l.proj.step(c, batch, 0, T);
|
||||
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
|
||||
}
|
||||
}
|
||||
@@ -1677,6 +1706,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The gated residual applies a control vector after every block's write (HcProject). */
|
||||
out->control_vector_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/unlimitedocr_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the
|
||||
# same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(unlimitedocr_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(unlimitedocr_bf16 architectures
|
||||
SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/unlimitedocr_bf16.cpp)
|
||||
@@ -0,0 +1,247 @@
|
||||
/* attn_llama.h -- one plain multi-head attention block, bf16 operands, paged KV. PRIVATE to
|
||||
* arch/unlimitedocr_bf16 (the arch/qwen35_bf16 + siglip2.h precedent: a header beside the plugin
|
||||
* that composes it).
|
||||
*
|
||||
* rmsnorm -> q gemm, k gemm, v gemm -> rope(q), rope(k)
|
||||
* -> kv_store -> paged attention (causal) -> o gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* It is rad_block_attn_gated.h with the Qwen3.5-specific parts removed, and the removals are the
|
||||
* model: Unlimited-OCR's decoder is a plain Llama-MoE (modeling_deepseekv2.py's
|
||||
* SlidingWindowLlamaAttention is MHA with `use_mla: false`), so
|
||||
*
|
||||
* * there is NO output gate: `q_proj` is [n_embd, n_head*head_dim] and holds only the query, so
|
||||
* no de-interleaving, no `sigmoid`, no `mul`;
|
||||
* * there is NO per-head q/k norm: the config's `qk_nope_head_dim`/`qk_rope_head_dim` are 0 and
|
||||
* the reference rotates the projections straight;
|
||||
* * the rotary is FULL head_dim (rot = head_dim = 128) and NeoX-half (`rotate_half` in the
|
||||
* reference), not partial, not mrope;
|
||||
* * q, k and v are three [1280, 1280] projections fused into ONE stacked-rows GEMM: the
|
||||
* rank-local q|k|v weight rows are staged once into a PERSIST plane, and q, k and v are
|
||||
* column views of one fused output plane (RadOperand::cols, abi/rad_runtime.h) that the
|
||||
* rope, kv_store and attention readers walk by row pitch -- the rad_block_attn_gated.h
|
||||
* argument against a fused [k|v] row does not apply to the stacked-rows form.
|
||||
*
|
||||
* Everything the gated block gets right about paged KV is copied through unchanged: the attention
|
||||
* declared BEFORE the store so block_size derives from the resolved kernel, the ranged `q_len`
|
||||
* band, the ragged-step cu_seqlens, the collective emitted by the plugin and not the core.
|
||||
*/
|
||||
#ifndef UNLIMITEDOCR_ATTN_LLAMA_H
|
||||
#define UNLIMITEDOCR_ATTN_LLAMA_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnLlamaBF16 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim + 2*kv_dim] fused q|k|v plane; q, k, v are the
|
||||
* column views [0, q_dim), [q_dim, q_dim+kv_dim), [q_dim+kv_dim, ...) */
|
||||
rad_buf qs = 0; /* [max_tok, q_dim] dense q lifted out of the fused plane for
|
||||
* attn_paged, whose kernels read q only contiguous (see step) */
|
||||
rad_buf k = 0; /* the same plane: the rope/kv_store readers take the k columns */
|
||||
rad_buf v = 0; /* the same plane: the v columns */
|
||||
rad_buf attn = 0; /* [max_tok, q_dim] */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
int64_t n_rot = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_qkv = 0, w_o = 0;
|
||||
rad_op op_norm = 0, op_qkv = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_qs = 0; /* cast: lift the fused plane's q slice into dense qs */
|
||||
int qrow = 0; /* attn_paged_qrow served: q is read in place at its pitch */
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The KV-head-replication refusal rad_block_attn_gated.h states: this block declares its k/v
|
||||
* with the plain even row-shard and passes no row span, so a world above the KV head count
|
||||
* would hand a rank half of one KV head. Say so at declare. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
/* The convert-time q|k|v fusion, the gate_up form rad_block_mlp.h states: one weight, one
|
||||
* GEMM, one movement unit; `row_parts` keeps the row-shard on q_local|k_local|v_local
|
||||
* boundaries so the column views stay exact per rank. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.attn_qkv.weight", l), { src.q, src.k, src.v }, 0));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_qkv = decl_w(b, nm.f("blk.%d.attn_qkv.weight", l), RAD_BF16,
|
||||
{q_dim + 2 * kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{q_dim, kv_dim, kv_dim});
|
||||
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
/* One GEMM over the fused [q|k|v] rows: N = q_dim + 2*kv_dim, the readers below take the
|
||||
* q, k and v column views of `w.q`. Same K, same per-column tile as the three-GEMM form,
|
||||
* so the bf16 outputs are bit-identical; the win is one launch, not arithmetic. */
|
||||
op_qkv = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim + 2 * kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qkv)),
|
||||
{w.h}, {w.q});
|
||||
|
||||
/* Full-head rotary, NeoX halves: the reference's rotate_half. The q call names n_head query
|
||||
* heads and no kv heads (the buffers are separate); the k call names the kv heads. */
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
/* attn_paged's prefill kernels read q only contiguous, and here q is a column slice of the
|
||||
* fused q|k|v plane (row pitch q_dim + 2*kv_dim). attn_paged_qrow reads that pitch in place
|
||||
* (libr4d's qrow rows cover head_dim 128/256/512). It is a separate op so no `--kernels` order
|
||||
* can hand the slice to a kernel that reads q only dense (gemma4.cpp:1001-1023). Where the op
|
||||
* is not declared or does not resolve, the slice is lifted into dense qs first. The cast is
|
||||
* always declared but issued only in the fallback. */
|
||||
op_qs = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.qs});
|
||||
auto declare_attn = [&](const char* op, rad_buf q) {
|
||||
/* Declared before kv_store so block_size derives from the resolved attention kernel (spec
|
||||
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the
|
||||
* plain causal rule through the R-SWA ring: the ring's visible set is the block table's
|
||||
* job (the runtime window prunes the table, not the kernel), so no re-declaration. */
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{q}, {w.attn});
|
||||
};
|
||||
if (rad_op_declared(b, "attn_paged_qrow") != 0)
|
||||
op_attn = declare_attn("attn_paged_qrow", w.q);
|
||||
if (op_attn) {
|
||||
qrow = 1;
|
||||
} else {
|
||||
qrow = 0;
|
||||
op_attn = declare_attn("attn_paged", w.qs);
|
||||
}
|
||||
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
op_o = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_o)),
|
||||
{w.attn}, {w.h});
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_qkv, brows(w.h, T), RAD_W(w_qkv), brows(w.q, T));
|
||||
|
||||
/* q, k and v are column views of the fused plane, walked by its row pitch: the rope and
|
||||
* kv_store kernels take the slice's pitch (r4d_rows_pitch). Attention reads the q slice in
|
||||
* place when attn_paged_qrow is served; otherwise it needs q dense, so the slice is lifted
|
||||
* into qs after rope and before the store. */
|
||||
RAD_ISSUE(c, op_rope_q, bcol(w.q, 0, g.q_dim(), T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, bcol(w.q, g.q_dim(), g.kv_dim(), T), rope_posmc(g, batch, T));
|
||||
|
||||
if (op_qs) RAD_ISSUE(c, op_qs, bcol(w.q, 0, g.q_dim(), T), brows(w.qs, T));
|
||||
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
bcol(w.q, g.q_dim(), g.kv_dim(), T),
|
||||
bcol(w.q, g.q_dim() + g.kv_dim(), g.kv_dim(), T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
qrow ? bcol(w.q, 0, g.q_dim(), T) : brows(w.qs, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* UNLIMITEDOCR_ATTN_LLAMA_H */
|
||||
@@ -0,0 +1,553 @@
|
||||
/* unlimitedocr_bf16 -- baidu/Unlimited-OCR's decoder: a small Llama-MoE, bf16 weights and bf16
|
||||
* activations.
|
||||
*
|
||||
* Scope: the text trunk plus the DeepEncoder vision tower
|
||||
* (arch/common/rad_block_sam.h: SAM ViT-B/16 -> map -> CLIP ViT-L/14 -> the projector
|
||||
* -> the 273-row layout of a 1024 view / 110 rows of a 640 tile, declared with
|
||||
* rad_declare_encoder(RAD_MM_IMAGE), patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower
|
||||
* serves both view geometries the processor stages -- the gundam mode's 640 tiles and global
|
||||
* view, and the base mode's pages -- as two op sets over the same weights, the 40 grid's absolute
|
||||
* position tables bicubic+antialias resamples of the checkpoint's (arch/common/rad_resample.h).
|
||||
* The tower's weights are mapped always; its ops and the encoder pass are declared only when
|
||||
* SAM's `sam_attn` op resolves, because no existing op
|
||||
* can carry the decomposed rel_pos_h/rel_pos_w attention bias (rad_block_sam.h's header states the
|
||||
* op and why). Without it this plugin is the text-only trunk and refuses images by name. The
|
||||
* decoder's KV is one RAD_KV_RING group with the checkpoint's `sliding_window_size` (128), the
|
||||
* reference's own R-SWA: prefill is fully causal, and from the end of the prefill the ring of the
|
||||
* last W generated tokens is appended to the prompt (`SlidingWindowLlamaAttention`, which keeps
|
||||
* the prompt as reference and overwrites ring slots in place). The checkpoint's windowed
|
||||
* no-repeat-ngram ban is the sampler's `sample_ngram_ban` stage.
|
||||
*
|
||||
* ============================== THE SHAPE (config.json) ==============================
|
||||
*
|
||||
* 12 layers, hidden 1280, 10 heads x 128 head_dim, 10 kv-heads (MHA, `use_mla: false` -- the
|
||||
* DeepseekV2 class names in the repo are packaging, the graph is Llama)
|
||||
* full rotary over head_dim, theta 10000, plain RMSNorm eps 1e-6 (NOT 1 + w)
|
||||
* vocab 129280, lm_head TIED to embed_tokens (the checkpoint ships both tensors)
|
||||
* layer 0 dense (first_k_dense_replace 1, inter 6848); layers 1..11 MoE:
|
||||
* 64 routed experts (moe_intermediate_size 896), top-6, scoring softmax,
|
||||
* norm_topk_prob False, routed_scaling_factor 1.0 -- an ordinary softmax gate,
|
||||
* 2 shared experts packed as ONE dense MLP 2x896 = 1792 wide, summed ungated
|
||||
*
|
||||
* The MoE block is arch/common/rad_block_moe_fp8.h in its plain-bf16 expert mode (probe() reads
|
||||
* format 3 off the first expert's encoding), declared EXTERNAL-INPUT (src.norm null): its
|
||||
* post-attention norm is declared by this plugin because the shared expert reads the SAME normed
|
||||
* input and the block's gather overwrites that input with the routed delta (`h.x` is the
|
||||
* fold target). The shared arm therefore lives here: gate|up -> silu_mul -> down -> add, beside
|
||||
* the routed arm, exactly `y = y + shared_experts(x)` in modeling_deepseekv2.py:627.
|
||||
*
|
||||
* The attention is this plugin's private attn_llama.h: the gated bf16 block minus the output gate
|
||||
* and the q/k head norms, which this model does not have.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_sam.h>
|
||||
|
||||
#include "attn_llama.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace unlimitedocr_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
int dense = 0; /* 1 = the first_k_dense layer, plain SwiGLU */
|
||||
AttnLlamaBF16 attn;
|
||||
MlpBF16 mlp; /* dense layers */
|
||||
MoeFP8 moe; /* routed layers */
|
||||
/* The routed layer's external norm and the plugin-owned shared arm: the gain, the two dense
|
||||
* linears' weights, and the ops. Per layer -- the ACTIVATION buffers are shared across the
|
||||
* layers (spec §8) and the ops are declared per layer, as every block here does. */
|
||||
rad_weight w_norm = 0, w_sh_gate_up = 0, w_sh_down = 0;
|
||||
rad_op op_moe_norm = 0; /* x -> h.x, the MoE block's external prepared input */
|
||||
rad_op op_sh_gu = 0, op_sh_act = 0, op_sh_down = 0, op_sh_ar = 0, op_sh_add = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t n_rot = 0;
|
||||
int64_t first_dense = 1; /* layers [0, first_dense) are dense MLPs */
|
||||
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* the residual stream and the vocabulary edges */
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
/* attention */
|
||||
rad_buf b_qkv = 0, b_qs = 0, b_attn = 0;
|
||||
/* dense feed-forward (layer 0) */
|
||||
rad_buf b_gate_up = 0, b_ffn = 0;
|
||||
/* routing -- one row per token */
|
||||
rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_eoff = 0, b_ecnt = 0;
|
||||
/* expert planes -- one row per (token, slot), a pass tall */
|
||||
rad_buf b_sorted = 0, b_egu = 0, b_edn = 0;
|
||||
ActFP8 a_eff{};
|
||||
/* the shared arm reads the block's prepared input (h) before the gather overwrites it, then
|
||||
* the dense linear's planes */
|
||||
rad_buf b_sgu = 0, b_sff = 0, b_sout = 0;
|
||||
|
||||
MoeFP8::Config moecfg{};
|
||||
/* The DeepEncoder vision tower (arch/common/rad_block_sam.h). Its weights are mapped always;
|
||||
* its ops and the encoder pass only when SAM's attention op resolves. */
|
||||
DeepEncoder enc;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_mm = 0, op_final_norm = 0, op_gather = 0,
|
||||
op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode,
|
||||
* and the shared expert must read the same normed row the routed experts do; the block's gather
|
||||
* folds the routed delta into h.x, so the shared arm is issued while h.x still holds the normed
|
||||
* row, BEFORE the block. */
|
||||
static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) {
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
|
||||
const char* wname = nm.f("blk.%d.ffn_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, wname, nm.ckpt("model.layers.%lld.post_attention_layernorm.weight",
|
||||
(long long)l)));
|
||||
lay.w_norm = decl_w(b, wname, RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
const int64_t n_ff_sh = m.moecfg.n_ff_shared;
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l),
|
||||
{ nm.ckpt("model.layers.%lld.mlp.shared_experts.gate_proj.weight",
|
||||
(long long)l),
|
||||
nm.ckpt("model.layers.%lld.mlp.shared_experts.up_proj.weight",
|
||||
(long long)l) }, 0));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down_shexp.weight", l),
|
||||
nm.ckpt("model.layers.%lld.mlp.shared_experts.down_proj.weight",
|
||||
(long long)l)));
|
||||
lay.w_sh_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), RAD_BF16,
|
||||
{2 * n_ff_sh, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{n_ff_sh, n_ff_sh});
|
||||
lay.w_sh_down = decl_w(b, nm.f("blk.%d.ffn_down_shexp.weight", l), RAD_BF16,
|
||||
{g.n_embd, n_ff_sh},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
/* The routed arm's own norm: x -> h.x, the buffer the block takes as its prepared input and
|
||||
* the buffer its gather writes the routed delta back into. */
|
||||
lay.op_moe_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
|
||||
lay.op_sh_gu = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * n_ff_sh),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_sh_gate_up)),
|
||||
{m.b_h}, {m.b_sgu});
|
||||
lay.op_sh_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n_ff_sh),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_sgu}, {m.b_sff});
|
||||
lay.op_sh_down = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", n_ff_sh), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_sh_down)),
|
||||
{m.b_sff}, {m.b_sout});
|
||||
/* Column-sharded like the dense MLP's down_proj: every rank holds a partial sum, reduced
|
||||
* once per step before the residual add. */
|
||||
if (g.world > 1)
|
||||
lay.op_sh_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_sout}, {m.b_sout});
|
||||
lay.op_sh_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_sout}, {m.b_x});
|
||||
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;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* Plain RMSNorm (DeepseekV2RMSNorm is x_hat * w), not the GemmaRMSNorm `1 + w`. */
|
||||
g.wadd = 0.0f;
|
||||
/* The linears are the checkpoint's own bf16: no scale planes, no quantised activations. The
|
||||
* MoeFP8 block in particular requires it (its external-input check reads it). */
|
||||
g.w_bf16 = true;
|
||||
|
||||
/* ---- geometry RadModelMeta does not name. */
|
||||
const int64_t n_expert_all = meta->n_expert > 0
|
||||
? meta->n_expert : rad_meta_geti(meta, "n_routed_experts", 0);
|
||||
const int64_t top_k = meta->n_expert_used > 0
|
||||
? meta->n_expert_used : rad_meta_geti(meta, "num_experts_per_tok", 0);
|
||||
const int64_t moe_ff = rad_meta_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_shared = rad_meta_geti(meta, "n_shared_experts", 0);
|
||||
m.first_dense = rad_meta_geti(meta, "first_k_dense_replace", 1);
|
||||
if (n_expert_all <= 0 || top_k <= 0 || top_k > n_expert_all || moe_ff <= 0 ||
|
||||
m.first_dense < 0 || m.first_dense >= g.n_layer) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: the container does not describe the routed "
|
||||
"decoder (n_routed_experts %lld, num_experts_per_tok %lld, "
|
||||
"moe_intermediate_size %lld, first_k_dense_replace %lld of %lld layers)\n",
|
||||
(long long)n_expert_all, (long long)top_k, (long long)moe_ff,
|
||||
(long long)m.first_dense, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The gate is an ordinary softmax top-k. A container that states a scheme this plugin does not
|
||||
* serve is refused by name rather than served as a softmax gate (spec §17). */
|
||||
if (const char* sf = rad_meta_gets(meta, "scoring_func", nullptr); sf && *sf &&
|
||||
std::strcmp(sf, "softmax") != 0) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: scoring_func '%s' is not implemented; the gate "
|
||||
"this plugin declares is the softmax top-k\n", sf);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double rsf = rad_meta_getf(meta, "routed_scaling_factor", 1.0);
|
||||
if (!(rsf > 0.0) || rsf != 1.0) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: routed_scaling_factor %g is not 1.0 and this "
|
||||
"plugin declares no router output scale\n", rsf);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t topk_group = rad_meta_geti(meta, "topk_group", 1);
|
||||
const int64_t n_group = rad_meta_geti(meta, "n_group", 1);
|
||||
if (topk_group != 1 || n_group != 1) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: grouped routing (n_group %lld, topk_group %lld) "
|
||||
"is not implemented; the reference's greedy top-k over one group is\n",
|
||||
(long long)n_group, (long long)topk_group);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "use_mla", 0)) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: use_mla is set; this decoder is the MHA graph "
|
||||
"(q/k/v projections), not the DeepSeek MLA\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The full-head rotary: no rope_parameters object is present, so yarn_from answers
|
||||
* "default" and theta stays the container's (the reference default 10000). */
|
||||
m.n_rot = g.head_dim;
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the routed geometry. n_expert is NOT divided (every rank holds every expert and routes
|
||||
* identically); the intermediate width is. */
|
||||
MoeFP8::Config& mc = m.moecfg;
|
||||
mc.n_expert = n_expert_all;
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.top_k = top_k;
|
||||
int s;
|
||||
if ((s = divide_or_fail(moe_ff, g.world, "moe_intermediate_size", &mc.n_ff_exp)) < 0)
|
||||
return s;
|
||||
/* The shared experts are packed as ONE dense MLP n_shared x moe_ff wide (DeepseekV2Model:
|
||||
* `intermediate_size = moe_intermediate_size * n_shared_experts`), summed ungated. The
|
||||
* MoeFP8 shared arm is the SIGMOID-gated family's shape; this model's arm is declared by the
|
||||
* plugin (declare_moe_norm_and_shared) and the block declares none. */
|
||||
const int64_t sh_all = n_shared * moe_ff;
|
||||
mc.n_ff_shared = 0;
|
||||
int64_t n_ff_sh = 0;
|
||||
if (sh_all > 0 && (s = divide_or_fail(sh_all, g.world, "n_shared_experts width",
|
||||
&n_ff_sh)) < 0)
|
||||
return s;
|
||||
mc.norm_topk = rad_meta_geti(meta, "norm_topk_prob", 0) ? 1 : 0;
|
||||
const int64_t moe_rows = 2048;
|
||||
mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows;
|
||||
|
||||
/* ---- KV: one R-SWA ring group.
|
||||
*
|
||||
* The reference's `SlidingWindowLlamaAttention` keeps the prefill as reference and from the
|
||||
* prefill's end keeps the last `sliding_window_size` generated tokens in a ring it overwrites
|
||||
* in place, attending over both. RAD_KV_RING is that: paged like a window group, but the floor
|
||||
* is per sequence and armed at admission (`visible_lo = prefill length`), so a decode query
|
||||
* sees [0, prefill) U [prefill, prefill + W). Prefill itself stays fully causal, which is why
|
||||
* the attention op keeps `causal=1` and `window=0`: the visible set is the block table's job,
|
||||
* and `causal=0` would make a prefill chunk non-causal.
|
||||
*
|
||||
* A checkpoint that states no window gets the plain full cache, so the text trunk still
|
||||
* serves. Prefix caching and speculation switch off for the group automatically (a runtime
|
||||
* window's KV before the prompt end is not reusable and a draft cannot know where the ring
|
||||
* starts). */
|
||||
const int64_t sw_size = rad_meta_geti(meta, "sliding_window_size", 0);
|
||||
const int64_t win = sw_size > 0 ? sw_size : rad_meta_geti(meta, "sliding_window", 0);
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = win > 0 ? RAD_KV_RING : RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.window = win > 0 ? win : 0;
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* ---- activation buffers. */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype,
|
||||
{g.max_tok, g.q_dim() + 2 * g.kv_dim()});
|
||||
/* The dense q lifted out of the fused plane for attn_paged (attn_llama.h's cast). */
|
||||
m.b_qs = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
|
||||
const int64_t R = g.max_tok, K = mc.rows * mc.top_k;
|
||||
m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert_all});
|
||||
m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k});
|
||||
m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k});
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K});
|
||||
m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert_all + 1});
|
||||
/* PERSIST: its only reader, rad_route_report, is not a declared op. See qwen4exp_fp8. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST);
|
||||
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
|
||||
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
|
||||
|
||||
if (n_ff_sh > 0) {
|
||||
mc.n_ff_shared = n_ff_sh; /* sizes nothing in the block (arm null there); kept for
|
||||
the shared-arm ops below */
|
||||
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * n_ff_sh});
|
||||
m.b_sff = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, n_ff_sh});
|
||||
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
|
||||
}
|
||||
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
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));
|
||||
|
||||
/* ---- vocabulary edges. The lm_head is TIED: the checkpoint ships lm_head.weight, and a
|
||||
* release that ships only the embedding is served by the same map (first source present
|
||||
* wins). Both edges are row-sharded with the vocabulary (spec §9). */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
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_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* ---- the expert format: the checkpoint's plain bf16, read off the first routed layer's
|
||||
* first expert. A quantised container would be a sibling plugin's. */
|
||||
{
|
||||
MoeFP8::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts",
|
||||
(long long)m.first_dense);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)m.first_dense, probe_src, &mc));
|
||||
if (!mc.expert_bf16) {
|
||||
fprintf(stderr, "radiance: unlimitedocr_bf16 serves plain bf16 experts; layer %lld's "
|
||||
"expert 0 is quantised. Serve that container with its quantised "
|
||||
"plugin.\n", (long long)m.first_dense);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the DeepEncoder tower: map and declare its weights, then (when `sam_attn` resolves) its
|
||||
* ops and the encoder pass. Without that op the tower stays off and images are refused. */
|
||||
RAD_ARCH_TRY(m.enc.declare(b, ctx, nm, g.n_embd, (int)g.n_layer + 64));
|
||||
|
||||
/* A picture's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and
|
||||
* before the first block. Declared only when the tower is, since otherwise no step can carry
|
||||
* media rows. */
|
||||
if (m.enc.on)
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
AttnLlamaBF16::Wire aw{};
|
||||
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_qkv; aw.k = m.b_qkv; aw.v = m.b_qkv;
|
||||
aw.qs = m.b_qs;
|
||||
aw.attn = m.b_attn;
|
||||
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
|
||||
MoeFP8::Wire fw{};
|
||||
fw.x = m.b_x;
|
||||
fw.h.x = m.b_h; /* external input: the plugin's own rmsnorm writes it */
|
||||
fw.logits = m.b_rlogits; fw.ids = m.b_eids; fw.ew = m.b_ew;
|
||||
fw.eoff = m.b_eoff; fw.ecnt = m.b_ecnt;
|
||||
fw.sorted = m.b_sorted; fw.egu = m.b_egu;
|
||||
fw.eff.x = m.a_eff.x;
|
||||
fw.edn = m.b_edn; /* moe, sgu, sff, sout, sgate stay null: no block arm */
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l < m.first_dense) ? 1 : 0;
|
||||
|
||||
AttnLlamaBF16::Src as{};
|
||||
as.norm = nm.ckpt("model.layers.%lld.input_layernorm.weight", (long long)l);
|
||||
as.q = nm.ckpt("model.layers.%lld.self_attn.q_proj.weight", (long long)l);
|
||||
as.k = nm.ckpt("model.layers.%lld.self_attn.k_proj.weight", (long long)l);
|
||||
as.v = nm.ckpt("model.layers.%lld.self_attn.v_proj.weight", (long long)l);
|
||||
as.o = nm.ckpt("model.layers.%lld.self_attn.o_proj.weight", (long long)l);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, m.n_rot, aw, as));
|
||||
|
||||
if (lay.dense) {
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", (long long)l);
|
||||
ms.gate = nm.ckpt("model.layers.%lld.mlp.gate_proj.weight", (long long)l);
|
||||
ms.up = nm.ckpt("model.layers.%lld.mlp.up_proj.weight", (long long)l);
|
||||
ms.down = nm.ckpt("model.layers.%lld.mlp.down_proj.weight", (long long)l);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
|
||||
} else {
|
||||
/* The block's norm, the shared arm and its linears, then the block. The block's norm
|
||||
* is declared by the plugin (external input) because its gather folds the routed
|
||||
* delta into h.x, and the shared arm reads its own copy of the normed row. */
|
||||
RAD_ARCH_TRY(declare_moe_norm_and_shared(b, m, (int)l));
|
||||
|
||||
MoeFP8::Src fs{};
|
||||
fs.cfg = mc;
|
||||
fs.norm = nullptr; /* external: declared above */
|
||||
fs.router = nm.ckpt("model.layers.%lld.mlp.gate.weight", (long long)l);
|
||||
fs.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l);
|
||||
fs.shared = nullptr; /* the ungated shared arm lives in the plugin */
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, (int)l, fw, fs));
|
||||
}
|
||||
}
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_hout});
|
||||
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
rad_note(b, "rank %d/%d: %lld layers, layer 0 dense (n_ff %lld), layers %lld..%lld MoE: "
|
||||
"%lld experts top-%lld (softmax, norm_topk %d), shared arm %lld wide, "
|
||||
"n_head=%lld n_head_kv=%lld head_dim=%lld vocab=[%lld,%lld) tied head",
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)g.n_ff,
|
||||
(long long)m.first_dense, (long long)(g.n_layer - 1),
|
||||
(long long)mc.n_expert_all, (long long)mc.top_k, mc.norm_topk,
|
||||
(long long)mc.n_ff_shared,
|
||||
(long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim,
|
||||
(long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
|
||||
if (win > 0)
|
||||
rad_note(b, "R-SWA: the KV group is a runtime ring (RAD_KV_RING), window %lld tokens from "
|
||||
"the prefill's end (the reference's SlidingWindowLlamaAttention); prefill is "
|
||||
"fully causal, and prefix cache and speculation are off for it", (long long)win);
|
||||
else
|
||||
rad_note(b, "R-SWA: the checkpoint states no sliding_window_size, so the KV group is a "
|
||||
"plain full cache");
|
||||
/* Only when the container states the processor: gen-convert copies the checkpoint's
|
||||
* generation_config into `generation.*`, so a checkpoint without it gets no note. */
|
||||
const int64_t ng_n = rad_meta_geti(meta, "generation.no_repeat_ngram_size", 0);
|
||||
if (ng_n > 0)
|
||||
rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=%lld over "
|
||||
"the last %lld tokens -- served by the sample_ngram_ban stage, overridable "
|
||||
"per request (ngram_ban_n / ngram_window); temp-0 parity checks run with it off",
|
||||
(long long)ng_n,
|
||||
(long long)rad_meta_geti(meta, "generation.no_repeat_ngram_window_size", 0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
if (batch->enc) {
|
||||
m.enc.step(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
if (m.op_mm && batch->n_mm_rows > 0)
|
||||
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok));
|
||||
|
||||
for (const Layer& l : m.layers) {
|
||||
l.attn.step(c, batch);
|
||||
if (l.dense) {
|
||||
l.mlp.step(c, batch);
|
||||
} else {
|
||||
const int64_t T = batch->n_tok;
|
||||
/* The MoE block's norm (x -> h.x), then the shared arm beside the routed arm: both
|
||||
* read the same prepared input, so the shared arm is issued while h.x still holds the
|
||||
* normed row and BEFORE the block's gather overwrites it with the routed delta. The
|
||||
* two residual adds commute: x += shared, then the block's x += routed. */
|
||||
RAD_ISSUE(c, l.op_moe_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_sh_gu, brows(m.b_h, T), RAD_W(l.w_sh_gate_up),
|
||||
brows(m.b_sgu, T));
|
||||
RAD_ISSUE(c, l.op_sh_act, brows(m.b_sgu, T), brows(m.b_sff, T));
|
||||
RAD_ISSUE(c, l.op_sh_down, brows(m.b_sff, T), RAD_W(l.w_sh_down),
|
||||
brows(m.b_sout, T));
|
||||
if (l.op_sh_ar)
|
||||
RAD_ISSUE_N(c, l.op_sh_ar, T * m.g.n_embd, brows(m.b_sout, T), RAD_NONE);
|
||||
RAD_ISSUE(c, l.op_sh_add, brows(m.b_x, T), brows(m.b_sout, T), brows(m.b_x, T));
|
||||
l.moe.step(c, batch);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_final_norm,
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.b_h, batch->n_tok),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace unlimitedocr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0",
|
||||
"baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), "
|
||||
"bf16 weights and activations, full rotary MHA, with the DeepEncoder "
|
||||
"(SAM ViT-B + CLIP ViT-L) vision tower")
|
||||
#endif
|
||||
Reference in new issue
Block a user