gemma4_bf16: a picture's rows read both ways on the sliding layers

use_bidirectional_attention "vision" (the 12B and the 31B): each
sliding layer attends a run's rows again over the cache up to the
run's end without the causal bound, over their causal result. The
global layers stay causal, as transformers' Gemma 4 masks, KerasHub
and vLLM have it. RADIANCE_MEDIA_BIDI=0 keeps every layer causal.
This commit is contained in:
keptn42 committed 2026-11-04 07:20:43 +01:00
1 parent da7b911c64
commit c6391e6ef9
5 files changed
+204 -5

No files matched your search

+4
View File
@@ -27,6 +27,9 @@ namespace arch {
struct Gemma4UnifiedVision {
bool on = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = false;
int64_t P = 0, width = 0, patch_dim = 0, npos = 0, n_embd = 0;
rad_weight w_ln1 = 0, w_ln1b = 0, w_in = 0, w_inb = 0, w_ln2 = 0, w_ln2b = 0, w_px = 0, w_py = 0;
rad_weight w_pn = 0, w_pnb = 0, w_proj = 0;
@@ -139,6 +142,7 @@ struct Gemma4UnifiedVision {
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
rad_note(b, "vision embedder (no tower): %lldx%lld patches of %lld values -> %lld, "
"positions %lld a side; %lld patches a pass -> %lld rows of %lld",
+4
View File
@@ -56,6 +56,9 @@ struct Gemma4Vision {
rad_op op_c[C_N] = {};
};
bool on = false, standardize = false, clip = false;
/* The language model reads a picture's rows both ways (RadEncoderDecl::bidirectional); the
* plugin sets it before declare. */
bool bidirectional = 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;
@@ -321,6 +324,7 @@ struct Gemma4Vision {
e.max_patches = P;
e.n_embd = n_embd;
e.out = b_out;
e.bidirectional = bidirectional ? 1 : 0;
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%s; %lld patches a pass -> %lld rows of %lld",
+86 -4
View File
@@ -456,6 +456,13 @@ struct Gemma4Attn {
* no library serves it, which the model reads as "no trees". */
bool tree = false;
rad_op op_attn_tree = 0, op_tree_lift = 0;
/* Pictures read both ways (Model::bidi, set before declare; sliding layers only): attention
* again over a run's keys without the causal bound (RadBatch::n_bidi), reading q in the row
* (op_bidi_row) where the step's attention does, else in its own rows (op_bidi); 0 where no
* kernel serves it. */
bool want_bidi = false;
rad_op op_bidi = 0, op_bidi_row = 0;
bool bidi_ok() const { return op_bidi || op_bidi_row; }
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
* "Prefetch beside the reductions") */
rad_op op_pf = 0;
@@ -494,6 +501,9 @@ struct Gemma4Attn {
bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); }
void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n,
RadOperand used) const;
/* The rows of each run read both ways, attended again (see op_bidi); `q_dense`: the step's
* attention left q in its own rows. */
void attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const;
};
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
@@ -646,11 +656,12 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
/* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM
* use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim),
* so 1.0 is passed explicitly. */
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0) {
auto attn = [&](const char* op, std::initializer_list<rad_buf> rd, int64_t q_hi = 0,
int causal = 1) {
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok),
RAD_INT("head_dim", cls.head_dim),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1),
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", causal),
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),
@@ -731,6 +742,10 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
op_attn = attn("attn_paged", {w.q, w.qkv});
}
}
if (want_bidi) {
if (op_attn_row) op_bidi_row = attn("attn_paged_qrow", {w.qkv}, 0, 0);
else op_bidi = attn("attn_paged", {w.q}, 0, 0);
}
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
@@ -857,6 +872,18 @@ int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.attn});
if (want_bidi)
op_bidi = 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", 0),
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),
@@ -965,6 +992,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
attend_bidi(c, batch, true);
return;
}
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
@@ -1003,6 +1031,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
* which come first (spec §8). */
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
batch->n_seq_decode > 0;
bool q_dense = true;
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
@@ -1013,8 +1042,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
q_dense = false;
} else if (row) {
if (T == 1) a_q = Q;
if (T == 1) { a_q = Q; q_dense = false; }
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
@@ -1041,6 +1071,38 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
brows(w.attn, Td),
praw(batch->spec_parent, RAD_I32, Td));
}
attend_bidi(c, batch, q_dense);
}
/* A run's rows (RadBatch::n_bidi) see every key of their run, later ones included: attention over
* their sequence's cache up to the run's end without the causal bound, written over what the
* causal pass left in their rows, on a sliding layer. Its window stays, two-sided: (causal or the
* run) and the window, which holds every key of a run up to the window's length. The keys are all
* in the cache: the step stored its own, and a run's earlier rows are this step's or a prefix
* hit's. */
void Gemma4Attn::attend_bidi(RadCtx* c, const RadBatch* batch, bool q_dense) const {
if (batch->n_bidi <= 0 || !bidi_ok()) return;
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int64_t pitch = kvb ? kvb->block_table_pitch : 0;
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
for (int64_t i = 0; i < batch->n_bidi; ++i) {
const int64_t r0 = batch->bidi_row[i], n = batch->bidi_n[i], s = batch->bidi_seq[i];
const RadOperand tb = praw2(table ? table + s * pitch : nullptr, RAD_I32, 1, pitch);
const RadOperand used = praw(batch->bidi_used + i, RAD_I32, 1);
const RadOperand out = brow_slice(w.attn, r0, n, qd);
if (op_bidi_row) {
RAD_ISSUE_N(c, op_bidi_row, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
kv_cache(kv, kv_layer), tb, used, RAD_NONE, RAD_NONE, RAD_NONE, out);
continue;
}
if (!q_dense)
RAD_ISSUE_N(c, op_lift_q, n, bcol_at(w.qkv, r0, qkvd, 0, qd, n),
brow_slice(w.q, r0, n, qd));
RAD_ISSUE_N(c, op_bidi, n, brow_slice(w.q, r0, n, qd), kv_cache(kv, kv_layer), tb, used,
RAD_NONE, RAD_NONE, RAD_NONE, out);
}
}
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
@@ -1895,6 +1957,10 @@ struct Model {
Gemma4UnifiedVision uvis{}; /* the 12B's embedders, in place of the tower and encoder */
Gemma4UnifiedAudio uaud{};
rad_op op_mm = 0;
/* A picture's or video frame's placeholders attend to each other both ways
* (use_bidirectional_attention "vision"): every sliding layer attends a run's rows again
* (Gemma4Attn::op_bidi), and the encoder says so (RadEncoderDecl::bidirectional). */
bool bidi = false;
G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */
bool fuse = false;
@@ -2516,10 +2582,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
kv_shared == 0 && ctx->draft_tree != 0;
bool tree_all = tree_want;
/* Pictures read both ways where the model was trained so, on the sliding layers alone: the
* global layers stay causal (transformers' create_masks_for_vision_model, "Gemma 4 explicitly
* disables bidirectional attention on global attention layers"; KerasHub's Gemma 4 decoder
* block and vLLM agree). RADIANCE_MEDIA_BIDI=0 reads them causally on every layer. */
const char* bidi_cfg = meta_text_gets(meta, "use_bidirectional_attention", "");
const char* bidi_env = std::getenv("RADIANCE_MEDIA_BIDI");
const bool want_bidi = bidi_cfg && !std::strcmp(bidi_cfg, "vision") && ctx->max_enc_patches > 0 &&
(Gemma4Vision::present(meta) || Gemma4UnifiedVision::present(meta)) &&
!(bidi_env && !std::strcmp(bidi_env, "0"));
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l];
lay.global = (is_global[(size_t)l] == 1);
lay.attn.want_bidi = want_bidi && !lay.global;
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;
@@ -2826,6 +2902,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta));
head_groups = rad_meta_geti(meta, k, 0);
}
m.bidi = want_bidi;
for (const Layer& lay : m.layers) m.bidi = m.bidi && (lay.global || lay.attn.bidi_ok());
if (want_bidi && !m.bidi)
rad_note(b, "pictures are read causally: no kernel attends a run's rows without the "
"causal bound");
m.vis.bidirectional = m.uvis.bidirectional = m.bidi;
RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups),
"model.", "gemma4_bf16"));
RAD_ARCH_TRY(m.aud.declare(b, meta, ctx, nm, g.n_embd,
@@ -2964,7 +3046,7 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6
m.j0.step(c, T);
const size_t L = m.layers.size();
if (m.slice_attn && batch->n_seq == 1) {
if (m.slice_attn && batch->n_seq == 1 && batch->n_bidi == 0) {
/* Attention per slice (see Model::slice_attn): slice A's context end first, then each
* layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward
* beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each