Repository navigation
feat(llama): accept checkpoints that name several stop tokens - #1288
Conversation
A checkpoint may name one stop token or a list of them. The llama family assumed a scalar at the bundle boundary: model.py wrote whatever the config held into runtime.json, and plugin.cpp read it with require_value<int32_t>, so a list was rejected with "llama runtime.json has invalid 'eos_token_id'" and the model could not run at all. Everything downstream was already built for this. LlamaTextGenConfig carries id_eos_ids, pipeline.cpp normalises the scalar and the list against each other, and the sampler already stops on any id in the set - with two C++ tests covering it. Only the two ends were missing. model.py now normalises the stop tokens from config.json or generation_config.json into a list, writes the first id as the scalar eos_token_id, and writes the full list as eos_token_ids only when there is more than one. Single-stop bundles therefore keep exactly the field set they had before, and a bundle stays readable by a runtime that predates the list. plugin.cpp reads the optional key, counts it in the strict field-set check, and validates every id against the vocabulary. Qualifies openbmb/MiniCPM5-2B, which names two stop tokens and emits the second one. Against the Hugging Face reference it matches token for token, normalised edit distance 0.0000. That case is also the proof the path is load-bearing: the model stops after two tokens against a ten-token cap, so a runtime honouring only the first id would have run to the cap and diverged. TinyLlama was rebuilt and run before and after the change and produced byte-identical output, confirming single-stop checkpoints are unaffected. Signed-off-by: Zhenshan Xie <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (5)
Included review availability: Your plan provides up to 12 included reviews per hour; 10 remain after this review. 📝 SummarySummaryThe Llama family adds support for checkpoints with multiple stop tokens.
Architecture impact
ValidationThe PR objectives report Hugging Face token agreement, second-token handling, byte-identical TinyLlama output, nine EOS tests, passing Llama CTest suites, and clean formatting and lint checks. Independent execution is not established. Review outcomeHUMAN REVIEW REQUIRED — the available evidence cannot resolve the implementation and blast-radius questions. Review finding counts are unavailable. WalkthroughThe Llama model now supports scalar and multiple EOS token IDs. The runtime validates and forwards multiple IDs. Tests cover normalization and configuration behavior. MiniCPM5-2B receives a test manifest and performance profile. ChangesLlama EOS token support
Priority: ⬇️ Low Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Feature Sequence Diagram(s)sequenceDiagram
participant ModelConfig
participant LlamaModel
participant RuntimePlugin
participant LlamaTextGenConfig
ModelConfig->>LlamaModel: provide EOS token settings
LlamaModel->>LlamaModel: normalize and emit EOS fields
LlamaModel->>RuntimePlugin: provide runtime configuration
RuntimePlugin->>RuntimePlugin: validate EOS token IDs
RuntimePlugin->>LlamaTextGenConfig: pass EOS token IDs
Merge Risk: ⚪ Minimal · up to Multiple EOS-token support and MiniCPM5-2B integration have no identified merge-blocking risk. 🚥 Pre-merge checks | ✅ 6 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (6 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 3 files. (2 skipped: 2 unsupported.) Full details: Shared Semantic NeutralityExplanation The pull request adds model-specific configuration to shared benchmark data. In Resolution Remove the Full details: Benchmark Validation IntegrityExplanation The new Resolution Align the accounting contract before adding this profile. In Comment |
… tokens (1304) ## Background `families/gemma` claimed `gemma` and `gemma2`. Google has since published Gemma 3, whose text-only checkpoints — `gemma-3-270m` (268M) and `gemma-3-1b-it` (1.0B, 2.9M downloads) — are among the smallest useful models on the Hub. #1300 refused them so they could not build a silently wrong graph; this adds the support. ## Exit Criteria - `gemma-3-1b-it` matches the Hugging Face reference. - Gemma and Gemma 2 build the same graph they built before. - Anything the family still cannot do is refused rather than approximated. ## Implementation Four Gemma 3 gaps, each found by measuring rather than by reading the architecture: | gap | effect when wrong | | --- | --- | | per-head q/k norms never given Gemma's `(1 + gamma)` | applied as `gamma` alone they are near zero; this is why an unguarded build emitted ` ```\n```\n``` ` | | local layers rotate on `rope_local_base_freq` (10000), global on `rope_theta` (1000000) | every layer used the global base | | query scale comes from `query_pre_attn_scalar` | matches `head_dim` on some widths and not others, so it must be read | | the rope change belongs in **all three** decoder builders | patching only the prefix builder left prefill right and decode wrong | That last one is worth recording: with only the prefill builder fixed, teacher-forced agreement was **6/6** while free-running was **1/8**. The gap between those two numbers is what identified the decode engine as the unpatched path. **A fifth fix is not Gemma 3 specific.** Gemma names two stop tokens — `[1, 107]` for Gemma 2, `[1, 106]` for Gemma 3 — and the second is `<end_of_turn>`, the one a chat turn actually ends on. `require_eos_token` kept `value.front()`, so the runtime stopped only on token 1. The pipeline and sampler already carried a set of stop tokens (`id_eos_ids`, `gemma_is_eos_token`); only the bundle boundary dropped them, exactly as in #1288 for llama. **Sliding-window attention is still not implemented.** The builder now refuses `max_sequence_length` above the checkpoint's `sliding_window` instead of silently building full attention for every layer. ### Change categories - [x] Model or runtime behavior ## Validation ### Commands and Results `google/gemma-3-1b-it`, the committed manifest case, engine through the native CLI against the Hugging Face reference: | | token ids | text | | --- | --- | --- | | engine | `[50429, 106]` | `Paris` | | reference | `[50429, 106]` | `Paris` | Normalised edit distance **0.0000** against a threshold of 0.15. **Gemma 2 regression — the stop-token fix repairs an already shipped model.** Same `gemma-2-2b` manifest case, built on `main` and on this branch: | | engine | reference | | --- | --- | --- | | `main` | `[235310, 235248, 108, 107, 1]` — runs **past** `<end_of_turn>` | `[235310, 235248, 108, 107]` | | this branch | `[235310, 235248, 108, 107]` — exact | identical | The decoded text is `'4'` either way, because 107 and 1 are both special and are stripped, so the existing manifest passed while the engine was over-generating. That is why this went unnoticed. Other suites: - `families/gemma/tests/` — 25 passed, 15 of them new - `ctest -R gemma` — 2/2 (`test_gemma_pipeline`, `test_gemma_sampler`) - `tools/tests/test_architecture.py` and `apps/benchmark/trtmc_benchmark/tests` — 154 passed - `ruff check` clean; `clang-format` 22.1.8 clean ### Failures only the official checkpoint showed Two internal-CI rounds failed on the 4B, both because **a published Gemma 3 config omits what transformers defaults, and the official checkpoints do exactly that**: | round | error | omitted field | | --- | --- | --- | | 1 | `AssertionError: Embedding shape (262208, 2560) != (0, 2560)` | `vocab_size` | | 2 | `ValueError: Gemma requires a supported checkpoint gated activation; got '<missing>'` | `hidden_activation` | The `unsloth` mirror I verified against states both, so local runs passed and CI did not — the risk this PR's environment note called out, realised twice. `gemma-3-1b` passed both rounds; only the 4B was affected. Rather than fix these one round at a time, I enumerated every field whose mirror value equals the `Gemma3TextConfig` default — precisely the ones an upstream config may leave out — and covered them: `vocab_size` is read off the embedding's safetensors shape, and Gemma 3 defaults are applied for an absent activation and norm epsilon. The epsilon matters most: without it this family falls back to **1e-5** where Gemma 3 uses **1e-6**, wrongly and silently. Verified by stripping all seven omissible fields from a local config — reproducing what CI builds against — and rebuilding: the engine still matches the reference token for token. ### Superseded note The first internal-CI run failed on the 4B with: ``` AssertionError: Embedding shape (262208, 2560) != (0, 2560) families/gemma/checkpoint_mapper.py:101 ``` `google/gemma-3-4b-it` does not state `vocab_size` in its `text_config`, so the config parser defaults it to 0 and the mapper then rejects the embedding it has just loaded. The `unsloth` mirror of the same weights *does* state it, so local verification passed and CI did not — the exact risk called out in this PR's environment note, now realised. The vocabulary size is now read off the embedding's safetensors shape whenever the config omits it, which costs no extra read. `gemma-3-1b` passed that CI run; only the 4B was affected. ### Hardware, Environment, and Revisions - NVIDIA A100 80GB PCIe, x86 dev container - Local verification used `unsloth/gemma-3-1b-it` and `unsloth/gemma-2-2b-it`. The official Google repos are gated and this container has no HF token; the mirrors carry identical weights (`unsloth/gemma-3-1b-it` reports 999,885,952 parameters, matching `google/gemma-3-1b-it` exactly). The manifest names the official `google/gemma-3-1b-it`, which CI can fetch — `gemma-2-2b-it` is already qualified the same way. - Rebased on `73028669` ### Not Run / Remaining Gaps - **Sliding-window attention is not implemented, and cannot currently be tested.** TensorRT fails to build this family at `max_sequence_length` 512 and above with an internal Myelin error (`wrap_attention_op_in_kgen.cpp:1909: CHECK(expected_live_inputs == knode->inputs().size())`, expected 3 live inputs, got 4). That limit is **pre-existing** — unmodified `main` fails identically on Gemma 2 — and it sits below Gemma 3's 512-token window, so every buildable length is inside the window where sliding and full attention are the same thing. The new guard exists so that a future TensorRT fix cannot silently widen that gap. ### Gemma 3 4B and the precision matrix 4B is `Gemma3ForConditionalGeneration`: the decoder sits under `language_model.model` beside a SigLIP vision tower, its decoder fields are nested in `text_config`, and its **global** layers carry linear rope scaling (factor 8) while the local layers stay unscaled. That per-attention-type split was read off the reference, which resolves `rope_scaling` to `{sliding_attention: default/10000, full_attention: linear/factor 8/1000000}`. The decoder prefix is detected, the nested fields are read, rope tables take a position scale, and the vision tower is never touched. Both widths are qualified at **fp32**. The reason is measured: Gemma 3 activations exceed the fp16 range. Running the reference in fp32 and recording the largest absolute value leaving each decoder layer, for the manifest prompt: | width | peak activation | fp16 max is 65,504 | layers over | | --- | --- | --- | --- | | gemma-3-270m | 102,956 | exceeds | 11 of 18 | | gemma-3-1b | 61,040 | under, by 7% | 0 | | gemma-3-4b | 298,680 | exceeds | 29 of 34 | That accounts exactly for the observed fp16 behaviour: 270m and 4B overflow and emit token 0 repeatedly, and the 1B survives only because its peak happens to land just inside the range. A 7% margin on one prompt is luck, not headroom, so fp16 is not used for any width here. **bf16 is also correct** for every width — 270m, 1B and 4B each match the reference exactly (NED 0.0000) on the manifest case — and bf16 is the checkpoints' native dtype. fp32 is chosen here only because it was verified first and is the most conservative; switching these manifests to bf16 would halve the engine size and is a reasonable follow-up. - **`gemma-3-270m` is not qualified here**, though it is correct at fp32 and bf16; only the 1B and 4B have manifests. - The earlier note that 270m might fail because its attention is wider than its residual stream was **wrong** — the 4B fails at fp16 too and is 2048 against 2560. It is precision, not shape. - Trying that second width is what caught the schedule bug described below, so it was worthwhile regardless. - Gemma 3 at 4B and above adds a vision tower and is out of scope; Gemma 3n and Gemma 4 remain refused. - `ruff format --check` reports pre-existing findings in four of the files this change touches. They are deliberately not reformatted: doing so turned a 175-line diff into a 1200-line one and buried the change. ## Contributor Self-Review - [x] I have completed a self-review of this change. ## Notes For Future Readers The useful technique here was teacher forcing. Free-running greedy agreement is a bad metric for a partly-correct decoder: one wrong token changes the context and every later token is meaningless, so the score moves almost at random. Feeding the reference's own tokens back in measures one step at a time and turned an ambiguous "2/8 then 1/8" into a clean split — prefill correct, decode wrong — which pointed straight at the builder I had not patched. The schedule default is the other thing worth recording. `google/gemma-3-1b-it` states `sliding_window_pattern: 6`; `google/gemma-3-270m-it` omits it and relies on the transformers default of the same value, and its resolved `layer_types` are 3 global layers in 18 — that default. My first implementation required the key to be present and fell back to "every layer global" when it was not, which builds a wrong graph without failing. Only trying a second width surfaced it. The helper now prefers an explicit `layer_types` list, then the stated pattern, then the default, and refuses a stated-but-unusable pattern instead of defaulting over it. The stop-token bug is the second instance of the same shape, after #1288 in llama: a runtime that already supported a capability, with the bundle boundary quietly discarding it. Both were invisible because the dropped tokens are special and decode to nothing. If another family shows an off-by-one in generated length, this is worth checking first. Third-party provenance: Gemma is published by Google; the checkpoints are the `google/gemma-3-1b-it` and `google/gemma-2-2b-it` Hugging Face repositories. ### Risk level - [x] Low Gemma and Gemma 2 keep the graph they had: the schedule helper returns "all global" when a checkpoint declares no sliding pattern, and the stop-token list is written only when a checkpoint names more than one. The one behaviour change to an existing model is Gemma 2 now stopping at `<end_of_turn>`, which is what the reference does.
Background
A checkpoint may name one stop token or a list of them. Llama 3 itself ships a list, and so
does
openbmb/MiniCPM5-2B, which reports"eos_token_id": [1, 130073].The
llamafamily assumed a scalar at the bundle boundary.model.pywrote whatever theconfig held into
runtime.json, andplugin.cppread it withrequire_value<std::int32_t>, so a JSON array was rejected outright:The model built fine and then could not run at all.
Exit Criteria
Implementation
Everything downstream was already built for this and is already tested:
LlamaTextGenConfigcarriesid_eos_ids,pipeline.cpp:46reconciles the scalar and thelist, and
sampler.cpp:26-30stops on any id in the set — covered bytest_generate_stops_at_any_default_eosandtest_explicit_eos_override_replaces_default_set.Only the two ends were missing.
families/llama/model.pynormalises the stop tokens fromconfig.jsonorgeneration_config.jsoninto a list, writes the first id as the scalareos_token_id, andwrites the full list as
eos_token_idsonly when there is more than one. Single-stopbundles therefore keep exactly the field set they had before, and any bundle stays readable
by a runtime that predates the list. Booleans are rejected explicitly, because
boolis anintsubclass and would otherwise pass as a token id.families/llama/runtime/plugin.cppreads the optional key, counts it in the strictfield-set check, and validates every id against the vocabulary. The validation sits after
the dimension checks so
vocab_sizeis known good before it is used as a bound.This mirrors
families/qwen3_8/model.py:40-53, which already normalises toeos_token_ids.Change categories
Validation
Commands and Results
New checkpoint qualified —
openbmb/MiniCPM5-2B, engine through the native CLI againstthe Hugging Face reference:
[27452, 130073]Paris[27452, 130073]ParisNormalised edit distance 0.0000 against a threshold of 0.15; token-for-token identical.
Proof the path is load-bearing. The model stops after two tokens against a ten-token cap,
and the token it stops on is
130073— the second id, not the first. A runtime honouringonly the first id would have run to the cap and produced different text. Before the change
the bundle did not load at all.
No regression for single-stop checkpoints.
TinyLlama-1.1B-Chat-v1.0was rebuilt and runon
mainand on this branch:Byte-identical. Its
runtime.jsonfield set is unchanged, since the plural key is onlywritten when it adds something.
Other suites:
families/llama/tests/test_eos_tokens.py— 9 new tests, passedctest -R llama— 4/4 passed (test_llama_pipeline,test_llama_plugin_helpers,test_llama_chat_template,test_llama_native_kv_cache)tools/tests/test_architecture.pyandapps/benchmark/trtmc_benchmark/tests— 163 passedruff checkclean;ruff format --checkclean on both files this change touches;clang-format22.1.8 cleanHardware, Environment, and Revisions
openbmb/MiniCPM5-2Bat12a3808a956f869c767195e9266b59c4d21d92e2;TinyLlama/TinyLlama-1.1B-Chat-v1.0for the regression controlc96119fdNot Run / Remaining Gaps
container carries a CPU-only torch, so locally the same bundle, the same native CLI call and
the same normalised-edit-distance check were run with the reference on the CPU; the GPU form
runs in CI.
families/llama/config.pystill typeseos_token_idasintwhile a list can flow throughit. The normalisation is done in
model.pyat the point of use rather than by retyping thedataclass, which would touch every family sharing that file — it is a byte-identical copy
across
qwen,phi,deepseek_v2and others.ruff format --checkreports pre-existing findings infamilies/llama/config.py, which thischange does not touch and deliberately does not reformat.
Contributor Self-Review
Notes For Future Readers
The interesting part is how little code was needed. The sampler, the pipeline config and two
C++ tests for multi-stop generation were all already present; the capability existed and was
simply not reachable, because neither end of the bundle could carry it. Worth checking for
that shape before building something new.
The decision to write
eos_token_idsonly when there is more than one is deliberate. Writingit unconditionally would have changed every existing llama bundle's
runtime.jsonand forcedthe strict field-count check in
plugin.cppto move for all of them. Gating it keeps theblast radius to exactly the checkpoints that need it.
Third-party provenance: MiniCPM5 is published by OpenBMB; the checkpoint is the
openbmb/MiniCPM5-2BHugging Face repository, which reportsLlamaForCausalLMand istherefore claimed by this family's existing identity check with no change to
support.py.Risk level
One optional field, written only when a checkpoint needs it, with the existing behaviour
unchanged for every checkpoint that does not. Verified by a before/after control on a
single-stop model.