diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 382e99f6..f6ede317 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -1712,12 +1712,14 @@ struct Model { /* Per-layer embeddings (hidden_size_per_layer_input > 0): the token-identity table * (embed_tokens_per_layer, n_layer x n_ple wide), the context projection of the scaled * embedding and its per-(token, layer) norm, combined into `b_ple` [max_tok, n_layer * n_ple] - * that every layer reads its slice of. */ + * that every layer reads its slice of. At two ranks the table is vocab-sharded like the token + * table, and its lookup is reduced the same way (op_ple_ar). The rest of the branch is + * replicated, so no layer reduces it. */ int64_t n_ple = 0; rad_weight w_ple_tok = 0, w_ple_norm = 0; G4Linear ln_ple_proj{}; rad_buf b_ple = 0, b_ple_tok = 0, b_pg = 0; - rad_op op_ple_tok = 0, op_ple_norm = 0, op_ple_add = 0; + rad_op op_ple_tok = 0, op_ple_ar = 0, op_ple_norm = 0, op_ple_add = 0; /* An image's placeholder positions take the token-identity row of pad_token_id, as the * reference looks them up (Gemma4Model.forward: llm_input_ids = pad where multimodal): that row * times sqrt(n_ple), made as fill(sqrt(n_ple)) * the row, scattered over the image rows. */ @@ -2030,10 +2032,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.n_ple < 0) { fprintf(stderr, "radiance: gemma4: hidden_size_per_layer_input %lld is negative\n", (long long)m.n_ple); return RAD_E_INVAL; } if (m.n_ple > 0) { const int64_t v_ple = meta_text_geti(meta, "vocab_size_per_layer_input", g.n_vocab_all); - if (g.world > 1) { + if (g.world > 2) { fprintf(stderr, "radiance: gemma4: per-layer embeddings (hidden_size_per_layer_input %lld) " - "are served at one rank only; this model is small enough for one card\n", - (long long)m.n_ple); + "are served at one or two ranks, not %d: the four-rank junctions keep " + "a rank's rows only, and the per-layer branch reads every row\n", + (long long)m.n_ple, g.world); return RAD_E_UNSUPPORTED; } if (v_ple != g.n_vocab_all) { @@ -2216,6 +2219,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("mult", std::sqrt((double)m.n_ple))), RAD_WEIGHTS(m.w_ple_tok)), {}, {m.b_ple_tok}); + /* A rank's lookup writes zeros for ids outside its vocabulary slice; the all-reduce makes + * every row whole. */ + if (g.world > 1) { + m.op_ple_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", P, g.max_tok * P), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_ple_tok}, {m.b_ple_tok}); + if (!m.op_ple_ar) return RAD_E_INVAL; + } RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"), { nm.ckpt("model.language_model.per_layer_model_projection.weight") }, P, g.n_embd, RAD_SHARD_NONE, grp_model(), m.b_x, m.b_ple)); @@ -2417,7 +2431,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * the bits it gives the whole. The buffer the second lane reduces in place is taken out of the * arena's sharing, which the runtime asks of every buffer a second lane touches; it lives * across the whole trunk already. */ - m.overlap = g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows; + /* Not with per-layer embeddings: the slices close each layer through j_ma alone, without the + * per-layer branch. */ + m.overlap = g.world > 1 && g.wire_exact && m.fuse && m.n_ple == 0 && + g.max_tok >= 2 * kOverlapRows; for (const Layer& lay : m.layers) m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar; if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h)); @@ -2602,6 +2619,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c rad_note(b, "prefill overlap: off (%s)", !g.wire_exact ? "the lossy all-reduce wire" : !m.fuse ? "the residual junctions are not fused" + : m.n_ple > 0 ? "the per-layer branch is not split into slices" : "a step holds fewer than two slices"); } if (m.fuse && (g.world == 2 || g.world == 4)) { @@ -2827,6 +2845,9 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.n_ple > 0) { RAD_ISSUE(c, m.op_ple_tok, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_ple_tok), brows(m.b_ple_tok, T)); + /* before the pad rows of image positions go in: every rank writes those whole */ + if (m.op_ple_ar) + RAD_ISSUE_N(c, m.op_ple_ar, T * m.g.n_layer * m.n_ple, brows(m.b_ple_tok, T), RAD_NONE); if (m.op_ple_pscat && batch->n_mm_rows > 0) { const int64_t nm_rows = batch->n_mm_rows; RAD_ISSUE_N(c, m.op_ple_pfill, nm_rows, brows(m.b_ple_pad, nm_rows)); @@ -2864,8 +2885,10 @@ static void step(RadCtx* c, const RadBatch* batch) { } } if (m.fuse && !last) { - /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ - l.j_ma.step(c, T, far); + /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op. + * With per-layer embeddings it closes the branch, whose output every rank holds whole + * (the feed-forward's reduction ran above): no all-reduce in front. */ + l.j_ma.step(c, T, far && !ple); } else { /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after * the mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 55007e9e..1231d7df 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3853,13 +3853,103 @@ TEST(a_gemma4_e4b_form_shares_kv_and_runs_the_per_layer_branch) { } } -/* The per-layer branch is not split across ranks, and a model whose every layer shares KV has no - * cache to read. */ +/* At two ranks the per-layer table is vocab-sharded like the token table and its lookup is reduced + * like the token lookup, before anything reads it; the rest of the branch is replicated. A step + * reduces the two lookups and, a layer, attention's and the feed-forward's partial sums -- folded + * into the attention junction where it resolves -- and never the branch's output, which every rank + * holds whole. The prefill overlap, whose slices skip the branch, stays off. */ +TEST(the_gemma4_e4b_form_runs_at_two_ranks) { + const int64_t L = 12, P = 12 * 64; + for (bool w4 : { false, true }) { + for (int rank : { 0, 1 }) { + RadBuilder b; + if (w4) { + const RadEncoding e = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); + b.encs = { { "attn_q.", e }, { "attn_k.", e }, { "attn_v.", e }, { "attn_o.", e }, + { "ffn_gate_up.", e }, { "ffn_down.", e } }; + } + RadModelMeta meta = gemma4_e4b_meta(); + RadBuildCtx ctx = build_ctx(rank, 2); + ctx.max_tok = 4096; /* past two slices of the overlap */ + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK(!gemma4_bf16::g_model[rank].overlap); + CHECK_EQ(gemma4_bf16::g_model[rank].fuse, w4); + + /* the per-layer table takes the token table's slice of the vocabulary */ + const RecOp* tok = find_op(b, "embed_lookup", 0); + const RecOp* ple = find_op(b, "embed_lookup", 1); + REQUIRE(tok != nullptr && ple != nullptr); + CHECK_EQ(pint(ple, "n_embd"), P); + CHECK_EQ(pint(ple, "n_vocab"), pint(tok, "n_vocab")); + CHECK_EQ(pint(ple, "vocab_offset"), pint(tok, "vocab_offset")); + + RadBatch batch = decode_batch(); + RadCtx c; c.b = &b; c.rank = rank; c.world = 2; c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + REQUIRE(ops.size() > 4); + CHECK_EQ(ops[0], std::string("embed_lookup")); + CHECK_EQ(ops[1], std::string("all_reduce")); + CHECK_EQ(ops[2], std::string("embed_lookup")); + CHECK_EQ(ops[3], std::string("all_reduce")); + CHECK_EQ(c.issues[3].n, batch.n_tok * P); + const int folded = count_issued(ops, "ar_rmsnorm_quant_i8"); + CHECK_EQ(count_issued(ops, "all_reduce") + folded, (int)(2 + 2 * L)); + CHECK_EQ(folded, w4 ? (int)L : 0); + } + } +} + +/* With an image at two ranks, the pad rows of the image positions go into the per-layer inputs + * after their lookup's all-reduce: every rank writes them whole, so before it they would count + * twice. */ +TEST(the_gemma4_e4b_form_writes_image_pad_rows_after_the_per_layer_all_reduce) { + std::vector keys(std::begin(k_gem4e_keys), std::end(k_gem4e_keys)); + std::vector vals(std::begin(k_gem4e_vals), std::end(k_gem4e_vals)); + const char* vk[] = { "vision_config.model_type", "vision_config.hidden_size", + "vision_config.num_attention_heads", "vision_config.head_dim", + "vision_config.intermediate_size", "vision_config.pooling_kernel_size", + "vision_config.position_embedding_size", "vision_config.num_hidden_layers", + "vision_config.patch_size", "vision_config.rope_parameters.rope_theta", + "vision_config.rope_parameters.rope_type", "vision_config.hidden_activation" }; + const char* vv[] = { "gemma4_vision", "768", "12", "64", "3072", "3", "10240", "2", "16", "100", + "default", "gelu_pytorch_tanh" }; + keys.insert(keys.end(), std::begin(vk), std::end(vk)); + vals.insert(vals.end(), std::begin(vv), std::end(vv)); + static const int32_t rows[] = { 4, 5, 6, 7, 8, 9, 10, 11 }; + static uint16_t embd[8 * 5376]; + for (int rank : { 0, 1 }) { + RadBuilder b; + RadModelMeta meta = gemma4_e4b_meta(); + meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data(); + RadBuildCtx ctx = build_ctx(rank, 2); + ctx.max_enc_patches = 9 * 64; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + RadBatch batch = prefill_batch(); + batch.n_mm_rows = 8; batch.mm_rows = rows; batch.mm_embd = embd; + RadCtx c; c.b = &b; c.rank = rank; c.world = 2; c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + size_t i = 0; /* the per-layer lookup: the second embed_lookup */ + for (int seen = 0; i < ops.size(); ++i) + if (ops[i] == "embed_lookup" && ++seen == 2) break; + REQUIRE(i + 4 < ops.size()); + const std::vector want = { "all_reduce", "fill", "mul_weight", "scatter_rows" }; + CHECK(std::vector(ops.begin() + (long)i + 1, ops.begin() + (long)i + 5) == want); + } +} + +/* The per-layer branch is served at one or two ranks, and a model whose every layer shares KV has + * no cache to read. */ TEST(the_gemma4_e4b_form_is_refused_where_it_cannot_run) { { RadBuilder b; RadModelMeta meta = gemma4_e4b_meta(); - RadBuildCtx ctx = build_ctx(0, 2); + RadBuildCtx ctx = build_ctx(0, 4); CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED); } {