Skip to content

fix(tokenizer): enable add_bos_token for Gemma 4 base models - #10312

Merged
danielhanchen merged 23 commits into
unslothai:mainfrom
Souravrajvi0:feat/gemma4-base-bos-token-471a
Sep 8, 2026
Merged

danielhanchen merged 23 commits into
unslothai:mainfrom
Souravrajvi0:feat/gemma4-base-bos-token-471a

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

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.

Souravrajvi0 and others added 2 commits September 4, 2026 19:19
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.
@danielhanchen

Copy link
Copy Markdown
Member

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?

Souravrajvi0 and others added 6 commits September 6, 2026 08:07
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.
@Souravrajvi0

Souravrajvi0 commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks Daniel, updated the pr

Detection no longer uses a Hub-name regex. We key off the loaded tokenizer (processor_class, Gemma 4 think_token/boa_token) and the model config (model_type / text_config, including gemma4_text). That covers local folders and extra quant suffixes such as gemma-4-31B-bnb-4bit.

-it is still left alone when the chat template already emits bos_token or eos is <turn|>.

The same heal now runs on the FastModel processor path (the #7903 repro) after the tokenizer is finalized, and load_correct_tokenizer takes the loaded model.config so a stripped local tokenizer still matches.

@Imagineer99 Imagineer99 self-assigned this Sep 7, 2026
@Imagineer99
Imagineer99 marked this pull request as ready for review September 7, 2026 10:37
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-08T09:32:53.059145Z 55ad954 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/tokenizer_utils.py Resolved
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.
@Imagineer99

Copy link
Copy Markdown
Member

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.

Souravrajvi0 and others added 2 commits September 7, 2026 13:30
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.
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

@Imagineer99 Thanks for catching this — agreed on the duplicate BOS after chat template + save/reload.

Pushed a follow-up on feat/gemma4-base-bos-token-471a (3371ffe17) that keeps add_bos_token for raw completions but strips template-emitted bos_token when the tokenizer already prepends BOS:

  • _dedupe_bos_chat_template runs after the base-model BOS repair (covers save/reload configs that persisted both flags)
  • get_chat_template no longer prepends {{ bos_token }} when auto-BOS is already on
  • fix_tokenizer_bos_token shares the same strip helper for GGUF/save paths

Raw tokenizer("...") still gets one BOS; rendered chat prompts should no longer double up. Happy to re-run the A/B if useful.

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.
@Imagineer99

Copy link
Copy Markdown
Member

Stripping template BOS introduces missing BOS with apply_chat_template(tokenize=True), which disables automatic special-token insertion. Local testing at 0097930 confirms this. Please preserve template BOS and disable additional special tokens when encoding rendered chat prompts instead. This candidate fix passes Linux, Windows and macOS A/B tests against the earlier PR head while preserving BOS for raw completions.

@Imagineer99

Copy link
Copy Markdown
Member

Fix added in b875482ff. Runtime templates retain BOS, while Studio avoids adding special tokens again to rendered chat. Raw completions retain automatic BOS. A/B validation passes on Linux, Windows and macOS. These checks run on the staging fork against the same product code.

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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed b2d798d with a slim-down and some hardening. Also chased the root cause on the Hub, which turned out to be more interesting than the issue thread suggested.

The mirrors are stale, we did not break them

unsloth/gemma-4-* base kept google's release-day tokenizer.json. Google replaced it about three hours later on 2026-04-02:

repo mirrored google patched tokenizer.json
gemma-4-E2B 13:04 16:14
gemma-4-E4B 13:03 16:14
gemma-4-31B 13:01 16:12
gemma-4-26B-A4B 12:52 16:13

Our file is byte identical to google's pre-patch blob (sha256 cc8d3a0c) on all four. gemma-4-12b was mirrored in June and is already correct, which is the control.

The two files differ at exactly three paths, all inside post_processor:

/post_processor/single                  google: ['<bos>', 'A']   ours: ['A']
/post_processor/pair                    google: 4 entries        ours: 2
/post_processor/special_tokens/<bos>    google: present          ours: missing

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 add_bos_token key in tokenizer_config.json, which is not where BOS lives: google omits that key on E4B, 31B and 26B-A4B and those repos still prepend. Second, google leaves every -it repo BOS-less too, so skipping -it keeps us matching upstream rather than diverging from it.

Separately from this PR, the seven stale base repos want a tokenizer.json re-upload, since that also fixes vLLM, llama.cpp and MLX users who never touch our loader.

What I changed

Detection is now two signals instead of five: processor_class == Gemma4Processor read from init_kwargs, and model_type / architectures through one anchored regex.

Removed, with the evidence:

  • The class-name branch never fired. Gemma 4 loads as GemmaTokenizer, not Gemma4Tokenizer.
  • think_token + boa_token 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 needs transformers >= 5.5.0, so no supported version reaches the hand-built post-processor. The concern behind it is real on 4.x though, so I kept a warning for it instead.

Behaviour changes:

  • Keyed on the emitted ids rather than add_bos_token. That attribute reads False on google's own patched mirrors while they still prepend, so it was never usable. 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.
  • 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.
  • The anchored regex stops two false positives the old prefix and substring tests allowed: a future gemma_45 or gemma-4.5, and DiffusionGemma4ForConditionalGeneration.

Verification

On unsloth/gemma-4-E2B, 4-bit, seed 3407, four prompts, greedy and sampled, each arm in its own process:

arm leading BOS repeat-4gram distinct longest run
before the fix 0 0.75 - 0.92 0.06 - 0.17 49 - 59
hardcoded <bos>, the control from #7903 1 0.00 - 0.15 0.45 - 0.75 1 - 3
this PR 1 identical to control identical identical

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 -it repo, every google repo, and Llama 3.2, Qwen3, Qwen2.5, Mistral, Phi-4, Gemma 2, Gemma 3 and Gemma 3n encode byte identically before and after. A healed E2B is byte identical to google/gemma-4-E2B and survives save_pretrained plus a reload. fix_tokenizer = False opts out on both loader paths.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +131 to +133
text = _JINJA_COMMENT_RE.sub("", chunk if isinstance(chunk, str) else str(chunk))
if "bos_token" in text or "<bos>" in text:
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment on lines +160 to +164
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed c161fec for the Studio side of this. d8ae79b fixes double BOS for most models but silently drops it for a couple, so I made the decision per prompt instead.

What d8ae79b does today

It 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.

I measured it across 30 chat models on transformers 5.5.0 and 5.16.1, counting leading BOS in the tokenized rendered prompt:

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: cb471a59ef

ℹ️ 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".

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: aa2ce5b9f0

ℹ️ 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".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 8, 2026
@danielhanchen
danielhanchen merged commit 30529a6 into unslothai:main Sep 8, 2026
48 of 50 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Gemma 4 base models are missing <bos> token in tokenizer config

3 participants