Repository navigation
model, models: gemma-embedding2's header reader, with an EncoderSpec on ModelSpec - #238
Conversation
…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.
There was a problem hiding this comment.
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)
|
The review is done and the contribution check passed, so I'm merging this. |
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-embedding2GGUF files and lists what no program runs yet; such a file does not serve yet.A
gemma-embedding2file now reads into aModelSpecand a role for every tensor, andcoverage::checklists 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 sideon a sliding layer,head 512, group 4on a full one), its q/k norm and rope (per-head QK norm plus rope: head 256, NeoX, 256 of 256 dims, or 512) anddense GELU GLU layer: ff 2048; thena layer program for gemma-embedding2andpre-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 aNeedfor each beforeprogram_ofreturns 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).Noneon every decoder reader. For this model it holds three facts: each layer's reach (keys on each side of a row;Noneon the full layers), the per-layer input width (embedding_length_per_layer_input, 512) and the output projection widths ([768]). The layers stayGqawithwindow: None, andGqa::window's doc says so. EmbeddingGemma (v1,gemma-embedding) fits the same struct withper_layer: Noneandproj: [3072, 768]; its reader is E8 of model: EmbeddingGemma and EmbeddingGemma 2 on a side seat #190, the second user of those two fields.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 takeRole::EngramDense. The two model-level tensors (per_layer_model_proj.weight,per_layer_proj_norm.weight) take it too for now; common placement refuses anEngramDensetensor with no layer, so the body PR places them.attention.sliding_windowis 1024, and llama.cpp masks a key when|i - j| > sliding_window / 2(LLAMA_SWA_TYPE_SYMMETRIC), soreachis 512 on each side. The reader stores the reach, not the file's number, so no consumer halves it again.Act::GeGlu. The FFN isgelu(gate) * upwith tanh GELU. It is a newActarm, likeAct::ReluSqrfor Nemotron.Act::what()names an activation for a refusal, and the decoder bodies that matchedReluSqrby 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()emitsNeed::Bidirectional { head, group, reach }for everyGqalayer of an encoder. This matters becausecoveragetreats a need as covered when any program'sAVAILABLErow covers it if the arch has no program; aNeed::Gqahere would read as covered by the decoders' causal rows.Need::GeGluis new for the same reason.coveragewould ask for a tool-call parser. The guard isspec.encoder.is_none().tokenizer.ggml.model = gemma4and notokenizer.ggml.pre. llama.cpp sets the pre-tokenizer togemma4for that tokenizer model (src/llama-vocab.cpp), so the reader does the same and records it inRead::defaults. Another name in either key is refused by name.template_ofis lifted out ofchat_ofso both readers take the template one way.The reader refuses by name: a missing key (
attention.causalandattention.shared_kv_layersmay be absent);pooling_typeother than mean;attention.causal = true; a nonzeroattention.shared_kv_layers; a value head other than the key head; a rope count that is odd or larger than the head; ahead_count_kvof 0 or one that does not divide the heads; asliding_window_patternof 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.cppsrc/models/gemma-embedding2.cppandsrc/llama-arch.cpp. Every stem is required there (noTENSOR_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):Hidden 512, 4 query heads, FFN 2048, per-layer input 512, output 768, vocabulary 262,144,
context_length262,144, 413 tensors.per_layer_model_proj.weightis 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
EncoderSpecbesideModelSpecor with an encoder variant ofModelSpec, and says E1 follows the answer. That question has no answer yet. This PR proposes a third shape, anOption<EncoderSpec>field insideModelSpec, soneeds()andcoverage::checkread one value. What each shape costs:encoder: Noneline at each of the ten existingModelSpecsites;needs()picks the attention need byspec.encoder, and the tool-call item is skipped for an encoder.ModelSpec.Readcarries a second value, andneeds()andcoverage::checktake it as a second argument at every call site.ModelSpec. Every reader'sModelSpecconstruction and every consumer that reads the decoder fields changes.Gqagains a direction and a two-sided reach). No new spec type, but everyGqaliteral 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
This PR attaches none of them: it is the reader.
Steps of
new-model.mdcrates/model/src/arch/gemma_embedding2/{hparams,names,roles,spec}.rs, theArcharms,program_of(None)spec.rs(a 6-layer model with both layer kinds, every refusal above) and thehw_meta test on the real file, both on a DGX Spark; see "What I ran"gate-gemma-embedding2-meta,tools/gate-paths.tsvrows,tools/hf-arch-check.pymirrorjust mac-static(check-recipes),python3 tools/hf-arch-check.py --self-testSteps 2 to 9 are later PRs.
place.rscomes with the body, where the bytes are known.Code shape
template_ofis lifted out ofchat_of. The overflow-checked product (mul, nemotron_h's) the per-layer array's length check (per_layer_items, whichper_layer_count, mimo2'spatternand the MTP sidecar'slayer_itemeach carried) and the tensor dims check (tensors_agree: every missing name first, then every tensor of other dims, which nemotron_h'sdims_agreeran on its own) now have one owner incrates/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).Needvariants and oneActarm, each a fact of the attention or FFN kind. No body gained a model branch: the bodies that matchedAct::ReluSqrnow refuse every non-SwiGLU arm throughAct::what().spec_ofrefuses anHparamswhose per-layer lists are not one per layer instead of indexing past them.tools/check-comments.shpasses.cargo fmtandcargo clippyare 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.rsmuland the loop in itsdims_agree(nowtensors_agree,crates/model/src/arch/mod.rs:323), the length checks incrates/model/src/arch/mod.rsper_layer_count,crates/model/src/arch/mimo2/hparams.rspatternandcrates/model/src/arch/mimo2/mtp.rslayer_item, andchat_of's template read (nowtemplate_of). Found and left as they are:crates/model/src/arch/glm5next/hparams.rs:596kindsruns the same length check, andglm5next/hparams.rs:650anddeepseek41/hparams.rs:1445per_layer_f32run it after a scalar fallback; each can callper_layer_itemsin a follow-up.What I ran
All runs are at the head
6b886f6c(baseeccb1e69) 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 t0on the DGX Spark:just mac-staticon the Mac:python3 tools/hf-arch-check.py --self-test: rc 0. With the main version of the script it fails, namingGemmaEmbedding2andgemma-embedding2as 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::):just gate-gemma-embedding2-metaon the real file:The summary line also prints
bytes=Ok(309855456),window=1024,reach=[Some(512), ...]withNoneat layers 5, 11, 17 and 23,tensors=413andper_layer=Some(512) proj=[768]. The file was at another path on the box, so it went in throughBLOOMERY_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:
BLOOMERY_MODELwithvar, so a non-UTF-8 value falls back to the default filehw_non_utf8_model_override_is_refusedtensors_agreenever compares dimsa_tensor_missing_or_of_other_dims_is_namedtensors_agreelists only the first missing tensora_tensor_missing_or_of_other_dims_is_namedtensors_agreenames a tensor of other dims before a missing onea_tensor_missing_or_of_other_dims_is_nameddims_agreeskips a conv bias the file carriesnemotron_h::spec::tests::the_conv_bias_may_be_absentdims_agreerequires the conv biasnemotron_h::spec::tests::the_conv_bias_may_be_absenta_key_of_another_model_is_nameda_key_of_another_model_is_namedsliding_window_patternentry that is not a bool reads as truea_key_of_another_model_is_namedhp.window.div_ceil(2))a_sliding_layer_takes_the_swa_head_and_half_the_window(window 11, reach 5)a_sliding_layer_takes_the_swa_head_and_half_the_windowEach mutant run exits 101 with the test failing, and the restored head passes the same test.
The earlier checks, at
0753160a(base3d750af3), each taken out one tree at a time (rc 101 for every one, no compile errors). The reader's code commit there is1dd21c13before this round's review fixes:a_tensor_missing_or_of_other_dims_is_nameda_key_of_another_model_is_nameda_key_of_another_model_is_nameda_key_of_another_model_is_namedspec_oflist lengtha_sliding_layer_takes_the_swa_head_and_half_the_window(index out of bounds)per_layer_itemslengtha_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_namedmulnemotron_h::spec::tests::an_overflowing_key_projection_is_named,an_overflowing_value_projection_is_namedWhat I ran into
None of this blocks the PR.
gate-gemma-embedding2-metaopens/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 asBLOOMERY_BOX_ENV='BLOOMERY_MODEL=<path>' just gate-gemma-embedding2-meta; a plainBLOOMERY_MODEL=<path>does not work, because box.sh reads that name on the calling side as a model profile. The gate is in thetools/gate-paths.tsvrows of eleven shared paths (crates/{runtime,tokenizer,placement}/src/**,crates/models/src/{lib,shape,headpick}.rs, threecrates/gguf/srcfiles,crates/{qdot,threads}/src/lib.rs), so until the file is on the box,just affectedgives a change to any of them this gate, and it fails at the open.coverage::check_withtakes theAVAILABLErows of every program whenprogram_ofreturnsNone. For a decoder that is a fair first answer. For an encoder it would hide the attention kind: aNeed::Gqawould read as covered by the causal flash rows. This PR gives the encoder its ownNeedvariants, 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 초안 리뷰는 제가 직접 했습니다.