radiance 1.4.0

- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
This commit is contained in:
Deadcode committed 2026-10-12 11:46:14 +02:00
1 parent d5b65cddc6
commit dc339b4cd2
153 files changed
+12956 -1067

No files matched your search

+19
View File
@@ -168,6 +168,11 @@ struct AttnGatedFP8 {
bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The pass's K and V into the cache and nothing else: no query, no attention, no output. What a
* pass that only leaves the layer's state behind asks for -- the MTP head's history pass over
* a prompt chunk with no row that drafts. The keys are the ones step() stores: the same
* projection, norm, rotation and store. */
void store_kv(RadCtx* c, const RadBatch* batch) const;
};
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -470,6 +475,20 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
return RAD_OK;
}
inline void AttnGatedFP8::store_kv(RadCtx* c, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
if (!ext_in) nq_h.step(c, T);
if (op_fill) return; /* the attention-zero rank holds no heads to store */
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
kp.step(c, w.h, w.k, T);
vp.step(c, w.h, w.v, T);
RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T));
RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_kv_store,
brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer));
}
inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
+2
View File
@@ -90,6 +90,8 @@ struct MlpFP8 {
const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers (MoeFP8::step_rows says who asks). */
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;
};
+49 -1
View File
@@ -387,6 +387,16 @@ struct MoeFP8 {
* `pff`, and down into the same `edn` rows the quantised down left zero. */
std::vector<int64_t> prot;
const char* prot_list = nullptr;
/* THE NEXT-LAYER EXPERT PREFETCH (rad_expert_prefetch). `xp_next` is the next routed layer, which
* this one predicts for at its router input -- the architecture links them once every layer is
* declared. `xp` is what this layer is to the one before it: its router, and each of the model's
* experts' unit -- the four handles its place's tables hold, and its place in the routing counts.
* Quantised experts only: a bf16 layer and the protected experts are not described, and a layer
* with no description is predicted for by nobody. */
const MoeFP8* xp_next = nullptr;
RadPrefetchNext xp{};
std::vector<rad_weight> xp_parts;
std::vector<int32_t> xp_count_at;
int64_t n_reg = 0;
/* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
@@ -461,6 +471,10 @@ struct MoeFP8 {
const Wire& wire, const Src& src, bool fold = false, bool add_out = true,
int ar_in = kArNone, bool ar_out_ = false);
void step(RadCtx* c, const RadBatch* batch) const;
/* The block over the first `T` rows of its buffers, which a pass that runs it for fewer rows
* than its batch has asks for: the MTP head's history pass, which reads the head's output only
* at its drafting rows. */
void step_rows(RadCtx* c, int64_t T) const;
/* One pass of at most `c.rows` tokens. */
void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const;
@@ -1469,6 +1483,29 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x, w.h.x}, {w.x});
/* The layer as the prefetch sees it, by the model's expert number -- what the router ranks. */
if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) {
const int64_t na = c.n_expert_all;
xp_parts.assign((size_t)(na * 4), 0);
xp_count_at.assign((size_t)na, -1);
for (int64_t s = 0; s < n_reg; ++s) {
const int64_t e = c.expert_base + reg[(size_t)s];
if (e < 0 || e >= na) continue;
xp_parts[(size_t)(e * 4 + 0)] = w_gu[(size_t)s];
xp_parts[(size_t)(e * 4 + 1)] = w_gus[(size_t)s];
xp_parts[(size_t)(e * 4 + 2)] = w_dn[(size_t)s];
xp_parts[(size_t)(e * 4 + 3)] = w_dns[(size_t)s];
xp_count_at[(size_t)e] = (int32_t)s;
}
xp.layer = layer;
xp.router = w_router;
xp.n_expert = na;
xp.top_k = c.top_k;
xp.n_parts = 4;
xp.parts = xp_parts.data();
xp.count_at = xp_count_at.data();
}
return RAD_OK;
}
@@ -1516,6 +1553,10 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* sharing pool (see declare), so issuing it ahead of its declared position moves no byte. */
/* THE ROUTED ARM. */
/* THE NEXT ROUTED LAYER'S PREDICTION, from this router's input, read in place behind the router
* on the compute stream (rad_expert_prefetch). A failure there costs the prediction, nothing else. */
if (xp_next && xp_next->xp.n_parts > 0)
(void)rad_expert_prefetch(c_, &xp_next->xp, w.h.x, r0, rows, g.n_embd);
/* THE COUNTS GO STRAIGHT INTO THE CORE'S ROW for this layer when it keeps one, so the
* report at the end of step() hands them over with no copy -- otherwise a card-local blit
* a routed layer, a whole dependent dispatch for a kilobyte. */
@@ -1564,6 +1605,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
* 2 * i + q, and each parity is its own pair of table operands; at four classes expert
* 4 * i + q, class q holding ceil((n_reg - q) / 4). */
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
/* The layer before predicted for this one: its copies go into the tables here, where they landed. */
(void)rad_expert_prefetch_step(c_, layer);
if (c.expert_bf16)
RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
@@ -1608,6 +1651,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
RAD_WTAB(w_dn[1], n_reg / 2), RAD_WTAB(w_dns[1], n_reg / 2),
brows(w.edn, rows * k));
/* This layer's streamed experts are read: the next one's copies cross the link from here. */
(void)rad_expert_prefetch_mark(c_);
/* THE PROTECTED EXPERTS, over the trailing run of the offsets: their sorted rows are the
* ones the quantised down GEMM above zeroed as past its live count, and the down GEMM
* here writes them -- after it, which the shared `edn` orders. */
@@ -1733,7 +1778,10 @@ inline void MoeFP8::calib_experts_pass(RadCtx* c_, int64_t slots) const {
}
inline void MoeFP8::step(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok;
step_rows(c_, batch->n_tok);
}
inline void MoeFP8::step_rows(RadCtx* c_, int64_t T) const {
for (int64_t r0 = 0; r0 < T; r0 += c.rows) {
const int64_t n = (T - r0 < c.rows) ? (T - r0) : c.rows;
pass(c_, T, r0, n);
+39 -32
View File
@@ -288,6 +288,24 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
{w.c}, {w.x});
RAD_ARCH_TRY(attn.declare(b, nm, g, l, kv, rotary_dim, w.attn, src.attn));
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of the residual stream `x` -- before the feed-forward,
* which then runs over those rows alone. Through `hout`, which is dead from the fc's read to
* the norm's write, because a gather in place could overwrite a row another sequence has yet to
* read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
RAD_ARCH_TRY(mlp.declare(b, nm, g, l, w.mlp, src.mlp));
op_norm = rw(b, RAD_OP(b, "rmsnorm",
@@ -297,22 +315,6 @@ inline int MtpBlockFP8<Ffn>::declare(RadBuilder* b, Names& nm, const Geom& geom,
RAD_WEIGHTS(w_norm)),
{w.x}, {w.hout});
/* DRAFT ROUND 1'S ROWS OUT OF A HISTORY PASS (RadBatch::draft_out_ids), one a drafting
* sequence in round order, to the front of `hout` -- where the lm_head reads a round's rows
* and round 2 reads its input. Through `x`, which is dead once the norm has read it, because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hout}, {w.x});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.x}, {w.hout});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The trunk's lm_head, over the head's hidden state. Banded at the logits buffer's own extent
* rather than at `rows`: it runs over one row a drafting sequence. */
op_logits = rw(b, RAD_OP(b, "logits_gemm",
@@ -435,27 +437,32 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES K AND V BEHIND, and they come from the
* block's input. The query, the attention, its output, the feed-forward, the norm and the
* lm_head compute the head's output, which only a drafting row reads -- and every prefill
* chunk but a prompt's last drafts nothing. `n_draft_out` is the batch's and the same on every
* rank, so a collective skipped here is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
attn.store_kv(c, batch);
return;
}
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
* attention above has stored them. The feed-forward, the norm and the lm_head compute the
* head's output, which only a drafting row reads -- and every prefill chunk but a prompt's
* last drafts nothing. `n_draft_out` is the batch's and the same on every rank, so a
* collective the feed-forward would run is skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
mlp.step(c, batch);
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
/* A history pass that drafts brings round 1's rows to the front first. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's output at any other row: the feed-forward, the norm and the lm_head
* would run over a whole prompt chunk for a handful of rows. So round 1's rows come to the
* front of `x` first, and everything after runs as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.x, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, L));
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.x), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hout, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hout, L), brows(w.x, L));
}
mlp.step_rows(c, L);
RAD_ISSUE(c, op_norm, brows(w.x, L), RAD_W(w_norm), brows(w.hout, L));
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
* whole: there is no row slice of it that means anything. */
+46 -34
View File
@@ -292,6 +292,22 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
false, false, kArNone, hc_attn.op_ar_write != 0));
if (src.qsa.qk_proj)
RAD_ARCH_TRY(qsa.declare(b, nm, g, l, src.qsa, w.qsa, w.attn.h, qsa_bk));
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids), before the
* feed-forward, which then runs over them alone: gathered into `hin`, one row a drafting
* sequence in round order, and copied back to the front of `hw`. Two ops and not one because a
* gather in place could overwrite a row another sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* The rotated expert input rides in this read, as it does on the trunk. */
HyperConn::Config mcfg = hc;
HyperConn::Wire mwire{w.hw, w.x, w.inj};
@@ -321,21 +337,6 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
/* ---- draft round 1's rows out of a history pass (RadBatch::draft_out_ids): gathered into the
* carry, one row a drafting sequence in round order, and copied back to the front of `hw` for
* the mixer. Two ops and not one because a gather in place could overwrite a row another
* sequence has yet to read. */
op_dsel = rw(b, RAD_OP(b, "gather_rows",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{w.hw}, {w.hin});
op_dback = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", HN),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.hin}, {w.hw});
if (!op_dsel || !op_dback) return RAD_E_INVAL;
/* ---- the head's own mixer: the connection with no write half, which collapses its wide
* stream to the one hidden state the lm_head reads. No fp8 twin -- that input is bf16. */
@@ -523,40 +524,51 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
RAD_W(w_fc_h), RAD_W(w_fc_e), brows(w.hw, T));
hc_attn.read(c, T, 0, T);
/* A HISTORY PASS THAT DRAFTS NOTHING ONLY LEAVES THE HEAD'S STATE BEHIND: the K and V of its
* rows and the indexer's block keys and tail, all of which come from the block's input. The
* query, the indexer's scores and selection, the attention, its output and everything after
* compute the head's stream, which only a drafting row reads. Every prefill chunk but a
* prompt's last is such a pass. `n_draft_out` is the batch's and the same on every rank, so
* the collectives skipped here are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) {
qsa.store(c, attn.w.h, batch);
attn.store_kv(c, batch);
return;
}
/* THE INDEXER RUNS FIRST, because the attention reads its selection. It can: this block's
* input is normed and quantised by the connection above, so `w.h` is already what it will be
* when the attention runs. */
qsa.step(c, attn.w.h, batch);
attn.step(c, batch);
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
* written above. Everything below computes the head's stream, which only a drafting row
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
* but a prompt's last is such a pass, so on those the head costs its attention alone.
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
* are skipped on all of them. */
if (r < 0 && batch->n_draft_out <= 0) return;
hc_attn.write(c, T, 0, T);
hc_mlp.read(c, T, 0, T);
mlp.step(c, batch);
hc_mlp.write(c, T, 0, T);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step. A history pass that drafts takes round 1's rows out of its own
* -- into the carry, and back to the front of `hw` for the mixer below. */
int64_t L = T; /* the rows the lm_head runs over */
/* A HISTORY PASS THAT DRAFTS GOES ON WITH ITS DRAFTING ROWS ALONE. They are round 1, and
* nothing reads the head's stream at any other row: the experts, their connection and the
* lm_head would run over a whole prompt chunk for a handful of rows. So round 1's rows come out
* of `hw` first -- gathered into `hin` and copied back to its front, two ops because a gather
* in place could overwrite a row another sequence has yet to read -- and everything after runs
* as a pass of those rows. */
int64_t L = T; /* the rows the stream goes on with */
if (r < 0) {
L = batch->n_draft_out;
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
brows(w.hin, L));
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
} else if (r < depth) {
RAD_ISSUE_N(c, op_carry, T, brows(w.hw, T), brows(w.hin, T));
}
hc_mlp.read(c, L, 0, L);
mlp.step_rows(c, L);
hc_mlp.write(c, L, 0, L);
/* THE CARRY, and only where a round after this one will read it. The last round of a group
* is followed by a trunk step; a history pass is round 1, followed by round 2 when the
* deployment drafts deeper. */
if (r < 0 ? depth > 1 : r < depth)
RAD_ISSUE_N(c, op_carry, L, brows(w.hw, L), brows(w.hin, L));
mixer.read(c, L, 0, L);
if (q2) {
/* `dsum` is GROUP-major [n_embd/group][ceil(L/16)*16] and not row-major, so it is passed
+51 -28
View File
@@ -154,6 +154,11 @@ struct QsaIndexer {
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg,
const Wire& wire, const ActFP8& in, rad_kvgroup* bk);
void step(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
/* The block keys and the tail of the pass's rows and nothing else: no query, no score, no
* selection. What a pass that only leaves the layer's state behind asks for (see
* AttnGatedFP8::store_kv); the stores are the ones step() makes. */
void store(RadCtx* c, const ActFP8& in, const RadBatch* batch) const;
bool store_keys(RadCtx* c, const RadBatch* batch) const;
};
inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
@@ -314,38 +319,16 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
return RAD_OK;
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
/* THE KEYS A PASS LEAVES BEHIND: the block keys of the blocks its rows complete and the tail of
* raw keys after them, out of the projection's raw-key head. False when the step carries no batch
* for the indexer's groups. */
inline bool QsaIndexer::store_keys(RadCtx* c_, const RadBatch* batch) const {
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
const int64_t koff = qw; /* the raw-key head, after the query heads */
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
const int64_t koff = c.heads * c.head_dim; /* the raw-key head, after the query heads */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
const RadKVGroupBatch* tlb = kv_batch(batch, c.kv_tail);
if (!bkb || !atb || !tlb) return;
if (!bkb || !tlb) return false;
/* COLUMN 0 OF THE STATE ROW IS THE COMMITTED SLOT. The row is wider than one whenever the
* deployment speculates -- the manager gives every linear group a second copy then, because
* the kernel that needed one asked for it -- and this op wants the committed slot in every
@@ -389,6 +372,46 @@ inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch
praw(batch->cu_seqlens, RAD_I32, S + 1),
kv_cache(c.kv_tail, layer),
praw2(tlb->state_index, RAD_I32, S, tw));
return true;
}
inline void QsaIndexer::store(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
proj.step(c_, in, w.qk, batch->n_tok);
(void)store_keys(c_, batch);
}
inline void QsaIndexer::step(RadCtx* c_, const ActFP8& in, const RadBatch* batch) const {
if (!on()) return;
const int64_t T = batch->n_tok, S = batch->n_seq;
const int64_t qw = c.heads * c.head_dim;
const int64_t nw = (c.heads + 1) * c.head_dim;
proj.step(c_, in, w.qk, T);
/* ONE LAUNCH OR `heads` + 1. The fused form takes the projection WHOLE -- the kernel picks
* head `h` out of it at the operand's own row pitch, so the strided view the unfused norm
* needs is not taken at all -- and it writes the query heads contiguous and rotated, which is
* what the pair below leaves behind. `n_head` 0 is the k-only form: no q_gate, no q_w, no
* q_out, and the ninth operand (`gate_out`) is absent as it is everywhere else.
*
* `T <= qprep_rows` IS THE TABLE'S BOUND and declare() says why it is correctness. */
if (op_qprep && T <= qprep_rows && !rope_mixed(batch)) {
RAD_ISSUE_N(c_, op_qprep, T,
RAD_NONE, brows(w.qk, T), RAD_B(w.cos_sin), rope_pos1(batch, T),
RAD_NONE, RAD_W(w_qn),
RAD_NONE, brows(w.q, T), RAD_NONE);
} else {
for (int64_t h = 0; h < c.heads; ++h)
RAD_ISSUE_N(c_, op_norm, T,
bcol_at(w.qk, 0, nw, h * c.head_dim, c.head_dim, T), RAD_W(w_qn),
bcol_at(w.q, 0, qw, h * c.head_dim, c.head_dim, T));
RAD_ISSUE_N(c_, op_rope, T, brows(w.q, T), rope_posmc(g, batch, T));
}
/* The keys first: the selection below reads the blocks they complete. */
const RadKVGroupBatch* bkb = kv_batch(batch, kv_bk);
const RadKVGroupBatch* atb = kv_batch(batch, c.kv_attn);
if (!atb || !store_keys(c_, batch)) return;
/* SCORE AND SELECT OVER EVERY QUERY IN THE STEP. A selection does not have to be per-SEQUENCE
* even though a block table is: both ops take `cu`, the block table stays the sequence's, and
+10
View File
@@ -0,0 +1,10 @@
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S arch/lfm2_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(lfm2_bf16 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(lfm2_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/lfm2_bf16.cpp)
+489
View File
@@ -0,0 +1,489 @@
/* lfm2_bf16 -- LiquidAI's LFM2 and LFM2-VL, bf16 weights and activations, one rank.
*
* ============================== THE SHAPE ==============================
*
* A hybrid of two layer kinds, in the order the checkpoint's `layer_types` lists them -- d1-3B's
* schedule is irregular (attention at 2, 5, 9, 13, ...), so it is read, never derived:
*
* conv in_proj -> [B | C | x], y = out_proj(C * conv(B * x)), where conv is a
* depthwise causal convolution of width `conv_L_cache` with no activation
* full_attention GQA with per-head RMS norms on q and k, NeoX rotary over the whole head
*
* each followed by a SwiGLU feed-forward (w1 the gate, w3 the up, w2 the down). Every norm is a
* plain RMSNorm -- `x_hat * w`, not Gemma's `1 + w` -- and the final one is `embedding_norm`. At
* d1-3B: 30 layers (10 attention), hidden 2048, 32 heads over 8 at head_dim 64, ffn 10752,
* vocabulary 128000 with the lm_head TIED to the embedding, conv width 3.
*
* LFM2-VL nests the same text model under `model.language_model` and adds a SigLIP2 tower and a
* projector (siglip2.h), declared when the container carries their weights and the deployment
* asked for media; the projector's rows replace the image placeholders' embeddings, which rotate
* at their token positions like any other token. A text-only LFM2 checkpoint keeps the text model
* under `model`. Which one this is is read off the config (a VL checkpoint has a `text_config`),
* not off the model's name.
*
* ============================== WHAT IT DOES NOT SERVE ==============================
*
* Tensor parallelism: one rank. A 3B model has no need of a second card, and the vocabulary
* shard, the head split and the all-reduces would be code no deployment runs. A drafter, MoE
* (LFM2-8B-A1B), conv bias, or a checkpoint without the rotary: each is refused by name.
*/
#include <arch/rad_arch.h>
#include <arch/rad_block_mlp.h>
#include <arch/rad_block_vit.h>
#include "siglip2.h"
#include <sstream>
#include <string>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Layer {
bool attention = false;
MlpBF16 mlp;
rad_weight w_norm = 0, w_in = 0, w_out = 0;
/* conv */
rad_weight w_conv = 0;
rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0;
/* attention: w_in is q, these are k, v and the two head norms */
rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0;
rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0;
rad_op op_store = 0, op_attn = 0;
/* both */
rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0;
};
struct Model {
Names nm{""};
Geom g{};
int64_t width = 0; /* conv_L_cache: the convolution's taps */
rad_kvgroup kv_attn = 0, kv_conv = 0;
rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0;
rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0;
rad_buf b_hout = 0, b_logits = 0;
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0;
std::vector<Layer> layers;
/* LFM2-VL's images: the tower and the scatter of its rows over the embeddings. */
bool media = false;
Siglip2 vit{};
MediaRows mrows{};
};
static Model g_model[MAX_RANKS];
/* A text_config key first, then the top level: a VL checkpoint nests the text model's settings
* and a text checkpoint does not. */
static const char* text_key(const RadModelMeta* m, const char* key) {
const std::string nested = std::string("text_config.") + key;
const char* v = rad_meta_gets(m, nested.c_str(), nullptr);
return v ? v : rad_meta_gets(m, key, nullptr);
}
static int64_t text_int(const RadModelMeta* m, const char* key, int64_t dflt) {
const char* v = text_key(m, key);
return v ? std::strtoll(v, nullptr, 10) : dflt;
}
static bool text_bool(const RadModelMeta* m, const char* key, bool dflt) {
const char* v = text_key(m, key);
if (!v) return dflt;
return std::strcmp(v, "true") == 0 || std::strcmp(v, "1") == 0;
}
/* `layer_types`, one word a layer. The container flattens the list space-separated. */
static int read_schedule(const RadModelMeta* m, int64_t n_layer, std::vector<Layer>* out) {
const char* s = text_key(m, "layer_types");
if (!s || !*s) {
fprintf(stderr, "radiance: lfm2: the container has no layer_types; this family's schedule "
"is irregular and is not derived\n");
return RAD_E_FORMAT;
}
std::istringstream in(s);
std::string kind;
while (in >> kind) {
if (kind != "conv" && kind != "full_attention") {
fprintf(stderr, "radiance: lfm2: layer_types[%zu] is '%s'; this plugin knows 'conv' "
"and 'full_attention'\n", out->size(), kind.c_str());
return RAD_E_UNSUPPORTED;
}
Layer l;
l.attention = kind == "full_attention";
out->push_back(l);
}
if ((int64_t)out->size() != n_layer) {
fprintf(stderr, "radiance: lfm2: layer_types names %zu layers and the model has %lld\n",
out->size(), (long long)n_layer);
return RAD_E_FORMAT;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: lfm2_bf16 serves one rank; run it with --tp 1\n");
return RAD_E_UNSUPPORTED;
}
if (meta->n_expert > 0 || text_bool(meta, "conv_bias", false) ||
!text_bool(meta, "block_use_swiglu", true) || !text_bool(meta, "use_pos_enc", true)) {
fprintf(stderr, "radiance: lfm2_bf16 serves the dense SwiGLU model with rotary "
"attention and bias-free convolutions; this checkpoint is not that\n");
return RAD_E_UNSUPPORTED;
}
Model& m = g_model[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
Names& nm = m.nm;
/* The FFN width as stated, unless the config asks for LFM2's sizing rule (the 1.2B and
* smaller releases): two thirds of it, times the multiplier, rounded up to `multiple_of`. */
RadModelMeta dims = *meta;
if (text_bool(meta, "block_auto_adjust_ff_dim", false)) {
int64_t ff = 2 * dims.n_ff / 3;
if (const char* mult = text_key(meta, "block_ffn_dim_multiplier")) {
const int64_t of = text_int(meta, "block_multiple_of", 256);
const double f = std::strtod(mult, nullptr);
if (!(f > 0.0) || of <= 0) return RAD_E_FORMAT;
ff = (int64_t)(f * (double)ff);
ff = of * ((ff + of - 1) / of);
}
dims.n_ff = ff;
}
RAD_ARCH_TRY(geom_from(m.g, &dims, ctx, "bf16", RAD_BF16));
Geom& g = m.g;
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
RAD_ARCH_TRY(read_schedule(meta, g.n_layer, &m.layers));
m.width = text_int(meta, "conv_L_cache", 0);
if (m.width < 2 || m.width > 8) {
fprintf(stderr, "radiance: lfm2: conv_L_cache %lld is outside the 2..8 the convolution "
"kernels serve\n", (long long)m.width);
return RAD_E_UNSUPPORTED;
}
const char* pre = rad_meta_gets(meta, "text_config.num_hidden_layers", nullptr)
? "model.language_model" : "model";
/* ---- the two state groups: paged KV for the attention layers, and a rolling window of the
* convolution's last width-1 inputs (plus the speculative slack the manager adds) for the
* conv layers. The conv group's channels are n_head_kv * head_dim: one "head" of n_embd. */
RadKVGroupDecl fd{};
fd.kind = RAD_KV_FULL;
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
fd.n_head_kv = g.n_head_kv;
fd.head_dim = g.head_dim;
m.kv_attn = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
g.kv_dtype = rad_dtype_name(fd.dtype);
RadKVGroupDecl cd{};
cd.kind = RAD_KV_CONV;
cd.dtype = RAD_BF16;
cd.n_head_kv = 1;
cd.head_dim = g.n_embd;
cd.conv_width = m.width;
m.kv_conv = rad_decl_kv_group(b, nm.f("kv_conv"), &cd);
if (!m.kv_attn || !m.kv_conv) return RAD_E_INVAL;
m.b_x = decl_b(b, nm.f("x"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_h = decl_b(b, nm.f("h"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_bcx = decl_b(b, nm.f("conv_bcx"), RAD_BF16, {g.max_tok, 3 * g.n_embd});
m.b_conv_in = decl_b(b, nm.f("conv_in"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_conv_out = decl_b(b, nm.f("conv_out"), RAD_BF16, {g.max_tok, g.n_embd});
m.b_q = decl_b(b, nm.f("attn_q"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_k = decl_b(b, nm.f("attn_k"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_v = decl_b(b, nm.f("attn_v"), RAD_BF16, {g.max_tok, g.kv_dim()});
m.b_attn = decl_b(b, nm.f("attn_out"), RAD_BF16, {g.max_tok, g.q_dim()});
m.b_gate_up = decl_b(b, nm.f("gate_up"), RAD_BF16, {g.max_tok, 2 * g.n_ff});
m.b_ffn = decl_b(b, nm.f("ffn"), RAD_BF16, {g.max_tok, g.n_ff});
m.b_hout = decl_b(b, nm.f("h_out"), RAD_BF16, {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));
/* ---- the vocabulary edges. The lm_head is tied in every release so far, and declared as a
* weight of its own anyway: the embedding lives in host memory (--embedding-placement) and the
* head on the card, and a kernel may ask the head for a layout the lookup does not read. */
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre)));
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s.embedding_norm.weight", pre)));
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
nm.ckpt("%s.embed_tokens.weight", pre)));
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, 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"), RAD_BF16, {g.n_vocab, g.n_embd},
RAD_ACCESS_VOCAB, RAD_SHARD_NONE, 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_WEIGHTS(m.w_tok)),
{}, {m.b_x});
/* The encoder's rows, over the lookup: one rank, so nothing is reduced after it. */
m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0;
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
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;
auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "gemm_nt",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) {
return rw(b, RAD_OP(b, "rmsnorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w)),
{in}, {out});
};
auto layer_w = [&](const char* name, int l, std::initializer_list<int64_t> shape,
uint32_t dtype) {
return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
};
for (int l = 0; l < (int)m.layers.size(); ++l) {
Layer& L = m.layers[(size_t)l];
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l),
nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l)));
L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32);
L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h);
if (L.attention) {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn));
const char* a = "%s.layers.%d.self_attn.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l),
nm.ckpt(a, pre, l, "q_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l),
nm.ckpt(a, pre, l, "k_layernorm.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l),
nm.ckpt(a, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16);
L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16);
L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32);
L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16);
L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q);
L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k);
L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v);
/* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is
* T * heads such rows. */
L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q);
L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k);
L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim,
"neox"), {m.b_q}, {m.b_q});
L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim,
"neox"), {m.b_k}, {m.b_k});
/* attn_paged before kv_store: the cache's block size is read off the resolved
* attention kernel. */
L.op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()),
RAD_INT("causal", 1), RAD_INT("window", 0),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_q}, {m.b_attn});
L.op_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, m.kv_attn)),
RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{m.b_k, m.b_v}, {});
L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h);
} else {
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv));
const char* c = "%s.layers.%d.conv.%s";
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight")));
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight")));
L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16);
/* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at
* convert, as the gated delta net's conv1d is. */
L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16);
L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16);
/* in_proj's row is [B | C | x]: conv(B * x), then C * that. */
L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx);
L.op_gate_in = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx}, {m.b_conv_in});
L.op_conv = rw(b, RAD_OP(b, "causal_conv1d",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(L.w_conv)),
{m.b_conv_in}, {m.b_conv_out});
L.op_gate_out = rw(b, RAD_OP(b, "mul",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", g.dtype)),
RAD_NOWEIGHTS),
{m.b_bcx, m.b_conv_out}, {m.b_conv_out});
L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h);
}
L.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),
{m.b_x, m.b_h}, {m.b_x});
MlpBF16::Src ms{};
ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l);
ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l);
ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l);
ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l);
RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms));
}
/* The final norm runs on the gathered rows only: it is per token, and those are the rows the
* lm_head reads. */
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_x}, {m.b_hout});
m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, 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});
/* THE VISION TOWER, LAST, so its activations share the arena with every buffer above. */
if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer + 64));
int64_t n_attn = 0;
for (const Layer& L : m.layers) n_attn += L.attention ? 1 : 0;
rad_note(b, "lfm2: %lld layers, %lld attention + %lld short convolution of width %lld; "
"%lld heads over %lld at head_dim %lld, ffn %lld, vocab %lld",
(long long)g.n_layer, (long long)n_attn, (long long)(g.n_layer - n_attn),
(long long)m.width, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.n_vocab);
return RAD_OK;
}
/* THE CONVOLUTION IS ISSUED ONCE PER HALF OF THE STEP, as the PLE's and the gated delta net's
* are: the decode rows [0, D) with `num_accepted`, which leaves the window in the layout a
* partly rejected verify reads back from, and the prefill chunks [D, S) without it, each leaving
* its tail at offset zero. `has_init` is `ctx_lens`: a sequence with tokens behind it has a
* history. The per-sequence arrays of the prefill half move to `+ D`; the token operands stay at
* their base, because the kernel reads rows at the absolute offsets in `cu`. */
static void conv_step(const Model& m, const Layer& L, RadCtx* c, const RadBatch* batch, int l) {
const int64_t T = batch->n_tok, S = batch->n_seq;
const RadKVGroupBatch* cv = kv_batch(batch, m.kv_conv);
const int32_t* idx = cv ? cv->state_index : nullptr;
int64_t D = 0, DT = 0;
batch_split(batch, &D, &DT);
const int64_t P = S - D;
if (D > 0)
RAD_ISSUE_N(c, L.op_conv, DT,
brows(m.b_conv_in, DT), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens, RAD_I32, D + 1), praw(idx, RAD_I32, D),
praw(batch->ctx_lens, RAD_I32, D), praw(batch->num_accepted, RAD_I32, D),
brows(m.b_conv_out, DT));
if (P > 0)
RAD_ISSUE_N(c, L.op_conv, T,
brows(m.b_conv_in, T), RAD_W(L.w_conv), kv_cache(m.kv_conv, l),
praw(batch->cu_seqlens + D, RAD_I32, P + 1),
praw(idx ? idx + D : nullptr, RAD_I32, P),
praw(batch->ctx_lens + D, RAD_I32, P), RAD_NONE,
brows(m.b_conv_out, T));
}
static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = g_model[rad_rank(c)];
const Geom& g = m.g;
if (batch->draft_pass || batch->spec_parent ||
(!m.media && (batch->enc || batch->n_mm_rows > 0))) {
rad_step_fail(c, "lfm2_bf16: this step asks for an encoder, a draft pass or media rows, "
"and the program declares none of them");
return;
}
/* AN ENCODER PASS RUNS THE VISION TOWER AND NOTHING ELSE (RadBatch::enc). */
if (batch->enc) {
m.vit.step(c, batch);
return;
}
const int64_t T = batch->n_tok, n = g.n_embd;
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
m.mrows.step(c, batch, m.b_x, T);
for (int l = 0; l < (int)m.layers.size(); ++l) {
const Layer& L = m.layers[(size_t)l];
RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T));
if (L.attention) {
const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn);
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T));
RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T));
RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T));
RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm),
brows(m.b_q, T));
RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm),
brows(m.b_k, T));
RAD_ISSUE(c, L.op_rope_q, brows(m.b_q, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_rope_k, brows(m.b_k, T), rope_pos1(batch, T));
RAD_ISSUE(c, L.op_store, brows(m.b_k, T), brows(m.b_v, T),
praw(kv ? kv->slot_mapping : nullptr, RAD_I32, T), kv_cache(m.kv_attn, l));
RAD_ISSUE_N(c, L.op_attn, batch->max_q_len,
brows(m.b_q, T), kv_cache(m.kv_attn, l),
praw2(kv ? kv->block_table : nullptr, RAD_I32, batch->n_seq,
kv ? kv->block_table_pitch : 0),
praw(kv ? kv->seqused : nullptr, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(m.b_attn, T));
RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T));
} else {
RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T));
RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T),
brows(m.b_conv_in, T));
conv_step(m, L, c, batch, l);
RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T),
brows(m.b_conv_out, T));
RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T));
}
RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
L.mlp.step(c, batch);
}
/* The lm_head runs on the rows the sampler asked for and on nothing else; a prefill chunk
* that finishes no sequence issues none of it. */
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_x, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out),
RAD_W(m.w_out_norm), 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 lfm2_bf16 */
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0",
"LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the "
"checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images")
#endif
+329
View File
@@ -0,0 +1,329 @@
/* siglip2.h -- LFM2-VL's image encoder: the SigLIP2 NaFlex tower and the projector after it.
*
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
*
* x = patches @ Wp^T + bp the patch embedding, a linear layer over a patch
* row (y, x, channel)
* x += pos_table resampled to each segment's grid torch's antialiased half-pixel bilinear
* (grid_embed_aa), rounded before the add
* depth times:
* x += out(attn(qkv(LN1(x)))) full attention within a segment (one tile or the
* thumbnail), no rotary
* x += fc2(gelu_tanh(fc1(LN2(x))))
* y = post_LN(x)
* out = l2(gelu(l1([LN](y viewed [P/merge^2, merge^2 * width])))) the projector
*
* which is transformers' Siglip2VisionModel (no pooling head) followed by Lfm2VlMultiModalProjector.
* The projector's pixel unshuffle is a VIEW here: the processor stores each segment's patches in
* merge-block order (core/mm/processor.cpp, image_lfm2), so a block's merge^2 patches are
* consecutive rows, dy then dx -- the order the unshuffle concatenates them in. The tower itself
* does not care about the order: attention within a segment is permutation-equivariant and every
* other layer is per patch, and the position table is resampled at each patch's own (row, column).
*
* q, k and v are one fused weight, concatenated at convert (map_concat), so a layer is one QKV
* GEMM; the attention reads the three as column slices.
*
* Replicated, per-request weights and pass-sized activations, as arch/common/rad_block_vit.h's
* tower: see the notes there.
*/
#ifndef LFM2_SIGLIP2_H
#define LFM2_SIGLIP2_H
#include <arch/rad_arch.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lfm2_bf16 {
using namespace rad::arch;
struct Siglip2 {
int64_t depth = 0, width = 0, heads = 0, ff = 0, patch = 0, merge = 0, side = 0;
int64_t head_dim = 0, patch_dim = 0, proj_hidden = 0, n_embd = 0, P = 0;
float eps = 1e-6f;
bool proj_norm = false, on = false;
struct Layer {
rad_weight n1w = 0, n1b = 0, n2w = 0, n2b = 0;
rad_weight qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0;
rad_weight up_w = 0, up_b = 0, down_w = 0, down_b = 0;
rad_op ln1 = 0, qkv = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0;
};
std::vector<Layer> L;
rad_weight w_patch = 0, b_patch = 0, w_pos = 0, pn_w = 0, pn_b = 0;
rad_weight mn_w = 0, mn_b = 0, m1_w = 0, m1_b = 0, m2_w = 0, m2_b = 0;
rad_op op_patch = 0, op_pos = 0, op_post = 0, op_mln = 0, op_m1 = 0, op_m2 = 0;
rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_mh = 0, b_mn = 0, b_mf = 0;
rad_buf b_out = 0;
/* A tower to declare: the container is an LFM2-VL one, whose vision_config is SigLIP2's. */
static bool present(const RadModelMeta* m) {
return !std::strcmp(rad_meta_gets(m, "vision_config.model_type", ""), "siglip2_vision_model") &&
rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0;
}
/* Input patches an output row: the projector's unshuffle. */
static int64_t merge_of(const RadModelMeta* m) {
const int64_t d = rad_meta_geti(m, "downsample_factor", 0);
return d * d;
}
int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm,
int64_t model_embd, int first_group);
void step(RadCtx* c, const RadBatch* batch) const;
};
inline int Siglip2::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx,
Names& nm, int64_t model_embd, int first_group) {
on = false;
if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK;
depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0);
width = rad_meta_geti(m, "vision_config.hidden_size", 0);
heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0);
ff = rad_meta_geti(m, "vision_config.intermediate_size", 0);
patch = rad_meta_geti(m, "vision_config.patch_size", 0);
eps = (float)rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-6);
const int64_t chans = rad_meta_geti(m, "vision_config.num_channels", 3);
const int64_t npos = rad_meta_geti(m, "vision_config.num_patches", 0);
merge = rad_meta_geti(m, "downsample_factor", 0);
proj_hidden = rad_meta_geti(m, "projector_hidden_size", 0);
n_embd = model_embd;
side = (int64_t)std::llround(std::sqrt((double)npos));
if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || merge <= 0 ||
proj_hidden <= 0 || side <= 0 || side * side != npos || width % heads || chans != 3) {
fprintf(stderr, "radiance: lfm2: the container's SigLIP2 vision_config is incomplete or "
"inconsistent (layers %lld, hidden %lld, heads %lld, ff %lld, patch %lld, "
"positions %lld, channels %lld; downsample_factor %lld, projector %lld)\n",
(long long)depth, (long long)width, (long long)heads, (long long)ff,
(long long)patch, (long long)npos, (long long)chans, (long long)merge,
(long long)proj_hidden);
return RAD_E_INVAL;
}
/* The pooling head is SigLIP2's contrastive readout; LFM2-VL reads the patch rows, and a
* checkpoint that ships a head would load weights nothing runs. Refused by name. */
if (rad_meta_geti(m, "vision_config.vision_use_head", 0) != 0 ||
!std::strcmp(rad_meta_gets(m, "vision_config.vision_use_head", ""), "true")) {
fprintf(stderr, "radiance: lfm2: this SigLIP2 tower has a pooling head, which LFM2-VL does "
"not read and this plugin does not serve\n");
return RAD_E_UNSUPPORTED;
}
const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu_pytorch_tanh");
const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu");
if (std::strcmp(act, "gelu_pytorch_tanh") || std::strcmp(pact, "gelu")) {
fprintf(stderr, "radiance: lfm2: the tower's activation '%s' and the projector's '%s' are "
"not gelu_pytorch_tanh and gelu, which is what this plugin serves\n",
act, pact);
return RAD_E_UNSUPPORTED;
}
const char* pb = rad_meta_gets(m, "projector_bias", "true");
if (std::strcmp(pb, "true") && std::strcmp(pb, "1")) {
fprintf(stderr, "radiance: lfm2: a projector without biases is not served\n");
return RAD_E_UNSUPPORTED;
}
proj_norm = !std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "true") ||
!std::strcmp(rad_meta_gets(m, "projector_use_layernorm", "true"), "1");
head_dim = width / heads;
patch_dim = chans * patch * patch;
const int64_t mm = merge * merge, mw = mm * width;
P = ctx->max_enc_patches;
/* The longest segment attention sees: a tile or the largest thumbnail, which the processor
* keeps within max_num_patches. A bound that picks the attention kernel's block height, so it
* is the real one in a sizing declare too. */
const int64_t seg = rad_meta_geti(m, "processor.image_processor.max_num_patches",
rad_meta_geti(m, "max_num_patches", P));
const int64_t max_seg = std::min<int64_t>(P, seg);
if (ctx->shape_probe) {
const int64_t r = std::min<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(mm, r / mm * mm);
}
if (P % mm) return RAD_E_SHAPE;
const int64_t R = P / mm;
const int ACC = RAD_ACCESS_PER_REQUEST;
auto bw = [&](const char* dn, const char* src, std::initializer_list<int64_t> shp,
RadWeightGroup g) -> rad_weight {
if (map_copy(b, dn, src) < 0) return 0;
return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g);
};
const char* tw = "model.vision_tower.vision_model.";
w_patch = bw(nm.f("v.patch.weight"), nm.ckpt("%sembeddings.patch_embedding.weight", tw),
{ width, patch_dim }, grp_model());
b_patch = bw(nm.f("v.patch.bias"), nm.ckpt("%sembeddings.patch_embedding.bias", tw),
{ width }, grp_model());
w_pos = bw(nm.f("v.pos.weight"), nm.ckpt("%sembeddings.position_embedding.weight", tw),
{ npos, width }, grp_model());
L.assign((size_t)depth, Layer{});
for (int64_t i = 0; i < depth; ++i) {
Layer& l = L[(size_t)i];
const RadWeightGroup g = grp_layer(first_group + (int)i);
const int li = (int)i;
const char* e = "%sencoder.layers.%d.%s";
l.n1w = bw(nm.f("v.blk.%d.norm1.weight", li), nm.ckpt(e, tw, li, "layer_norm1.weight"), { width }, g);
l.n1b = bw(nm.f("v.blk.%d.norm1.bias", li), nm.ckpt(e, tw, li, "layer_norm1.bias"), { width }, g);
l.n2w = bw(nm.f("v.blk.%d.norm2.weight", li), nm.ckpt(e, tw, li, "layer_norm2.weight"), { width }, g);
l.n2b = bw(nm.f("v.blk.%d.norm2.bias", li), nm.ckpt(e, tw, li, "layer_norm2.bias"), { width }, g);
/* q, k, v fused at convert: one GEMM a layer. */
const char* qw = nm.f("v.blk.%d.qkv.weight", li);
const char* qb = nm.f("v.blk.%d.qkv.bias", li);
if (map_concat(b, qw, { nm.ckpt(e, tw, li, "self_attn.q_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.k_proj.weight"),
nm.ckpt(e, tw, li, "self_attn.v_proj.weight") }) < 0 ||
map_concat(b, qb, { nm.ckpt(e, tw, li, "self_attn.q_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.k_proj.bias"),
nm.ckpt(e, tw, li, "self_attn.v_proj.bias") }) < 0)
return RAD_E_INVAL;
l.qkv_w = decl_w(b, qw, RAD_BF16, { 3 * width, width }, ACC, RAD_SHARD_NONE, g);
l.qkv_b = decl_w(b, qb, RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g);
l.out_w = bw(nm.f("v.blk.%d.proj.weight", li), nm.ckpt(e, tw, li, "self_attn.out_proj.weight"), { width, width }, g);
l.out_b = bw(nm.f("v.blk.%d.proj.bias", li), nm.ckpt(e, tw, li, "self_attn.out_proj.bias"), { width }, g);
l.up_w = bw(nm.f("v.blk.%d.fc1.weight", li), nm.ckpt(e, tw, li, "mlp.fc1.weight"), { ff, width }, g);
l.up_b = bw(nm.f("v.blk.%d.fc1.bias", li), nm.ckpt(e, tw, li, "mlp.fc1.bias"), { ff }, g);
l.down_w = bw(nm.f("v.blk.%d.fc2.weight", li), nm.ckpt(e, tw, li, "mlp.fc2.weight"), { width, ff }, g);
l.down_b = bw(nm.f("v.blk.%d.fc2.bias", li), nm.ckpt(e, tw, li, "mlp.fc2.bias"), { width }, g);
if (!l.n1w || !l.n1b || !l.n2w || !l.n2b || !l.qkv_w || !l.qkv_b || !l.out_w ||
!l.out_b || !l.up_w || !l.up_b || !l.down_w || !l.down_b)
return RAD_E_INVAL;
}
pn_w = bw(nm.f("v.post_norm.weight"), nm.ckpt("%spost_layernorm.weight", tw), { width }, grp_model());
pn_b = bw(nm.f("v.post_norm.bias"), nm.ckpt("%spost_layernorm.bias", tw), { width }, grp_model());
const char* pj = "model.multi_modal_projector.";
if (proj_norm) {
mn_w = bw(nm.f("v.proj.norm.weight"), nm.ckpt("%slayer_norm.weight", pj), { mw }, grp_model());
mn_b = bw(nm.f("v.proj.norm.bias"), nm.ckpt("%slayer_norm.bias", pj), { mw }, grp_model());
if (!mn_w || !mn_b) return RAD_E_INVAL;
}
m1_w = bw(nm.f("v.proj.fc1.weight"), nm.ckpt("%slinear_1.weight", pj), { proj_hidden, mw }, grp_model());
m1_b = bw(nm.f("v.proj.fc1.bias"), nm.ckpt("%slinear_1.bias", pj), { proj_hidden }, grp_model());
m2_w = bw(nm.f("v.proj.fc2.weight"), nm.ckpt("%slinear_2.weight", pj), { n_embd, proj_hidden }, grp_model());
m2_b = bw(nm.f("v.proj.fc2.bias"), nm.ckpt("%slinear_2.bias", pj), { n_embd }, grp_model());
if (!w_patch || !b_patch || !w_pos || !pn_w || !pn_b || !m1_w || !m1_b || !m2_w || !m2_b)
return RAD_E_INVAL;
/* ---- activations. `mh` is the post-norm's output declared at the MERGED width: the norm
* writes P rows of `width` and the projector reads P/mm rows of mm * width, the same bytes. */
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width });
b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width });
b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width });
b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width });
b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff });
b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mw });
if (proj_norm) b_mn = decl_b(b, nm.f("v.mn"), RAD_BF16, { R, mw });
b_mf = decl_b(b, nm.f("v.mf"), RAD_BF16, { R, proj_hidden });
b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd });
if (!b_x || !b_h || !b_qkv || !b_att || !b_ff || !b_mh || (proj_norm && !b_mn) || !b_mf ||
!b_out)
return RAD_E_INVAL;
auto gemm = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w,
rad_weight bias) -> rad_op {
return RAD_OP(b, "gemm_nt_bias",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K),
RAD_STR("dtype", "bf16"), RAD_STR("act", a)),
RAD_WEIGHTS(w, bias));
};
auto lnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_weight bias) -> rad_op {
return RAD_OP(b, "layernorm",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n),
RAD_F64("eps", eps), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w, bias));
};
op_patch = rw(b, gemm(P, width, patch_dim, "none", w_patch, b_patch), {}, { b_x });
op_pos = rw(b, RAD_OP(b, "grid_embed_aa",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width),
RAD_INT("side", side), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w_pos)),
{ b_x }, { b_x });
for (Layer& l : L) {
l.ln1 = rw(b, lnorm(P, width, l.n1w, l.n1b), { b_x }, { b_h });
l.qkv = rw(b, gemm(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv });
l.attn = rw(b, RAD_OP(b, "attn_dense",
RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim),
RAD_INT("gqa", 1), RAD_INT("causal", 0),
RAD_STR("dtype", "bf16"),
RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)),
RAD_INT("max_seqlen", max_seg)),
RAD_NOWEIGHTS),
{ b_qkv }, { b_att });
l.proj = rw(b, gemm(P, width, width, "none", l.out_w, l.out_b), { b_att, b_x }, { b_x });
l.ln2 = rw(b, lnorm(P, width, l.n2w, l.n2b), { b_x }, { b_h });
l.up = rw(b, gemm(P, ff, width, "gelu_tanh", l.up_w, l.up_b), { b_h }, { b_ff });
l.down = rw(b, gemm(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_x }, { b_x });
}
op_post = rw(b, lnorm(P, width, pn_w, pn_b), { b_x }, { b_mh });
if (proj_norm) op_mln = rw(b, lnorm(R, mw, mn_w, mn_b), { b_mh }, { b_mn });
op_m1 = rw(b, gemm(R, proj_hidden, mw, "gelu", m1_w, m1_b), { proj_norm ? b_mn : b_mh }, { b_mf });
op_m2 = rw(b, gemm(R, n_embd, proj_hidden, "none", m2_w, m2_b), { b_mf }, { b_out });
if (!ctx->shape_probe) {
RadEncoderDecl e{};
e.name = "vision";
e.modalities = RAD_MM_IMAGE;
e.patch_dim = patch_dim;
e.merge = mm;
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "SigLIP2 tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
"%lld x %lld position table; projector %lld -> %lld -> %lld%s; %lld patches a "
"pass -> %lld rows",
(long long)depth, (long long)width, (long long)heads, (long long)head_dim,
(long long)ff, (long long)patch, (long long)side, (long long)side,
(long long)mw, (long long)proj_hidden, (long long)n_embd,
proj_norm ? " behind a layer norm" : "", (long long)P, (long long)R);
}
on = true;
return RAD_OK;
}
inline void Siglip2::step(RadCtx* c, const RadBatch* batch) const {
const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg;
const int64_t mm = merge * merge, Rn = Pn / mm;
if (!on || batch->enc != RAD_MM_IMAGE || Pn <= 0 || Pn > P || Pn % mm || S <= 0) {
rad_step_fail(c, "lfm2: an encoder pass this program's SigLIP2 tower cannot serve: no "
"tower, not images, more patches than it was declared for, or not whole "
"merged rows");
return;
}
/* The patches, their coordinates -- a dense [4, P] of row, column, segment height and width,
* which is what the position resample reads -- and the segment boundaries. */
const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim);
const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn);
const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1);
RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn));
RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd);
for (const Layer& l : L) {
RAD_ISSUE_N(c, l.ln1, Pn, brows(b_x, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE,
brows(b_qkv, Pn));
RAD_ISSUE_N(c, l.attn, Pn,
bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b),
brows(b_x, Pn), brows(b_x, Pn));
RAD_ISSUE_N(c, l.ln2, Pn, brows(b_x, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn));
RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE,
brows(b_ff, Pn));
RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b),
brows(b_x, Pn), brows(b_x, Pn));
}
/* The post-norm writes Pn rows of `width` into a buffer declared at the merged width: the
* same bytes the projector reads as Pn/mm rows -- the pixel unshuffle. */
RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(pn_w), RAD_W(pn_b), brows(b_mh, Rn));
if (proj_norm)
RAD_ISSUE_N(c, op_mln, Rn, brows(b_mh, Rn), RAD_W(mn_w), RAD_W(mn_b), brows(b_mn, Rn));
RAD_ISSUE_N(c, op_m1, Rn, brows(proj_norm ? b_mn : b_mh, Rn), RAD_W(m1_w), RAD_W(m1_b),
RAD_NONE, brows(b_mf, Rn));
RAD_ISSUE_N(c, op_m2, Rn, brows(b_mf, Rn), RAD_W(m2_w), RAD_W(m2_b), RAD_NONE,
brows(b_out, Rn));
}
} /* namespace lfm2_bf16 */
#endif /* LFM2_SIGLIP2_H */
+4
View File
@@ -1097,6 +1097,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, mlp_fold, mlp_add,
mlp_ar_in, mlp_ar_out));
}
#if QWEN35_MOE
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (int64_t l = 0; l + 1 < m.n_main; ++l) m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp;
#endif
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),
+3
View File
@@ -1232,6 +1232,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
/* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */
for (size_t l = 0; l + 1 < m.layers.size(); ++l) m.layers[l].mlp.xp_next = &m.layers[l + 1].mlp;
/* ---- the 97th connection. No write half, no fp8 twin: it produces the one hidden state the
* lm_head reads, as a bf16 input. Its `hc_norm` is what a pre-norm model calls the
* final norm -- this checkpoint has no `model.language_model.norm.weight` at all. */