Repository navigation
[tokenizer] Pass bos and eos into Hugging Face chat templates - #5757
Conversation
|
|
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The bug is real on main: Llama-3-style templates that reference bos_token/eos_token render without them on the default SFT path. The fix belongs in HuggingFaceTokenizer, but it should replace the identical experiment overrides rather than duplicate them. This touches core, so a maintainer still needs to review.
What this PR does. It moves two behaviors from the experiment HFBackendTokenizer into HuggingFaceTokenizer:
apply_chat_templatepassesbos_token/eos_tokento the Jinja template (caller kwargs still win).encodeskips prepending BOS when the text already starts with the BOS string.
SFT token ids change for templates that reference those variables. That is expected and explained in the description. No golden loss files are affected.
Example. Test asset template {{ bos_token }}{% for m in messages %}{{ m.role }}\n{{ m.content }}{{ eos_token }}{% endfor %}, messages user/hi, assistant/yo, run through ChatProcessor:
main: "user\nhiassistant\nyo" -> [BOS] user\nhi assistant\nyo [EOS appended by ChatProcessor]
PR: "<|begin_of_text|>user\nhi<|end_of_text|>assistant\nyo<|end_of_text|>" -> [BOS] user\nhi [EOS] assistant\nyo [EOS]
The real Llama 3 template writes {{- bos_token }} and <|eot_id|>. So on main only BOS was missing; ChatProcessor's add_bos=True was covering for it.
Must fix
- The PR description's "Summary (human-written)" section is empty. The author needs to fill it in.
torchtitan/experiments/transformers_modeling_backend/tokenizer.py:46-55:HFBackendTokenizer.apply_chat_templateand.encodeare now exact duplicates of the new base code. Delete them and fix the class docstring (details inline attokenizer.py:429).tests/unit_tests/cpu/components/data/test_chat_dataset.py:344:TestHuggingFaceTokenizerChatTemplateTokensduplicatestest_shifted_by_one. Delete it, and switchTestHFBackendTokenizerChatLabelstoHuggingFaceTokenizer.
Should consider
torchtitan/components/tokenizer.py:460:encodenow overrides an explicitadd_bos=True. Document that in theadd_bosdocstring.tests/unit_tests/cpu/components/data/test_chat_dataset.py:200: four of the five new token assertions are implied by the exact-string check or by the code just above them.torchtitan/components/renderer.py:80-81: theDefaultRenderererror message still namesbos_tokenas a missing template variable. Change the example (e.g. "pad_token,unk_token, ...") or say "HF's fullspecial_tokens_map".
Details
- Gate: the problem is concrete (asset template plus Llama 3), the root cause is in the right layer (the tokenizer owns
bos_token/eos_token;BaseTokenizerdoes not), and no overlapping open PR exists. The alternatives the PR lists (move it into ChatProcessor or BaseTokenizer) are correctly rejected. - HF transformers passes the whole
special_tokens_map(bos, eos, unk, pad, ...) into the template. This PR covers only bos/eos. That is fine as a minimal fix, since no in-repo template is known to need the others. - Prompt/response boundary: with the asset template,
apply_chat_template([user], add_generation_prompt=True)renders<bos>user\nQ<eos>assistant\n, which is still a token prefix of the full sequence. So_require_token_prefixkeeps working, and the supervised suffix isanswer + [EOS], as asserted byTestHFBackendTokenizerChatLabels. - Pre-existing, out of scope: when
bos_token == eos_token, the base tokenizer sets onlybos_token, so{{ eos_token }}still renders""on the default path.HFBackendTokenizer.__init__repairs this only for the experiment.
Not verified: I didn't check SFT loss on a real Llama 3 tokenizer. The asset-based reasoning above is from reading the code.
| def apply_chat_template( | ||
| self, messages: Sequence[Mapping[str, Any]], **kwargs | ||
| ) -> str: | ||
| """Render messages with this tokenizer's BOS and EOS strings. | ||
|
|
||
| Jinja renders a missing ``bos_token`` or ``eos_token`` as an empty | ||
| string, which drops the special tokens from templates that reference | ||
| them. Pass ``""`` when a token is unset. Caller-supplied kwargs win. | ||
| """ | ||
| kwargs.setdefault("bos_token", self.bos_token or "") | ||
| kwargs.setdefault("eos_token", self.eos_token or "") | ||
| return super().apply_chat_template(messages, **kwargs) |
There was a problem hiding this comment.
These two overrides (this one and the BOS check in encode at 460-463) are copied line for line from HFBackendTokenizer.apply_chat_template / HFBackendTokenizer.encode in torchtitan/experiments/transformers_modeling_backend/tokenizer.py:46-55. Leaving them in the subclass means the same logic lives in two places, and every call runs the setdefault and startswith checks twice.
Please delete both methods from HFBackendTokenizer in this PR. Its __init__ eos repair and the {% generation %} rewrite in set_chat_template can stay. Also update its class docstring ("The base tokenizer only passes messages. This subclass auto-injects special tokens..."), which is no longer true. That is roughly -10 LoC.
There was a problem hiding this comment.
Deleted HFBackendTokenizer.apply_chat_template and encode. Those methods repeated the base setdefault and the BOS prefix check, so both ran twice. __init__ still repairs eos when eos_id was left unset, and set_chat_template still rewrites {% generation %} tags. The class docstring now says that. d539942.
| # Chat templates such as Llama 3 render bos_token into the text. | ||
| # ChatProcessor still passes add_bos=True; do not insert a second BOS. | ||
| if self.bos_token and text.startswith(self.bos_token): | ||
| kwargs["add_bos"] = False |
There was a problem hiding this comment.
This overrides an explicit add_bos=True from the caller, so add_bos no longer means what the encode docstring above says ("Whether to add BOS token"). It now means "make sure the text starts with BOS". That is a reasonable contract, and it also stops pretraining text that starts with the literal BOS string from getting two BOS ids (text_datasets.py:53). But the docstring should say it, since encode is shared by every HuggingFaceTokenizer caller.
Smallest fix: document it in the add_bos arg docstring, e.g. add_bos (bool): Whether to add a BOS token. Skipped if text already starts with bos_token. The other option is to make the decision at the two ChatProcessor call sites (text_datasets.py:166,179) with add_bos=not text.startswith(bos_token). That keeps encode literal, but it needs bos_token on BaseTokenizer, so I'd go with the docstring.
There was a problem hiding this comment.
Documented on add_bos: skipped when the text already starts with bos_token. ChatProcessor and pretraining encode(..., add_bos=True) want one BOS, not a second one. The branch is unchanged. d539942.
| class TestHuggingFaceTokenizerChatTemplateTokens(unittest.TestCase): | ||
| """Asset chat templates must receive bos_token and eos_token.""" | ||
|
|
||
| def test_apply_chat_template_includes_bos_and_eos_once(self): | ||
| tokenizer = HuggingFaceTokenizer(tokenizer_path=_TOKENIZER_PATH) | ||
| rendered = tokenizer.apply_chat_template( | ||
| [ | ||
| {"role": "user", "content": "hi"}, | ||
| {"role": "assistant", "content": "yo"}, | ||
| ] | ||
| ) | ||
| self.assertIn("<|begin_of_text|>", rendered) | ||
| self.assertIn("<|end_of_text|>", rendered) | ||
| # ChatProcessor encodes the rendered string with add_bos=True. | ||
| tokens = tokenizer.encode(rendered, add_bos=True, add_eos=False) | ||
| self.assertEqual(tokens.count(tokenizer.bos_id), 1) |
There was a problem hiding this comment.
This class tests nothing new. test_shifted_by_one (lines 189-206) already asserts the exact rendered string with both BOS and EOS, and that there is exactly one BOS id after encode(..., add_bos=True). Please delete it.
Also, once the duplicate overrides are removed from HFBackendTokenizer, TestHFBackendTokenizerChatLabels below exercises base-class behavior through an experiment class from a core test directory. Switching it to HuggingFaceTokenizer (and renaming it, e.g. TestChatTemplateSpecialTokens) moves the BOS/answer-only-labels coverage to the default path and removes a core-test -> experiment import. The experiment-specific parts ({% generation %} rewrite, eos repair) would then belong in the experiment's own tests if they need coverage.
There was a problem hiding this comment.
Deleted TestHuggingFaceTokenizerChatTemplateTokens. test_shifted_by_one already checks the rendered string and one BOS id. TestHFBackendTokenizerChatLabels is now TestChatTemplateSpecialTokens on HuggingFaceTokenizer and still checks answer-only labels. {% generation %} coverage stays in test_hf_backend_renders_generation_tags. d539942.
| # The template renders bos_token and ChatProcessor also passes add_bos=True. | ||
| self.assertEqual(full_tokens[0], tokenizer.bos_id) | ||
| self.assertEqual(full_tokens.count(tokenizer.bos_id), 1) | ||
| # eos_token closes the user turn and the assistant turn. | ||
| self.assertEqual(full_tokens.count(tokenizer.eos_id), 2) | ||
| self.assertEqual(full_tokens[-1], tokenizer.eos_id) | ||
| self.assertIn(tokenizer.eos_id, full_tokens[:-1]) |
There was a problem hiding this comment.
The exact-string assertion at 191-196 already pins where BOS and EOS go. Of these, only count(bos_id) == 1 checks something new: the encode dedup. full_tokens[-1] == eos_id is guaranteed by the append two lines up, and assertIn(eos_id, full_tokens[:-1]) follows from count == 2. Suggest keeping only the BOS count:
| # The template renders bos_token and ChatProcessor also passes add_bos=True. | |
| self.assertEqual(full_tokens[0], tokenizer.bos_id) | |
| self.assertEqual(full_tokens.count(tokenizer.bos_id), 1) | |
| # eos_token closes the user turn and the assistant turn. | |
| self.assertEqual(full_tokens.count(tokenizer.eos_id), 2) | |
| self.assertEqual(full_tokens[-1], tokenizer.eos_id) | |
| self.assertIn(tokenizer.eos_id, full_tokens[:-1]) | |
| # The template renders bos_token and ChatProcessor also passes add_bos=True. | |
| self.assertEqual(full_tokens.count(tokenizer.bos_id), 1) |
There was a problem hiding this comment.
Dropped full_tokens[0] == bos_id, full_tokens[-1] == eos_id, and assertIn(eos_id, full_tokens[:-1]). Kept count(bos_id) == 1 and count(eos_id) == 2. The last-id assert follows from the append just above, and assertIn follows from the count. The count is what shows both EOS markers became EOS ids. d539942.
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. Every code item from the last review is fixed at HEAD. The only thing still open is the empty human-written summary. This touches core, so a maintainer still needs to review.
What changed since the last review (d539942). HFBackendTokenizer no longer duplicates the base apply_chat_template/encode. The redundant test class is gone, and the label test now runs on HuggingFaceTokenizer. The encode docstring and the DefaultRenderer error message are updated.
Example (unchanged). Asset template, messages user/hi, assistant/yo:
main: "user\nhiassistant\nyo" -> [BOS] ... [EOS appended]
PR: "<|begin_of_text|>user\nhi<|end_of_text|>assistant\nyo<|end_of_text|>" -> [BOS] ... [EOS] ... [EOS]
Earlier must-fix items
- The "Summary (human-written)" section is empty. Still open: the author needs to write it.
- Duplicate
HFBackendTokenizer.apply_chat_template/encodeoverrides. Resolved: deleted, and the class docstring now describes only the{% generation %}rewrite and the eos repair (torchtitan/experiments/transformers_modeling_backend/tokenizer.py:16-22). No caller relied on the subclass'sencode(text, **kwargs)signature. The base takes*args, **kwargsand readsargs[0]. - Redundant
TestHuggingFaceTokenizerChatTemplateTokens, plus the core test importing the experiment. Resolved: the class is deleted, andTestChatTemplateSpecialTokensuses_load_tokenizer()(HuggingFaceTokenizer).
Earlier should-consider items: the add_bos docstring and the renderer error message are fixed. The extra token assertions in test_shifted_by_one are cut down to the BOS and EOS counts.
Should consider
tests/unit_tests/cpu/components/data/test_chat_dataset.py:353-355(outside the diff hunk, so not inline): now that both tests use the same tokenizer, the two BOS asserts intest_single_bos_and_answer_only_labelsrepeattest_shifted_by_one. That test already checkscount(bos_id) == 1and that the processor input equalsfull_tokens. Only the exact answer-only label check is new. You can drop those three lines and keep the label assertion.
No new problems in the new commits.
Not verified: I didn't run the CPU tests locally. CI needs to confirm test_chat_dataset.py and test_tokenizer.py pass.
|
CPU failure is real For GPU tests, numerics need to be regenerated. Please wait until all tests finished before updating them together. |
The refusal still happens. The message now says TorchTitan passes only those two tokens, so the old special-token variables substring no longer matches.
The chat template now emits bos and eos, so llama3_debugmodel_sft no longer matches the old curve. These ten steps are the A10G fake PG run from CI.
|
Will wait until all remaining pending tests finished, and will update the numerics and push them. For CPU and 1 GPU failures, have fixed and commited locally, but did not push it yet. |
|
All other CI tests passed, so pushed the fixes |
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Why
The Real PG integration suite (`8 GPU Integration (Real PG - full suite
- features)`) and the ROCm integration suite have failed the `sft` loss
check on main since #5757 (`899480301`; `a87db08ea` before it passed):
```
[sft] AssertionError: 7.889825820922852 != 7.887711524963379 : loss mismatch at step 1 # A10G
[sft] AssertionError: 7.890093803405762 != 7.887524604797363 : loss mismatch at step 1 # MI350X
```
#5757 renders `bos_token`/`eos_token` in Hugging Face chat templates, an
intended change to the SFT token stream. It regenerated
`tests/assets/losses/fake_pg/a10g/sft.txt` but not the real-PG A10G and
MI350X goldens.
## What changed
- `tests/assets/losses/real_pg/a10g/sft.txt` and
`tests/assets/losses/real_pg/mi350x/sft.txt`: steps 1-10 regenerated;
headers unchanged.
## Numerics
The new values are the full-precision TensorBoard metrics of the failing
main runs' baseline training (the same values `loss_compare.py
--export-result` writes), read with `scripts/loss_compare.py`'s own
extraction from the uploaded `integration-8gpu-features-outputs`
artifacts:
- A10G: run 41746280593 (`e6ca6d861`). Step 1 matches the log's baseline
(7.889825820922852, grad_norm 4.189799785614014).
- MI350X: the ROCm run on `73c4ebdac`. Step 1 matches the log's baseline
(7.890093803405762, grad_norm 4.189815998077393).
The commits between #5757 and those runs (#5572, #5787, #5776, #5774,
#5779, #5741, #5786) do not change SFT numerics.
## Testing
- CI: Real PG (`ciflow/real-pg`) and ROCm (`ciflow/rocm`) integration
suites.
- A manual `export_results` run of the integration workflow for `sft` on
main (run 41760303504) exported a real-PG A10G golden identical to this
one.
- `Multi-GPU Unit Tests` fails here with the `_VisionEncoder ...
named_preserve_dtype_params` error that is also on main; #5795 fixes it.
This PR was AI-assisted.
Conflicts resolved so main's new behavior and this PR's sum-then-scale design both hold: - #4819 (FLOPs per input batch): the graphable forward/backward returns (loss, metrics) and forward_backward builds ForwardBackwardResult with num_flops; kept, with this PR's single-argument _run_forward_backward. The core, GraphTrainer and TorchFT trainers keep main's FLOPs reduction and this PR's loss logging (sums divided by the step's loss tokens). TorchFT averages FLOPs over the replicas when ft_pg is set, also without DP or CP. - #5779 (max_context_length from the model config): preprocess_inputs drops max_context_length and keeps aux_loss_denominators. - #5563 (ChunkedLossWrapper keeps caller FSDP policies): main's chunked loop, without the count argument. test_chunked_loss_fsdp.py: losses are sums; the test divides gradients once by the loss tokens before comparing, as optim_step does. - #5757/#5796 (SFT data change): sft.txt goldens taken from main; regenerated from CI next.
Main's SFT data change (#5757/#5796) set the step-1 loss token count to N = 8080 (real PG) and 4066 (fake PG). Main rounds 1/N to bf16 at the logits, this PR divides the fp32 gradients by N once. Step-1 loss is bitwise; step-1 grad norm moves by fp32(1/N)/bf16(1/N): - real_pg/a10g: 4.189800 -> 4.182507 (x0.99826), run 41978609975 job 127083279813 - real_pg/mi350x: 4.189816 -> 4.182497 (x0.99825), run 41978590756 job 127083230002 - fake_pg/a10g: 4.005685 -> 4.003838 (x0.99954), run 41978607830 job 127083270741 Values copied from each job's "Baseline metrics in import file format" block; the "#" header lines are kept and the "# config:" lines match.
Summary (human-written)
Why
HuggingFaceTokenizer.apply_chat_templaterendered withmessagesand the caller's kwargs only. Jinja's default Undefined becomes an empty string, so a template that prints{{ bos_token }}or{{ eos_token }}dropped both. Default recipes useHuggingFaceTokenizer, not the experiment subclass that already passed those strings.encode(..., add_bos=True)only prepends BOS. It does not put EOS between turns.ChatProcessorcallsencodethat way on the rendered string, then appends one EOS if the last id is not already EOS.Example. Asset template in
tests/assets/tokenizer(bos_tokenis<|begin_of_text|>,eos_tokenis<|end_of_text|>), messagesuser/hithenassistant/yo:Same text,
encode(..., add_bos=True, add_eos=False)on that asset tokenizer:What changed
HuggingFaceTokenizer.apply_chat_templatepassesbos_tokenandeos_tokenviasetdefault. Caller kwargs win. A missing token is"", so Jinja does not see Undefined.HuggingFaceTokenizer.encodesetsadd_bos=Falsewhen the text already starts withbos_token, soChatProcessor'sadd_bos=Truedoes not insert a second BOS.HFBackendTokenizer.apply_chat_templateandencodeare deleted. They repeated the basesetdefaultand the BOS prefix check.__init__still repairs eos wheneos_idwas left unset, andset_chat_templatestill rewrites{% generation %}tags.encode'sadd_bosdocstring says the prepend is skipped when the text already starts withbos_token.DefaultRenderer's error no longer namesbos_tokenas a variable this tokenizer omits. It names the rest of the special-token map (pad_token,unk_token, ...).tests/unit_tests/cpu/components/data/test_chat_dataset.pystill expects the corrected render.TestHuggingFaceTokenizerChatTemplateTokensis gone (test_shifted_by_onealready checks that string and one BOS id).TestHFBackendTokenizerChatLabelsisTestChatTemplateSpecialTokensonHuggingFaceTokenizerand still checks answer-only labels.Alternatives considered
HFBackendTokenizer. That subclass also rewrites{% generation %}tags and repairs eos when bos and eos are the same string. Default SFT should not depend on the experiment tokenizer for variables the base tokenizer already knows.HFBackendTokenizer. No. After the base change they only ran the samesetdefaultand prefix check a second time.BaseTokenizer.apply_chat_template. The base class has nobos_tokenoreos_token.ChatProcessorafter rendering. The template already says where they go, and any otherapply_chat_templatecaller would still drop them.User-facing changes
This changes SFT chat strings for every recipe that uses
HuggingFaceTokenizerand a template that referencesbos_token/eos_token. Templates that do not reference those names are unchanged, because the extra kwargs are unused.encodechanges only when the text already starts withbos_token.{{ bos_token }}/{{ eos_token }}render as empty strings""if unset)encode(rendered, add_bos=True)prepends BOS even when the template already wrote it{{ eos_token }}, including between turnsbos_token=/eos_token=Numerics
Not bitwise-identical. Chat token ids change for those templates, so SFT loss on the same rows will not match the base commit
4759738106a6f198a4dd41c78d2a754be5d0b2c4. No GPU loss comparison. No golden loss files to regenerate: this does not change the model forward, only the chat strings fed to it. Pretraining text that does not start withbos_tokenencodes as before.Testing
setdefaultor the prefix check.py_compileof the four touched files succeeded.ufmt2.3.0 reported them already formatted./opt/homebrew/anaconda3/bin/python -m pytest tests/unit_tests/cpu/components/data/test_chat_dataset.py -qstill does not collect here (spmd_typeshas norules, then NumPy 2.2.6 vs bottleneck). CI has to run it.{% generation %}coverage stays intests/unit_tests/cpu/components/test_tokenizer.py.Known issues / follow-ups
Local collection failure above is an environment mismatch, not this diff. No follow-up code change.