From 0895588b7683771cdff2118d87cb762524edf1b9 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sun, 11 Oct 2026 02:51:18 +0000 Subject: [PATCH] gemma4: the vision tower -- images and video through Gemma 4's own encoder The 31B's tower (27 layers of 1152, 72-wide heads, a 2-D rotary over two 18-pair neox blocks, 3x3 pooling, per-channel standardisation) declared beside the text model when the container carries it and the deployment serves media; its rows replace the placeholder embeddings after the lookup. qk_norm_rope's blocks mode now runs at any head_dim and section size (a lane a pair outside the register layout). --- arch/gemma4_bf16/gemma4_bf16.cpp | 41 +++- arch/gemma4_bf16/gemma4_vision.h | 321 +++++++++++++++++++++++++++++++ libr4d/r4d_encoder_bf16.hip | 76 +++++++- libr4d/r4d_rows.cpp | 9 +- 4 files changed, 437 insertions(+), 10 deletions(-) create mode 100644 arch/gemma4_bf16/gemma4_vision.h diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 83d456b1..5e793b2d 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -1,4 +1,4 @@ -/* gemma4_bf16.cpp -- Gemma 4 dense, text-only, bf16. +/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (gemma4_vision.h). * * Two attention classes over ONE residual stream, alternating by layer. A "sliding" layer is * sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global" @@ -19,6 +19,8 @@ #include #include +#include "gemma4_vision.h" + namespace gemma4_bf16 { using namespace rad::arch; @@ -1215,6 +1217,11 @@ struct Model { Gemma4Head head{}; bool have_head = false; + /* The vision tower (gemma4_vision.h), declared when the container carries one and the + * deployment serves media; `op_mm` writes its rows over the placeholders' embeddings. */ + Vision vis{}; + rad_op op_mm = 0; + G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */ bool fuse = false; bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ @@ -1429,6 +1436,15 @@ 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}); + /* An image's rows over its placeholders' embeddings, after the (all-reduced) lookup and + * before the first block reads the stream: the reference scales the token embeddings by + * sqrt(n_embd) and scatters the image features in unscaled. */ + if (Vision::present(meta) && ctx->max_enc_patches > 0) + 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}); /* ---- the layers. This loop is the model card. */ 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; @@ -1535,6 +1551,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset)); } + /* ---- the vision tower, its weight groups past the trunk's and the head's (whether or not + * this deployment declares the head, so the groups do not move with max_spec). */ + { + const int64_t head_groups = has_assistant(meta) ? hd_i(meta, "num_hidden_layers", 0) + 1 : 0; + RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups))); + } + rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, " "slider %lld heads x %lld, global %lld heads x %lld, soft-capped logits", g.rank, g.world, (long long)g.n_layer, (long long)n_global, @@ -1554,6 +1577,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c static void step(RadCtx* c, const RadBatch* batch) { Model& m = g_model[rad_rank(c)]; + /* AN ENCODER PASS RUNS THE TOWER AND NOTHING ELSE. */ + if (batch->enc) { + m.vis.step(c, batch); + return; + } /* A DRAFT PASS RUNS THE HEAD AND NOTHING ELSE. The trunk already ran this step and left its * final-normed hidden state in `h`, which the head's history pass gathers from. */ if (batch->draft_pass != 0) { @@ -1584,6 +1612,10 @@ static void step(RadCtx* c, const RadBatch* batch) { 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)); trc_copy(c, m.trc, m.g.n_embd, 0, 0, m.b_x, batch->n_tok); /* site x0: post-embedding */ const int64_t T = batch->n_tok; @@ -1642,12 +1674,17 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { out->draft_depth = kHeadDepth; out->draft_depth_fixed = 0; } + /* The tower's pooling window, so a pass size the core picks itself is whole windows. */ + if (Vision::present(meta)) { + const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); + if (k > 0) out->enc_merge = k * k; + } return RAD_OK; } #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", - "Gemma 4 dense (text-only), w4a8 from its CT-INT4 (compressed-tensors) release: " + "Gemma 4 dense (text and images), w4a8 from its CT-INT4 (compressed-tensors) release: " "sliding-window and proportional-RoPE global attention over a GemmaRMSNorm stream " "with GELU feed-forward, per-layer scalar scaling and soft-capped logits") RAD_ARCH_CHAT_FORMAT(gemma4_bf16) diff --git a/arch/gemma4_bf16/gemma4_vision.h b/arch/gemma4_bf16/gemma4_vision.h new file mode 100644 index 00000000..5dd0b122 --- /dev/null +++ b/arch/gemma4_bf16/gemma4_vision.h @@ -0,0 +1,321 @@ +/* gemma4_vision.h -- the vision tower of Gemma 4's large dense models (31B), for gemma4_bf16. + * + * The same tower family embgemma2 serves (transformers' Gemma4VisionModel), at the 31B's size and + * with the two parts that model leaves out: + * + * a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16, + * (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's + * column and one for its row ([2, 10240, width] table) + * 27 layers of width 1152: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v + * without one, a 2-D rotary over two 36-channel neox blocks a 72-wide head -- x (the column) + * over the first, y over the second, each block at theta^(-j / 18) (rope_type "default"; the + * embedding model spells the same rotary "axial") -- bidirectional attention within an image at + * scale 1, a gated gelu-tanh MLP + * pooling: the mean of each 3 x 3 window times sqrt(width) (the processor lays a window's nine + * patches out consecutively, raster order of windows, as the reference's position pooling) + * STANDARDISATION (vision_config.standardize): (z - std_bias) * std_scale per channel. The + * reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them; + * here z is the pooler's bf16 row, so those channels keep bf16's spacing at their magnitude + * (about 1e-2 after the scale -- measured against the reference, see vision.md). The bias row + * is made on the card: fill(-1) times std_bias, added to z; then times std_scale. + * the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows + * replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the + * image rows are not scaled). + * + * 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 stream. */ +#pragma once + +namespace gemma4_bf16 { + +using namespace rad::arch; + +struct Vision { + struct Layer { + rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0; + 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; + }; + bool on = false, standardize = 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; + rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0; + rad_op op_out = 0, op_sfill = 0, op_sbias = 0, op_sadd = 0, op_sscale = 0; + rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0, + b_py = 0, b_pool = 0, b_sb = 0, b_pn = 0, b_out = 0; + std::vector L; + + static bool present(const RadModelMeta* m) { + const char* t = rad_meta_gets(m, "vision_config.model_type", ""); + return t && !std::strcmp(t, "gemma4_vision"); + } + + int 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; + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0); + hd = rad_meta_geti(m, "vision_config.head_dim", 0); + ff = rad_meta_geti(m, "vision_config.intermediate_size", 0); + pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0); + npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0); + const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0); + const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0); + const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads); + const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6); + const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0); + const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", ""); + const char* act = rad_meta_gets(m, "vision_config.hidden_activation", ""); + standardize = rad_meta_geti(m, "vision_config.standardize", 0) != 0; + if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 || + depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads || + hd % 4) { + fprintf(stderr, "radiance: gemma4_bf16: the container's vision_config is incomplete or " + "not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv " + "%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width, + (long long)heads, (long long)hd, (long long)kvh, (long long)ff, + (long long)pool, (long long)depth); + return RAD_E_INVAL; + } + if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) || + (std::strcmp(rt, "default") && std::strcmp(rt, "axial")) || + std::strcmp(act, "gelu_pytorch_tanh")) { + fprintf(stderr, "radiance: gemma4_bf16: this vision tower uses clipped linears, a '%s' " + "rotary or a '%s' activation, which this plugin does not serve\n", + rt, act); + return RAD_E_UNSUPPORTED; + } + n_embd = model_embd; + patch_dim = 3 * patch * patch; + const int64_t kk = pool * pool; + P = ctx->max_enc_patches; + if (P % kk) P -= P % kk; + R = P / kk; + const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE; + const char* V = "model.vision_tower"; + + RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V))); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0)); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1)); + RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight"))); + w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model()); + w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model()); + if (standardize) { + RAD_ARCH_TRY(map_copy(b, nm.f("v.std_bias"), nm.ckpt("%s.std_bias", V))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.std_scale"), nm.ckpt("%s.std_scale", V))); + w_sbias = decl_w(b, nm.f("v.std_bias"), RAD_BF16, {width}, A, N, grp_model()); + w_sscale = decl_w(b, nm.f("v.std_scale"), RAD_BF16, {width}, A, N, grp_model()); + } + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const long long li = (long long)i; + const RadWeightGroup g = grp_layer(first_group + (int)i); + auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); }; + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li), + {src("self_attn.q_proj.linear.weight"), + src("self_attn.k_proj.linear.weight"), + src("self_attn.v_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li), + {src("mlp.gate_proj.linear.weight"), + src("mlp.up_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight"))); + l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g); + l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g); + l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g); + l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g); + l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g); + l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g); + l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g); + 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); + } + + 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_o = decl_b(b, nm.f("v.o"), 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_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff}); + b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff}); + b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width}); + b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width}); + b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width}); + b_sb = decl_b(b, nm.f("v.sb"), RAD_BF16, {R, width}); + b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width}); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd}); + + auto rms = [&](int64_t rows, rad_weight w) { + if (!w) + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) { + return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto add = [&](int64_t rows) { + return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + auto lookup = [&](rad_weight w) { + return RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width), + RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)), + RAD_WEIGHTS(w)); + }; + 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)), + RAD_WEIGHTS(w)); + }; + op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x}); + op_px = rw(b, lookup(w_px), {}, {b_px}); + op_py = rw(b, lookup(w_py), {}, {b_py}); + op_padd = rw(b, add(P), {b_px, b_py}, {b_px}); + op_add = rw(b, add(P), {b_x, b_px}, {b_x}); + /* Two neox blocks of hd / 4 pairs, x (staged plane 1, the column) then y (plane 0). */ + char sec[48]; + std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4)); + for (Layer& l : L) { + 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", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1), + RAD_STR("sections", sec), RAD_STR("comps", "1 0")), + RAD_WEIGHTS(l.q_norm, l.k_norm)), + {b_qkv}, {b_qkv}); + l.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", P), RAD_INT("window", 0)), + RAD_NOWEIGHTS), + {b_qkv}, {b_att}); + l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o}); + l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o}); + l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x}); + l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h}); + l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu}); + l.op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_gu}, {b_ff}); + l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o}); + l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o}); + l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x}); + } + op_pool = rw(b, RAD_OP(b, "pool_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_x}, {b_pool}); + if (standardize) { + op_sfill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width), + RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)), + RAD_NOWEIGHTS), + {}, {b_sb}); + op_sbias = rw(b, gain(w_sbias), {b_sb}, {b_sb}); + op_sadd = rw(b, add(R), {b_pool, b_sb}, {b_pool}); + op_sscale = rw(b, gain(w_sscale), {b_pool}, {b_pool}); + } + op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn}); + op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out}); + + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO; + e.patch_dim = patch_dim; + e.merge = kk; + e.max_patches = P; + e.n_embd = n_embd; + 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", + (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, + (long long)n_embd); + on = true; + return RAD_OK; + } + + void step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool; + if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) { + rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, " + "more patches than it was declared for, or not whole pooling windows"); + return; + } + const int64_t Rn = Pn / kk; + const int32_t* crd = batch->enc_coord; + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand rc = praw2(crd, RAD_I32, 2, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn)); + RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn)); + 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)); + 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)); + RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, 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)); + RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), 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)); + RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), 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)); + RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), 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)); + } + RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn)); + if (standardize) { + RAD_ISSUE_N(c, op_sfill, Rn, brows(b_sb, Rn)); + RAD_ISSUE_N(c, op_sbias, Rn, brows(b_sb, Rn), RAD_W(w_sbias), brows(b_sb, Rn)); + RAD_ISSUE_N(c, op_sadd, Rn, brows(b_pool, Rn), brows(b_sb, Rn), brows(b_pool, Rn)); + RAD_ISSUE_N(c, op_sscale, Rn, brows(b_pool, Rn), RAD_W(w_sscale), brows(b_pool, Rn)); + } + RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn)); + RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn)); + } +}; + +} /* namespace gemma4_bf16 */ diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index 9d8008e1..e44db1ea 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -217,6 +217,61 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( } } +// The `blocks` mode at any head_dim and section size (Gemma 4's vision tower: 72-wide heads, two +// sections of 18 pairs) -- what the register layout above cannot hold. A wave a head and a lane a +// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains, +// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot` +// are normed only; a v head (v_norm) is normed at unit gain. +__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( + uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw, + const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, + uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, + QkBlocks blk, uint32_t pplane) { + __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; + __shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf]; + const uint32_t m = blockIdx.x; + const uint32_t n_rope = n_head + n_head_kv; + const uint32_t n_norm = n_rope + (v_norm ? n_head_kv : 0); + const uint32_t half = rot / 2; + uint16_t* row = qkv + (size_t)m * ld; + const float div = rscale != 0.0f ? rscale : 1.0f; + for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) { + int c = 0, s0 = 0; + while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; } + const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div; + const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]); + sincosf(p * inv, &sn_s[i], &cs_s[i]); + pa_s[i] = 2 * s0 + ((int)i - s0); + pb_s[i] = pa_s[i] + blk.sec[c]; + } + __syncthreads(); + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (uint32_t hh = wave; hh < n_norm; hh += kQkThreads / 32) { + uint16_t* h = row + hh * head_dim; + float ss = 0.0f; + for (uint32_t e = lane; e < head_dim; e += 32) { const float v = bf2f(h[e]); ss += v * v; } + ss = r4d_wave_sum(ss); + const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps); + const bool is_v = hh >= n_rope; + const uint16_t* w = hh < n_head ? qw : kw; + auto nrm = [&](uint32_t e) { + const float g = is_v ? 1.0f : bf2f(w[e]) + wadd; + return bf2f(f32_to_bf16(bf2f(h[e]) * sc * g)); + }; + if (is_v) { + for (uint32_t e = lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e)); + continue; + } + for (uint32_t i = lane; i < half; i += 32) { + const uint32_t a = (uint32_t)pa_s[i], b = (uint32_t)pb_s[i]; + const float x0 = nrm(a), x1 = nrm(b); + h[a] = f32_to_bf16(x0 * cs_s[i] - x1 * sn_s[i]); + h[b] = f32_to_bf16(x0 * sn_s[i] + x1 * cs_s[i]); + } + for (uint32_t e = rot + lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e)); + } +} + // ---------------------------------------------------------------------------- pool_rows // ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to // bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column. @@ -541,21 +596,32 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M const QkBlocks* blk, int pplane, long stream) { if (!qkv || !pos || !qw || !kw) return -1; if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim || - (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || head_dim % 32 || - mode < 0 || mode > 2) + (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 2) return -2; + if (mode != 2 && head_dim % 32) return -2; if (mode == 1 && head_dim % 64) return -2; if (mode == 0 && (rot / 2) % 32) return -2; QkBlocks b{}; + bool any = false; /* the blocks mode outside the register layout: qk_norm_rope_any_kernel */ if (mode == 2) { if (!blk || blk->n <= 0 || blk->n > 8) return -2; b = *blk; int total = 0; for (int c = 0; c < b.n; ++c) { - if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) return -2; + if (b.sec[c] <= 0) return -2; + if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) any = true; total += b.sec[c]; } if (2 * total != rot) return -2; + if (head_dim % 32) any = true; + } + if (any) { + hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, + (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, + (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, + (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, + eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane); + return hipGetLastError() == hipSuccess ? 0 : -4; } #define R4D_QN(MD) \ hipLaunchKernelGGL(qk_norm_rope_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, \ @@ -766,12 +832,14 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { return R4D_NO(RAD_E_SHAPE); /* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a * 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */ - if (hd % 32 || hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); int md = 0; if (mode && !std::strcmp(mode, "gptj")) md = 1; else if (mode && !std::strcmp(mode, "blocks")) md = 2; else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); + /* Any head_dim in the blocks mode (qk_norm_rope_any_kernel); the others need multiples of 32. */ + if (md != 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); QkBlocks blk{}; long long M = 0, pplane = 0; if (md == 2) { diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index da325c7b..29b01c6e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2801,7 +2801,7 @@ static const RadConstraint cAttnDenseH512G4[] = { /* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to * 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */ static const RadConstraint cQkNormRope[] = { - C_LE("head_dim", 1024), C_DIV("head_dim", 32), + C_LE("head_dim", 1024), C_DIV("head_dim", 2), }; /* ---- gated delta net ----------------------------------------------------------------------- */ @@ -3778,9 +3778,10 @@ static const RadKernelInfo kKernels[] = { { "qk_norm_rope_bf16", "qk_norm_rope", "attn", "per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place", - "head_dim a multiple of 32 up to 1024, neox (rotary_dim / 2 a multiple of 32), gptj, or " - "blocks (sections of 16 or a multiple of 32 pairs, each starting on a 32-channel slice); one " - "workgroup a token and a wave a head, sin/cos computed once for all its heads", + "head_dim up to 1024, a multiple of 32 for neox (rotary_dim / 2 a multiple of 32) and gptj; " + "blocks at any even head_dim and section size (sections of 16 or a multiple of 32 pairs, each " + "on a 32-channel slice, in registers; others a lane a pair); one workgroup a token and a wave " + "a head, sin/cos computed once for all its heads", "bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRope), NOTUNE,