From 157450a82ba7c246ec5f3660c4775a60144719e2 Mon Sep 17 00:00:00 2001 From: Boris Manojlovic Date: Tue, 27 Oct 2026 20:02:33 +0100 Subject: [PATCH] gemma4_bf16: per-layer MLP width for use_double_wide_mlp (Gemma 4 E2B), and the bf16 descriptor for unmodified Google E2B/E4B directories --- arch/gemma4_bf16/gemma4_bf16.cpp | 40 +++++++++++++++--- core/format/checkpoint.cpp | 19 ++++++++- docs/ARCHITECTURES.md | 6 ++- tests/arch_test.cpp | 69 ++++++++++++++++++++++++++++++++ tests/checkpoint_test.cpp | 41 +++++++++++++++++++ 5 files changed, 168 insertions(+), 7 deletions(-) diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 52a56ffb..43fd0f71 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -57,6 +57,15 @@ static int g4_parse_types(const char* lt, int64_t n, std::vector& is_global return RAD_OK; } +/* A config boolean, flattened as "true"/"false" (`use_double_wide_mlp`). */ +static bool g4_getb(const RadModelMeta* m, const char* k, bool dflt) { + const char* s = meta_text_gets(m, k, nullptr); + if (!s) return dflt; + if (!std::strcmp(s, "true") || !std::strcmp(s, "True")) return true; + if (!std::strcmp(s, "false") || !std::strcmp(s, "False") || !std::strcmp(s, "null")) return false; + return std::atoll(s) != 0; +} + static int g4_schedule(const RadModelMeta* m, int64_t n, int64_t interval, std::vector& is_global) { const char* lt = meta_text_gets(m, "layer_types", nullptr); @@ -996,7 +1005,7 @@ struct Gemma4Mlp { struct Wire { rad_buf x = 0, h = 0, gu = 0, ffn = 0; }; Wire w{}; - Geom g{}; + Geom g{}; /* g.n_ff is this layer's width (double-wide layers are wider) */ int layer = 0; rad_weight w_norm = 0, w_post = 0; /* the norms (always bf16) */ G4Linear ln_gu{}, ln_down{}; /* the GEMM weights (bf16 or w4a8) */ @@ -1008,7 +1017,8 @@ struct Gemma4Mlp { rad_op op_pf = 0; rad_weight pf_w = 0; - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre); + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre, + int64_t n_ff); void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, bool ar_fused = false) const; /* For the prefill overlap, over rows [r0, r0 + n): the arm from the pair a junction wrote to @@ -1037,8 +1047,9 @@ void Gemma4Mlp::tail(RadCtx* c, int64_t r0, int64_t n) const { brow_slice(w.x, r0, n, E)); } -int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre) { - g = geom; layer = l; w = wire; +int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, + const char* pre, int64_t n_ff) { + g = geom; layer = l; w = wire; g.n_ff = n_ff; /* The norms: always bf16 (no rule matches them), name map first. */ RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l))); @@ -1738,6 +1749,9 @@ struct Model { rad_buf b_qg = 0, b_kg = 0, b_vg = 0, b_atting = 0; /* global rows */ rad_buf b_qkvs = 0, b_qkvg = 0; /* the fused projections' rows, where a layer has one */ rad_buf b_gu = 0, b_ffn = 0; + /* ...and the double-wide layers' own pair, since a GEMM reads its activation packed (a narrow + * layer in the wide buffer would read a padded row). Declared only for use_double_wide_mlp. */ + rad_buf b_gu_w = 0, b_ffn_w = 0; rad_weight w_tok = 0, w_out = 0, w_lm = 0; rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0, op_cap = 0; @@ -2130,6 +2144,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } } + /* A double-wide MLP (use_double_wide_mlp, Gemma 4 E2B): the layers from first_shared on have + * 2 * intermediate_size, as transformers' Gemma4TextMLP builds them (`use_double_wide_mlp and + * is_kv_shared_layer`). Each layer declares its own weights and op widths, and the two widths + * keep a pair of activation buffers each (b_gu_w). */ + const bool wide_mlp = g4_getb(meta, "use_double_wide_mlp", false) && kv_shared > 0; + const int64_t n_ff_wide = 2 * g.n_ff; + /* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s); * the global class is built from the container header. */ m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim; @@ -2169,6 +2190,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_atting= decl_b(b, nm.f("attn_outg"), g.act_dtype, {g.max_tok, m.cg.q_dim()}); m.b_gu = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); + if (wide_mlp) { + m.b_gu_w = decl_b(b, nm.f("gate_up_wide"), g.act_dtype, {g.max_tok, 2 * n_ff_wide}); + m.b_ffn_w = decl_b(b, nm.f("ffn_wide"), g.act_dtype, {g.max_tok, n_ff_wide}); + if (!m.b_gu_w || !m.b_ffn_w) return RAD_E_INVAL; + } m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); @@ -2336,7 +2362,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre, lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l])); - RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre)); + /* The double-wide layers write their own pair of buffers (see b_gu_w). */ + Gemma4Mlp::Wire lw = mw; + const bool wide = wide_mlp && l >= first_shared; + if (wide) { lw.gu = m.b_gu_w; lw.ffn = m.b_ffn_w; } + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, lw, pre, wide ? 2 * g.n_ff : g.n_ff)); /* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */ RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.layer_scalar", (int)l), diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 06828b71..5877dff6 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -267,12 +268,28 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { /* The quantisation descriptor, which with the architecture selects the plugin (spec ยง2.4): the * quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from - * bf16 releases. */ + * bf16 releases. + * + * A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is the bf16 release that + * arch/gemma4_bf16 serves as compressed-tensors, which is what rad-convert's + * `--set quantization_config.quant_method=compressed-tensors` said by hand. Its per-layer + * embeddings or shared KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape + * and refuses those two keys, so the bare (gemma4, "") descriptor must not win. */ std::string quant_descriptor(const MetaOwn& m) { std::string q; if (const char* qm = m.get("quantization_config.quant_method")) { q = qm; if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; } + return q; + } + if (m.arch == "gemma4") { + auto gi = [&](const char* k) -> int64_t { + const char* v = m.get(std::string("text_config.") + k); + if (!v) v = m.get(k); + return v ? std::strtoll(v, nullptr, 10) : 0; + }; + if (gi("hidden_size_per_layer_input") > 0 || gi("num_kv_shared_layers") > 0) + q = "compressed-tensors"; } return q; } diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 81a680bf..60db81a1 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -1078,10 +1078,14 @@ reads change no value; on 4x R9700 the 31B with DFlash2 decoded 15% faster with a drafter about 2%. **The E2B/E4B form.** `arch/gemma4_bf16` serves Gemma 4's small dense form (tested on -NVIDIA-Nemotron-3.5-Bolt-E4B, `deploy/compose/nemotron-3.5-bolt-e4b-bf16.yaml`) at one rank: +NVIDIA-Nemotron-3.5-Bolt-E4B, `deploy/compose/nemotron-3.5-bolt-e4b-bf16.yaml`, and on Google's +gemma-4-E2B-it) at one rank: - KV-shared layers: from layer `n_layer - num_kv_shared_layers` on, a layer projects q only and attends over the cache of the last earlier layer of its class that keeps one (E4B: sliding layers read 22, full layers 23). Shared layers are not bound to a KV group, so their pages hold nothing. +- Double-wide MLP (`use_double_wide_mlp`, E2B): those same layers have 2 * `intermediate_size` in + both projections. Each layer declares its own weight shapes and op widths, and the two widths keep + a pair of activation buffers each. - Per-layer embeddings (`hidden_size_per_layer_input`): a token table scaled by sqrt(width), plus the normed projection of the scaled embedding, mixed at 2^-0.5. Each layer runs a branch after its feed-forward: gate, gelu times its slice, projection, norm, add. On a w4a8 or w8a8 trunk diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 8f165c72..afdf099b 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4469,6 +4469,27 @@ RadModelMeta gemma4_e4b_meta() { return m; } +/* E2B: the same twelve layers with `use_double_wide_mlp`, so the four KV-shared layers (8..11) + * declare 2 * intermediate_size (transformers' Gemma4TextMLP). */ +RadModelMeta gemma4_e2b_meta() { + static const std::vector keys = [] { + std::vector v(std::begin(k_gem4e_keys), std::end(k_gem4e_keys)); + v.push_back("use_double_wide_mlp"); + return v; + }(); + static const std::vector vals = [] { + std::vector v(std::begin(k_gem4e_vals), std::end(k_gem4e_vals)); + v.push_back("true"); + return v; + }(); + RadModelMeta m = gemma4_e4b_meta(); + m.name = "test-gemma4-e2b-form"; + m.n_kv = (int)keys.size(); + m.kv_key = keys.data(); + m.kv_val = vals.data(); + return m; +} + /* Layers 8..11 keep no cache: only 0..7 are bound, and each shared layer's attention reads the last * earlier layer of its class that keeps one (sliding 8..10 -> 7, global 11 -> 5). Every layer runs * the per-layer branch (gate, gelu times its slice, projection, norm, add), and the step lints @@ -4680,6 +4701,54 @@ TEST(the_gemma4_e4b_form_replicates_kv_heads_at_four_ranks) { } } +/* A double-wide MLP is per layer: layers 0..7 declare gate_up [2F, E] and down [E, F] with F = + * intermediate_size, layers 8..11 [4F, E] and [E, 2F], and every activation op carries its layer's + * width. The shared `gate_up` and `ffn` buffers hold the widest layer, so a narrow layer's slice + * keeps the wide row pitch. */ +TEST(a_gemma4_e2b_form_declares_the_double_wide_layers) { + RadBuilder b; + RadModelMeta meta = gemma4_e2b_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + const int64_t E = meta.n_embd, F = meta.n_ff; + for (int l : { 0, 7, 8, 11 }) { + const int64_t w = l >= 8 ? 2 * F : F; + const RecWeight* gu = find_w(b, "blk." + std::to_string(l) + ".ffn_gate_up.weight"); + const RecWeight* dn = find_w(b, "blk." + std::to_string(l) + ".ffn_down.weight"); + REQUIRE(gu != nullptr && dn != nullptr); + CHECK_EQ(gu->d.shape[0], 2 * w); + CHECK_EQ(gu->d.shape[1], E); + CHECK_EQ(gu->d.n_row_parts, 2); + CHECK_EQ(gu->d.row_parts[0], w); + CHECK_EQ(gu->d.row_parts[1], w); + CHECK_EQ(dn->d.shape[0], E); + CHECK_EQ(dn->d.shape[1], w); + } + for (int l = 0; l < 12; ++l) { + const RecOp* act = find_op(b, "gelu_mul", l); + REQUIRE(act != nullptr); + CHECK_EQ(pint(act, "n"), l >= 8 ? 2 * F : F); + } + /* The narrow and the wide layers keep their own pair, since a GEMM reads its activation packed. */ + const RecBuf* gu = find_b(b, "gate_up"); + const RecBuf* ff = find_b(b, "ffn"); + const RecBuf* guw = find_b(b, "gate_up_wide"); + const RecBuf* ffw = find_b(b, "ffn_wide"); + REQUIRE(gu != nullptr && ff != nullptr && guw != nullptr && ffw != nullptr); + CHECK_EQ(gu->d.shape[0], ctx.max_tok); + CHECK_EQ(gu->d.shape[1], 2 * F); + CHECK_EQ(ff->d.shape[1], F); + CHECK_EQ(guw->d.shape[1], 4 * F); + CHECK_EQ(ffw->d.shape[1], 2 * F); + + RadBatch batch = decode_batch(); + RadCtx c{ .b = &b, .batch = &batch, .world = 1 }; + gemma4_bf16::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); +} + /* A world the heads do not divide over, and a model whose every layer shares KV, are refused. */ TEST(the_gemma4_e4b_form_is_refused_where_it_cannot_run) { { diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 3635dc85..6c26b1ce 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -165,6 +165,47 @@ TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) { CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3")); } +/* Google's bf16 E2B needs no `--set quantization_config.quant_method`: its per-layer embeddings + * name the E form, which arch/gemma4 refuses and arch/gemma4_bf16 serves. */ +TEST(a_gemma4_e2b_checkpoint_selects_the_bf16_plugin_on_its_own) { + const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, + "{\"model_type\":\"gemma4\",\"text_config\":{\"hidden_size\":1536," + "\"intermediate_size\":6144,\"hidden_size_per_layer_input\":256," + "\"num_kv_shared_layers\":20,\"use_double_wide_mlp\":true}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("gemma4")); + CHECK_EQ(ck.meta().quant, std::string("compressed-tensors")); +} + +/* E4B states shared KV layers without per-layer embeddings; either key selects the same plugin. */ +TEST(a_gemma4_e4b_checkpoint_selects_the_bf16_plugin_on_its_own) { + const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, + "{\"model_type\":\"gemma4\",\"text_config\":{\"hidden_size\":2560," + "\"intermediate_size\":10240,\"num_kv_shared_layers\":6," + "\"use_double_wide_mlp\":false}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK_EQ(ck.meta().quant, std::string("compressed-tensors")); + /* The rule is gemma4's: another architecture with the same key keeps its own descriptor. */ + const std::string other = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, + "{\"model_type\":\"ltx2\",\"text_config\":{\"num_kv_shared_layers\":6}}"); + Checkpoint ok; + REQUIRE_EQ(ok.open(other), RAD_OK); + CHECK_EQ(ok.meta().quant, std::string()); +} + +/* The 26B-A4B/31B shape declares neither key and keeps the bare descriptor arch/gemma4 owns. */ +TEST(a_gemma4_31b_checkpoint_keeps_the_bare_descriptor) { + const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, + "{\"model_type\":\"gemma4\",\"text_config\":{\"hidden_size\":5376," + "\"intermediate_size\":21504,\"num_hidden_layers\":62}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("gemma4")); + CHECK_EQ(ck.meta().quant, std::string()); +} + TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) { const std::string dir = write_checkpoint({ bf16("a.weight", { 4, 8 }, 1.0f) }, "{}"); Checkpoint ck;