Skip to content

model, models: gemma-embedding2's header reader, with an EncoderSpec on ModelSpec - #238

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-reader
Oct 15, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-reader

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Part of #59 (plan and PR order in #190), E1: step 1 of docs/contrib/new-model.md, the header reader.

What and why

Release notes: Under the hood: the model reader recognizes gemma-embedding2 GGUF files and lists what no program runs yet; such a file does not serve yet.

A gemma-embedding2 file now reads into a ModelSpec and a role for every tensor, and coverage::check lists what no program runs. On the Q8_0 file the list is, for each of the 24 layers, the bidirectional attention at the layer's head (bidirectional GQA flash, head 256, group 2, 512 keys each side on a sliding layer, head 512, group 4 on a full one), its q/k norm and rope (per-head QK norm plus rope: head 256, NeoX, 256 of 256 dims, or 512) and dense GELU GLU layer: ff 2048; then a layer program for gemma-embedding2 and pre-tokenizer gemma4. Several parts have no item of their own yet: the per-layer input, the gainless V norm, the trained scalar on each layer's output, the norms after the attention and FFN blocks, the scale on the token rows, the output projection and the mean pooling. They come under the layer program item now, and the body PR adds a Need for each before program_of returns a program. No program runs the model yet. The body, the tokenizer and the serve seat are later PRs.

This PR proposes one new field on the spec, and the trunk keeps the types it has (question 4 of #190 is open; see the next section):

  • ModelSpec::encoder: Option<EncoderSpec> (crates/models/src/encoder.rs, new). None on every decoder reader. For this model it holds three facts: each layer's reach (keys on each side of a row; None on the full layers), the per-layer input width (embedding_length_per_layer_input, 512) and the output projection widths ([768]). The layers stay Gqa with window: None, and Gqa::window's doc says so. EmbeddingGemma (v1, gemma-embedding) fits the same struct with per_layer: None and proj: [3072, 768]; its reader is E8 of model: EmbeddingGemma and EmbeddingGemma 2 on a side seat #190, the second user of those two fields.
  • The per-layer input is not Extra::Ple. That site is an n-gram hash table with a causal conv. Here each layer's input is a slice of one projection of the token rows (per_layer_model_proj), so the spec records only its width. The per-layer stems take Role::EngramDense. The two model-level tensors (per_layer_model_proj.weight, per_layer_proj_norm.weight) take it too for now; common placement refuses an EngramDense tensor with no layer, so the body PR places them.
  • The window. The file's attention.sliding_window is 1024, and llama.cpp masks a key when |i - j| > sliding_window / 2 (LLAMA_SWA_TYPE_SYMMETRIC), so reach is 512 on each side. The reader stores the reach, not the file's number, so no consumer halves it again.
  • Act::GeGlu. The FFN is gelu(gate) * up with tanh GELU. It is a new Act arm, like Act::ReluSqr for Nemotron. Act::what() names an activation for a refusal, and the decoder bodies that matched ReluSqr by name now refuse every non-SwiGLU arm through it with the same text.
  • Need::Bidirectional. An encoder's attention layer needs a bidirectional flash kernel, not the causal one. needs() emits Need::Bidirectional { head, group, reach } for every Gqa layer of an encoder. This matters because coverage treats a need as covered when any program's AVAILABLE row covers it if the arch has no program; a Need::Gqa here would read as covered by the decoders' causal rows. Need::GeGlu is new for the same reason.
  • No tool-call item for an encoder. The file carries a chat template (it joins text and media placeholders), so without a guard coverage would ask for a tool-call parser. The guard is spec.encoder.is_none().
  • The pre-tokenizer. The file has tokenizer.ggml.model = gemma4 and no tokenizer.ggml.pre. llama.cpp sets the pre-tokenizer to gemma4 for that tokenizer model (src/llama-vocab.cpp), so the reader does the same and records it in Read::defaults. Another name in either key is refused by name. template_of is lifted out of chat_of so both readers take the template one way.

The reader refuses by name: a missing key (attention.causal and attention.shared_kv_layers may be absent); pooling_type other than mean; attention.causal = true; a nonzero attention.shared_kv_layers; a value head other than the key head; a rope count that is odd or larger than the head; a head_count_kv of 0 or one that does not divide the heads; a sliding_window_pattern of the wrong length or not of bools; a tensor missing or of other dims than the keys give; and a tensor not in the role table. Tensors are checked in two passes: every missing tensor is listed at once, and only when none is missing is every tensor of other dims listed. Tensor names and their dims come from mainline llama.cpp src/models/gemma-embedding2.cpp and src/llama-arch.cpp. Every stem is required there (no TENSOR_NOT_REQUIRED), and the reader requires them too.

Header facts the meta test pins (embeddinggemma-2-Q8_0.gguf, ggml-org/embeddinggemma-2-GGUF, 309,855,456 B):

Full layers 5, 11, 17, 23 The 20 sliding layers
Head (key = value) 512 256
Key and value heads 1 2
Rope (NeoX) 512 values, base 1e6 256 values, base 1e4
Reach every key 512 each side

Hidden 512, 4 query heads, FFN 2048, per-layer input 512, output 768, vocabulary 262,144, context_length 262,144, 413 tensors. per_layer_model_proj.weight is BF16 [512, 12288]; the coverage list has no item for that weight format.

Question 4 of #190

#190 asks whether the reader should describe an encoder with an EncoderSpec beside ModelSpec or with an encoder variant of ModelSpec, and says E1 follows the answer. That question has no answer yet. This PR proposes a third shape, an Option<EncoderSpec> field inside ModelSpec, so needs() and coverage::check read one value. What each shape costs:

  • A field (this PR). One encoder: None line at each of the ten existing ModelSpec sites; needs() picks the attention need by spec.encoder, and the tool-call item is skipped for an encoder.
  • Beside ModelSpec. Read carries a second value, and needs() and coverage::check take it as a second argument at every call site.
  • A variant of ModelSpec. Every reader's ModelSpec construction and every consumer that reads the decoder fields changes.
  • The attention kind and reach on the layer (Gqa gains a direction and a two-sided reach). No new spec type, but every Gqa literal in the tree changes, and the facts past the trunk (per-layer input, output projection) still need a home.

If the maintainer picks another shape, this PR changes to it.

Common-owner table

Owner This model Why
Placement plan does not attach No routed experts. The whole model and its activations are one fixed size, placed beside the chat model's plan.
Kernel table attaches (body PR) Q8_0 dense GEMM rows; the body picks through the table.
Card expert leg does not attach Dense model, no experts.
Residency does not attach No experts; every weight stays on the card.
Expert tier does not attach Same.
Prompt walk does not attach Non-causal: each row reads the rows after it, so an input is one pass, not a walk over chunks.
Resident slots does not attach Nothing stays between requests (no KV).
Serve seat attaches (seat PR) A side seat beside the chat model.
Timing attaches (seat PR) Through the serve seat.

This PR attaches none of them: it is the reader.

Steps of new-model.md

Step Here How it was checked
1. GGUF arch reading crates/model/src/arch/gemma_embedding2/{hparams,names,roles,spec}.rs, the Arch arms, program_of (None) The synthetic-header tests in spec.rs (a 6-layer model with both layer kinds, every refusal above) and the hw_ meta test on the real file, both on a DGX Spark; see "What I ran"
10. Gates and recipes (bookkeeping) gate-gemma-embedding2-meta, tools/gate-paths.tsv rows, tools/hf-arch-check.py mirror just mac-static (check-recipes), python3 tools/hf-arch-check.py --self-test

Steps 2 to 9 are later PRs. place.rs comes with the body, where the bytes are known.

Code shape

  • No second copy. template_of is lifted out of chat_of. The overflow-checked product (mul, nemotron_h's) the per-layer array's length check (per_layer_items, which per_layer_count, mimo2's pattern and the MTP sidecar's layer_item each carried) and the tensor dims check (tensors_agree: every missing name first, then every tensor of other dims, which nemotron_h's dims_agree ran on its own) now have one owner in crates/model/src/arch/mod.rs, and nemotron_h, mimo2 and the new reader call them. The new reader also calls the existing helpers (positive, optional_usize, meta_bool, per_layer_count, blk, the shared names, classify_with).
  • Model code holds only architecture facts. The common owners gained an encoder field, two Need variants and one Act arm, each a fact of the attention or FFN kind. No body gained a model branch: the bodies that matched Act::ReluSqr now refuse every non-SwiGLU arm through Act::what().
  • Dead code is gone.
  • No silent failure. Every key and tensor the reader does not accept is refused by name (list above). spec_of refuses an Hparams whose per-layer lists are not one per layer instead of indexing past them.
  • Comments state what is true now. tools/check-comments.sh passes.
  • No relaxed gate.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up (41, the ratchet's 41).

Duplication found or removed: removed crates/model/src/arch/nemotron_h/hparams.rs mul and the loop in its dims_agree (now tensors_agree, crates/model/src/arch/mod.rs:323), the length checks in crates/model/src/arch/mod.rs per_layer_count, crates/model/src/arch/mimo2/hparams.rs pattern and crates/model/src/arch/mimo2/mtp.rs layer_item, and chat_of's template read (now template_of). Found and left as they are: crates/model/src/arch/glm5next/hparams.rs:596 kinds runs the same length check, and glm5next/hparams.rs:650 and deepseek41/hparams.rs:1445 per_layer_f32 run it after a scalar fallback; each can call per_layer_items in a follow-up.

What I ran

All runs are at the head 6b886f6c (base eccb1e69) unless a line names another commit. The card-side runs used a DGX Spark (aarch64 Linux, driver 595.84) in the dev container; the reader's tests do not run on a Mac. The static checks ran on an Apple Silicon Mac.

just contrib-check --tier t0 on the DGX Spark:

DONE tier=t0 total=82 red=0 wall=300s

just mac-static on the Mac:

mac-static: fmt-check rc 0 in 14 s — rustfmt diff blocks: 0
mac-static: lint rc 0 in 50 s — mac-check: lint ^warning: 41 = the ratchet 41 in tools/lint-ratchet.txt
mac-static: check-recipes rc 0 in 145 s

python3 tools/hf-arch-check.py --self-test: rc 0. With the main version of the script it fails, naming GemmaEmbedding2 and gemma-embedding2 as missing from the mirror.

Every arch test, which covers the nemotron_h and mimo2 readers that now call the lifted helpers (tools/gate.sh --release -p bloomery-model --lib -- arch::):

test result: ok. 264 passed; 0 failed; 0 ignored; 0 measured; 86 filtered out; finished in 0.08s

just gate-gemma-embedding2-meta on the real file:

gemma-embedding2 layers=24 full=[5, 11, 17, 23] hidden=512 out=768 ple=512 ff=2048 pins_differ=0
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s

The summary line also prints bytes=Ok(309855456), window=1024, reach=[Some(512), ...] with None at layers 5, 11, 17 and 23, tensors=413 and per_layer=Some(512) proj=[768]. The file was at another path on the box, so it went in through BLOOMERY_BOX_ENV='BLOOMERY_MODEL=<path>'.

FAIL-first for the checks this round added. Each mutant is a temporary patch, reverted after its run; the unchanged head passes:

Mutant Test that fails
the meta test reads BLOOMERY_MODEL with var, so a non-UTF-8 value falls back to the default file hw_non_utf8_model_override_is_refused
tensors_agree never compares dims a_tensor_missing_or_of_other_dims_is_named
tensors_agree lists only the first missing tensor a_tensor_missing_or_of_other_dims_is_named
tensors_agree names a tensor of other dims before a missing one a_tensor_missing_or_of_other_dims_is_named
nemotron_h's dims_agree skips a conv bias the file carries nemotron_h::spec::tests::the_conv_bias_may_be_absent
nemotron_h's dims_agree requires the conv bias nemotron_h::spec::tests::the_conv_bias_may_be_absent
a rope count larger than the head is accepted a_key_of_another_model_is_named
a rope base of 0 is accepted a_key_of_another_model_is_named
a sliding_window_pattern entry that is not a bool reads as true a_key_of_another_model_is_named
the reach rounds up (hp.window.div_ceil(2)) a_sliding_layer_takes_the_swa_head_and_half_the_window (window 11, reach 5)
the head or rope count error names the other layer kind's key (four mutants, one per key) a_sliding_layer_takes_the_swa_head_and_half_the_window

Each mutant run exits 101 with the test failing, and the restored head passes the same test.

The earlier checks, at 0753160a (base 3d750af3), each taken out one tree at a time (rc 101 for every one, no compile errors). The reader's code commit there is 1dd21c13 before this round's review fixes:

Check taken out Test that fails
missing tensor a_tensor_missing_or_of_other_dims_is_named
KV head count 0 a_key_of_another_model_is_named
heads not a multiple of KV heads a_key_of_another_model_is_named
odd rope dimension a_key_of_another_model_is_named
spec_of list length a_sliding_layer_takes_the_swa_head_and_half_the_window (index out of bounds)
per_layer_items length a_key_of_another_model_is_named, mimo2::hparams::tests::a_short_layer_array_is_refused, nemotron_h::spec::tests::a_short_per_layer_array_is_named
overflow check in mul nemotron_h::spec::tests::an_overflowing_key_projection_is_named, an_overflowing_value_projection_is_named

What I ran into

None of this blocks the PR.

  • The meta gate needs the file on the box. gate-gemma-embedding2-meta opens /models/embeddinggemma-2-GGUF/embeddinggemma-2-Q8_0.gguf (ggml-org/embeddinggemma-2-GGUF, 309,855,456 B). Where the file sits on the box is the maintainer's call. Another path goes in as BLOOMERY_BOX_ENV='BLOOMERY_MODEL=<path>' just gate-gemma-embedding2-meta; a plain BLOOMERY_MODEL=<path> does not work, because box.sh reads that name on the calling side as a model profile. The gate is in the tools/gate-paths.tsv rows of eleven shared paths (crates/{runtime,tokenizer,placement}/src/**, crates/models/src/{lib,shape,headpick}.rs, three crates/gguf/src files, crates/{qdot,threads}/src/lib.rs), so until the file is on the box, just affected gives a change to any of them this gate, and it fails at the open.
  • A model with no program is covered by any program's rows. coverage::check_with takes the AVAILABLE rows of every program when program_of returns None. For a decoder that is a fair first answer. For an encoder it would hide the attention kind: a Need::Gqa would read as covered by the causal flash rows. This PR gives the encoder its own Need variants, so the list is right today. If more non-decoder models come, the rule could instead take no rows for an arch with no program.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, "What I ran"에 적은 검사를 돌렸습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

…on ModelSpec

EmbeddingGemma 2 reads into a spec: every layer is GQA with a q/k norm
and NeoX rope of its kind's head (512 on the full layers, 256 on the
sliding ones), and a GELU GLU feed-forward. ModelSpec::encoder holds what
the trunk does not: each layer's reach (half the file's sliding_window on
each side, llama.cpp's symmetric mask), the per-layer input width and the
output projection widths. Every decoder reader sets it to None.

An encoder's attention is Need::Bidirectional and its feed-forward
Need::GeGlu, so no decoder row covers them while the arch has no
program. An encoder asks for no tool-call parser. The pre-tokenizer is
gemma4 when the file names none, as llama.cpp sets it. template_of is
lifted out of chat_of. Act::what names an activation for a refusal.

The reader refuses by name another pooling, causal attention, shared KV
layers, a key head count of 0 or one that does not divide the heads, an
odd rope count, a missing key, and a tensor missing or of other dims:
every missing one first, else every one of other dims. spec_of refuses
hparams whose per-layer lists are not one per layer. The
gate-gemma-embedding2-meta recipe runs the synthetic-header tests and
the hw_ test on the Q8_0 file; hf-arch-check's mirror lists the arch.

Common rows: the overflow-checked product (nemotron_h's mul) and the
per-layer array's length check (per_layer_items, which per_layer_count,
mimo2's pattern and its MTP sidecar's layer_item each carried) have one
owner in arch, which nemotron_h, mimo2 and the new reader call.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 15, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: The header reader validates its inputs, reports encoder requirements, and refuses execution without a program.

Checked

Duplicates: Gemma's classifier and Nemotron's classifier delegate to the common classify_with walk. Their tensor tables hold architecture facts.

Complexity: Hparams::read delegates head, encoder and tensor validation. Need::fmt and arch::spec add match arms; needs and coverage::check_with add encoder selection. The reported complexity alone establishes no defect.

Silent failure: malformed metadata, invalid heads and rope parameters, missing tensors and wrong dimensions return named errors. Encoder reach is built from one pattern entry per layer. CPU and GPU harness entry points reject the new architecture.

Tests: static inspection confirms assertions reject swapped full/sliding heads, rounded-up reach, dropped array-length checks, causal encoder requirements and skipped tensor-dimension comparisons. The metadata gate asserts header pins and rejects a non-UTF-8 override. Gates were not rerun here.

Gates: no existing pins or thresholds are relaxed. The new recipe selects synthetic checks and ignored metadata tests.

Escape catalog: no C1–C4 pattern matched. No ledger lessons are in force.

Notes

The PR reports gate commands, output, model identity, commit hashes and a DGX Spark driver version, but omits the required nvidia-smi output line. Attach that line to complete GPU evidence.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/shared/routed_legs.rs, crates/gpu-gates/src/engine.rs, crates/gpu-gates/src/oracle/mod.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card placement Placement planning: crates/placement tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant