Repository navigation
fix(tokenizer): enable add_bos_token for Gemma 4 base models - #10312
Conversation
Gemma 4 base (non-it) unsloth Hub mirrors ship without add_bos_token: true even though google/gemma-4-* includes it. Without BOS, base-model inference degenerates into repeated text. Set add_bos_token at load time for the four base families (E2B, E4B, 31B, 26B-A4B) and their -unsloth-bnb-4bit variants. -it models are untouched because their chat templates already emit bos_token. Fixes unslothai#7903.
|
Confirmed nothing in unsloth/tokenizer_utils.py sets add_bos_token for the Gemma 4 base mirrors today, so the degenerate generation in the repro stands. The name regex in _GEMMA4_BASE_MODEL_RE will miss local paths and other quant suffixes such as gemma-4-31B-bnb-4bit, so could you key off the loaded config or tokenizer instead, and mark it ready for review when you are happy with it? |
Key add_bos_token healing off the loaded tokenizer and model config instead of a Hub-name regex, so local paths and extra quant suffixes still get BOS. Apply the same heal on the FastModel processor path, which never calls load_correct_tokenizer.
Honor the loaded model config on FastLanguageModel loads, heal FastModel processors after the tokenizer is finalized instead of swallowing errors, and cover the processor path in unit tests.
|
Thanks Daniel, updated the pr Detection no longer uses a Hub-name regex. We key off the loaded tokenizer (
The same heal now runs on the FastModel processor path (the #7903 repro) after the tokenizer is finalized, and |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 82b148c9a0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Forward fix_tokenizer through FastModel/FastBaseModel so Gemma 4 BOS healing respects fix_tokenizer=False on the processor path. When a load falls back to bare PreTrainedTokenizerFast, rebuild the Rust post-processor instead of only setting a Python add_bos_token attribute.
|
The missing BOS fix introduces duplicate BOS after applying the Gemma 4 chat template and saving/reloading the tokenizer. A/B evidence shows one BOS on main and two on the PR across Windows and macOS. Suggested improvement before merge: prevent duplicate BOS for rendered chat prompts while preserving automatic BOS for raw completions. |
Keep add_bos_token for raw completions on Gemma 4 base models, but strip template-emitted bos_token when the tokenizer already prepends BOS. Prevents double BOS after get_chat_template and save/reload while preserving the missing-BOS fix from unslothai#7903.
|
@Imagineer99 Thanks for catching this — agreed on the duplicate BOS after chat template + save/reload. Pushed a follow-up on
Raw |
Reuse _dedupe_bos_chat_template in the GGUF BOS helper so a mapping of templates is stripped per entry instead of passing a dict to re.sub.
|
Stripping template BOS introduces missing BOS with |
|
Fix added in |
Verified the root cause on the Hub: the gemma-4 base mirrors kept google's release-day tokenizer.json, which google replaced about three hours later on 2026-04-02. Ours has post_processor.single = [A], google's has [<bos>, A]. Our file is byte identical to google's pre-patch blob (sha256 cc8d3a0c) on E2B, E4B, 31B and 26B-A4B, so this is a stale mirror rather than anything we changed. gemma-4-12b was mirrored in June and is already correct. google leaves every -it repo BOS-less as well, so skipping -it keeps us matching upstream. Detection is now two signals instead of five: - processor_class == Gemma4Processor, read from init_kwargs where it actually lives. - model_type / architectures, via one anchored regex. Removed, with the evidence for each: - The class-name branch never fired. Gemma 4 loads as GemmaTokenizer, not Gemma4Tokenizer. - The think_token + boa_token pair is redundant. All 16 gemma-4 repos ship processor_class, and a checkpoint stripped of it is already covered by the model config. - _update_generic_fast_post_processor is unreachable. On transformers 5.5.0 and 5.16.1 the generic backend is TokenizersBackend, whose add_bos_token is a working property, so _has_add_bos_token_setter is always true. Gemma 4 requires transformers >= 5.5.0, so no supported version reaches the hand-built post_processor. - _normalize_type_name and _tokenizer_stored had one caller each. The anchored regex also stops two false positives the old prefix and substring tests allowed: a future gemma_45 or gemma-4.5, and DiffusionGemma4ForConditionalGeneration. Behaviour changes: - The repair is keyed on the emitted ids, not add_bos_token. That attribute reads False on google's own patched mirrors while they still prepend, so it was never a usable signal. An already-correct tokenizer now keeps its post_processor instead of having one rebuilt. - A failed repair is reported. The bare except hid the ValueError raised when bos_token is None, and pre-5.x fast tokenizers accept the attribute without changing what they emit, so a caller could be told BOS was restored when it was not. Both warn now. - bos_token inside a Jinja comment no longer suppresses the repair, since it renders to nothing. - _tokenizer_auto_adds_bos unwraps the nested list a processor returns, which it previously read as a non-matching first element. - Tokenizer objects are compared by identity, so a wrapper defining __eq__ cannot trigger a field comparison. Testing: 44 cases, 9 of them against a real in-memory tokenizers backend, so they fail if the repair ever degrades to an inert attribute set. They skip on transformers 4.x via a capability probe. The network test is marked slow as well as e2e so the default addopts deselect it. Verified on unsloth/gemma-4-E2B, 4-bit, seed 3407, four prompts, greedy and sampled: input ids and generated ids are identical to hardcoding <bos>, which is the control from unslothai#7903. Without the repair the same run degenerates, repeated-4gram 0.90 and longest run 58. 133 token-id checks over 28 real tokenizers pass on transformers 5.5.0 and 5.16.1, with every -it repo, every google repo and Llama, Qwen, Mistral, Phi-4, Gemma 2, Gemma 3 and Gemma 3n encoding byte identically. fix_tokenizer = False opts out on both loader paths. Repo suite: 2210 passed, with the same nine pre-existing unrelated failures as the merge base.
|
Pushed The mirrors are stale, we did not break them
Our file is byte identical to google's pre-patch blob (sha256 The two files differ at exactly three paths, all inside Two things follow. First, the four-family scope here is right, and the "only E2B is a real delta" reading in #7903 was based on the Separately from this PR, the seven stale base repos want a What I changedDetection is now two signals instead of five: Removed, with the evidence:
Behaviour changes:
VerificationOn
Input ids and generated ids match the control exactly in both decoding modes. 133 token-id checks over 28 real tokenizers pass on transformers 5.5.0 and 5.16.1. Every Tests are 44 cases, 9 against a real in-memory tokenizers backend so they fail if the repair ever degrades to an inert attribute set. They skip on transformers 4.x via a capability probe. Repo suite: 2210 passed, with the same nine pre-existing unrelated failures as the merge base. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2d798dedd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| text = _JINJA_COMMENT_RE.sub("", chunk if isinstance(chunk, str) else str(chunk)) | ||
| if "bos_token" in text or "<bos>" in text: | ||
| return True |
There was a problem hiding this comment.
Distinguish BOS references from actual emissions
When a Gemma 4 base tokenizer has a template that merely references bos_token in control flow, such as {% if bos_token is defined %}, this substring check reports that the template emits BOS. _is_gemma4_instruct_tokenizer then treats the tokenizer as instruct and skips the BOS repair, leaving affected base-model prompts without the token this change is intended to restore. Detect an output expression such as {{ bos_token }} rather than any reference to the variable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar as written. I scanned the chat templates of 30 real models, every gemma-4 base and -it repo plus Llama 2 and 3.x, Qwen 2.5 and 3, Mistral, Phi, Gemma 2, 3 and 3n, DeepSeek, GLM-4, SmolLM2, gpt-oss and TinyLlama: zero reference bos_token only in control flow. Jinja comments were a real case and those are stripped before the check. Happy to tighten it to an output expression if a shipping template ever does this.
| def _strip_bos_from_chat_template_text(chat_template): | ||
| if not isinstance(chat_template, str) or not chat_template: | ||
| return chat_template | ||
| stripped = re.sub(r"\{[\s\-]*\{[\s\-]*bos\_token[\s\-]*\}[\s\-]*\}", "", chat_template, count = 1) | ||
| return re.sub(r"\{[\s\-]*\{[\s\-]*bos\_token[\s\-]*\+[\s\-]*", "", stripped, count = 1) |
There was a problem hiding this comment.
Strip BOS from every conditional template branch
When alternative template branches each begin with {{ bos_token }}, count = 1 removes only the first textual occurrence. If generation selects another branch, the template still emits BOS while the tokenizer also prepends it, so the GGUF export retains the duplicate token; the previous implementation removed all matching occurrences. Remove the leading BOS expression from each possible branch rather than only the first match in the template string.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable on anything shipping. Across the same 30 templates, the maximum number of BOS emissions in any single template string is 1, counting {{ bos_token }}, a literal , and begin_of_text, and dict templates counted per value. The count = 1 narrowing is still a gratuitous change from the previous unbounded re.sub, so if you would rather restore the old semantics that is a one-token edit and I have no objection; I am not making it on reachability grounds alone.
d8ae79b tokenizes every rendered chat prompt with add_special_tokens = False. That is right when the template emits BOS, and wrong when it does not, because the tokenizer's BOS is then dropped and nothing puts one back. Measured across 30 chat models on transformers 5.5.0 and 5.16.1, counting leading BOS in the tokenized rendered prompt: 11 fixed template emits BOS and tokenizer adds one, 2 -> 1 17 unchanged Qwen, Phi, GLM, gpt-oss, SmolLM2, gemma-4-it and the google mirrors 2 regressed tinyllama-chat and zephyr-sft, 1 -> 0 Both regressions are the same shape: a template that does not emit BOS on a Llama-architecture tokenizer that does. That covers a lot of community chat finetunes, so it is worth being exact. Decide per prompt instead. _prompt_already_has_bos tokenizes the rendered text with special tokens off and checks whether the first id is already BOS, which is the only thing that settles it. All 30 models now come out at exactly one BOS, with no case left wrong. Also applied to the vision model's text-only path, which renders a chat template through format_chat_prompt and had the same double-BOS exposure without the flag. Tests: 10 cases over the four template and tokenizer combinations, plus a processor wrapper, an empty prompt, a tokenizer with no bos_token, and one that raises when called. They build real tokenizers backends in memory, so no weights and no network. Studio chat and inference suites: 252 passed.
|
Pushed What
|
| outcome | count | models |
|---|---|---|
| fixed, 2 BOS to 1 | 11 | Llama 2 and 3.x, Mistral 7B and Small 24B, gemma-2-it, gemma-3-it, gemma-3n-it, DeepSeek-R1-Distill |
| unchanged | 17 | Qwen 2.5 and 3, Phi 3.5 and 4, GLM-4, gpt-oss, SmolLM2, every gemma-4-it including google's |
| regressed, 1 BOS to 0 | 2 | unsloth/tinyllama-chat, unsloth/zephyr-sft |
Both regressions are the same shape: a chat template that does not emit BOS on a Llama-architecture tokenizer that does. That covers a fair number of community chat finetunes, so it is worth being exact rather than picking the majority case.
The change
_prompt_already_has_bos tokenizes the rendered text with special tokens off and checks whether the first id is already BOS. That is the only thing that actually settles it, since neither the template text nor add_bos_token is reliable on its own. All 30 models now land on exactly one BOS, with nothing left wrong:
FIXED=11 REGRESSED=2 UNCHANGED=17 (before)
WRONG after the fix (0): none (after)
I also applied it to the vision model's text-only path at inference.py:1493. That one renders a chat template through format_chat_prompt and then tokenized with plain defaults, so it had the same double-BOS exposure that d8ae79b set out to fix, just without the flag.
Testing
10 new cases in studio/backend/tests/test_chat_prompt_bos.py covering the four template and tokenizer combinations, plus a processor wrapper, an empty prompt, a tokenizer with no bos_token, and one that raises when called. They build real tokenizers backends in memory, so no weights and no network.
Studio chat and inference suites: 252 passed across test_chat_prompt_bos, test_chat_text_encoding, test_chat_turn_end_eos, test_chat_template_continuation, test_chat_only_reason, test_chat_message_identity, test_chat_template_tool_arguments, test_chat_attachments, test_audio_token_detection and test_chat_eos_template_refresh.
Worth noting the repo CI here is queued behind about 446 org-wide runs, so the checks on this PR have been sitting pending rather than failing.
ProcessorMixin.save_pretrained writes the processor's own chat_template.jinja
(processing_utils.py), but the export deduped only tokenizer.tokenizer, so the processor copy
kept its {{ bos_token }}. With this PR enabling tokenizer-level BOS for Gemma 4 base, that
exports a GGUF whose template prepends a second BOS.
Reproduced: after _dedupe_bos_chat_template(processor.tokenizer) the inner copy is stripped
while processor.chat_template still reads "{{ bos_token }}...".
_dedupe_bos_chat_template now decides once from the inner tokenizer, since a processor cannot
be called without an image, then strips every copy it owns. The export passes the processor
rather than the inner tokenizer and restores both templates afterwards.
tests/python is 61 files AGPL-3.0 to 1 Apache, and the gate enforces it. The docstring also claimed google/gemma-4-* carries add_bos_token; it omits the key on E4B, 31B and 26B-A4B and prepends BOS from tokenizer.json's post_processor instead.
Opening comment-reduction pass, AST-gated as comments only. 50 added comment lines down to 40. The release-day provenance for the stale mirrors belongs in the PR description, not the source.
|
@codex security review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
core/inference/inference.py imports unsloth and trl at module scope, and the studio-backend-ci.yml matrix installs neither, so the module-level import in test_chat_prompt_bos.py failed collection and took the whole job down on all four Python versions. Same _stub_if_missing block as test_vision_client_tools.py, installed before the import and dropped after it.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 55ad9541af
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| inputs = raw_tokenizer( | ||
| formatted_prompt, | ||
| return_tensors = "pt", | ||
| add_special_tokens = not _prompt_already_has_bos(raw_tokenizer, formatted_prompt), |
There was a problem hiding this comment.
Preserve BOS on the multimodal processor path
When Studio serves an image with a repaired Gemma 4 base tokenizer, _needs_gemma4_base_bos has necessarily found no BOS-emitting template, but _generate_vision_response still calls processor(..., add_special_tokens = False) in its image branch. That disables the tokenizer post-processor enabled by this change, so multimodal prompts still omit BOS and retain the degenerate-generation failure this commit addresses; apply the same _prompt_already_has_bos decision used here to the processor call.
Useful? React with 👍 / 👎.
Fixes #7903.
Gemma 4 base (non-it) Hub mirrors ship without add_bos_token: true even though google/gemma-4-* includes it. Without BOS, base-model inference degenerates into repeated text.
Set add_bos_token at load time for E2B, E4B, 31B, and 26B-A4B base families (and -unsloth-bnb-4bit variants). -it models are untouched because chat templates already emit bos_token.
Rebased onto latest main; supersedes closed #8044.