Repository navigation
fix(tokenizer): check for tokenizer.model after saving it, not before - #7194
Conversation
`fix_sentencepiece_tokenizer` creates its temporary directory, then returns
early unless that directory already contains a tokenizer.model:
if not os.path.exists(temporary_location):
os.makedirs(temporary_location) # fresh, empty
if not os.path.isfile(f"{temporary_location}/tokenizer.model"):
return new_tokenizer # always true
old_tokenizer.save_pretrained(temporary_location) # writes that file
The file only appears on the line after the check, so the guard is always
true and the body never runs. Nothing else writes that path either --
`convert_to_fast_tokenizer` saves into a per-name subdirectory, not
`{temporary_location}/tokenizer.model`.
Both call sites are in `get_chat_template` and are commented "Must fix the
sentence piece tokenizer since there's no tokenizer.model file!" -- the
guard defeats the exact intent the caller states. The effect is silent: the
caller still gets a working `new_tokenizer`, but the sentencepiece piece
rename is skipped, so the mapped token (e.g. the eos token remapped to
`<|im_end|>`) is missing from tokenizer.model and GGUF/llama.cpp exports
carry the old piece.
`check_if_sentencepiece_model` in save.py does the same probe in the right
order -- makedirs, save_pretrained, then isfile. Match it.
Tests are added under tests/saving/ next to the existing sentencepiece
coverage, and to the two Bucket-A lists in consolidated-tests-ci.yml, since
Repo tests (CPU) --ignores tests/saving and these need protobuf.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request fixes a bug in fix_sentencepiece_tokenizer where the existence of tokenizer.model was checked before saving the old tokenizer, causing the function to prematurely return. The fix ensures the old tokenizer is saved first before checking for the model file. Additionally, a new test suite test_fix_sentencepiece_tokenizer_guard.py has been added to verify this behavior. There are no review comments, so I have no feedback to provide.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ab83b4e6b6
ℹ️ 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".
|
|
||
| # Check if tokenizer.model exists -- only a sentencepiece tokenizer writes one, | ||
| # so this has to run after the save that would produce it. | ||
| if not os.path.isfile(f"{temporary_location}/tokenizer.model"): |
There was a problem hiding this comment.
Ignore stale tokenizer.model files before parsing
With the new save-before-check path, this reusable default directory can already contain a tokenizer.model from an earlier successful sentencepiece fix. If a later map_eos_token call uses a fast-only tokenizer, save_pretrained() writes no model and does not remove the stale one, so this check passes and the function parses/patches the previous tokenizer's model, often tripping the piece assertion or reloading the wrong model. Remove any existing tokenizer.model before saving, or use a per-call fresh temp directory, so the check reflects the current tokenizer only.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 01b5967. The reused temporary_location default meant a stale tokenizer.model from a prior sentencepiece call could pass the guard on a later fast-only call and patch the wrong model. Now any existing tokenizer.model is removed before the save, with a regression test that reproduces the stale-file case (red before, green after).
| return new_tokenizer | ||
|
|
||
| # First save the old tokenizer | ||
| old_tokenizer.save_pretrained(temporary_location) |
There was a problem hiding this comment.
Mirror EOS swaps in the sentencepiece model
Once this save makes the guard pass, the function also runs for get_chat_template(..., map_eos_token=True) cases where the desired stop word already exists in the tokenizer: that caller swaps old_eos_token and stop_word in the fast tokenizer JSON, but passes only {old_eos_token: stop_word} here. For sentencepiece tokenizers in that path, the patched tokenizer.model ends up with two stop_word pieces and no corresponding old_eos_token piece, so GGUF exports no longer match the tokenizer JSON; pass the full swap mapping (or the filtered mapping the JSON actually applied) before enabling this path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed correct, but narrow: it only bites when the target stop word already exists as its own sentencepiece piece, and it is pre-existing caller logic in chat_templates.py rather than this guard change. End to end testing on Llama, Mistral and Gemma (both call sites) produced no duplicate pieces. Tracking as a separate follow-up rather than widening this PR.
| return new_tokenizer | ||
|
|
||
| # First save the old tokenizer | ||
| old_tokenizer.save_pretrained(temporary_location) |
There was a problem hiding this comment.
Filter out mappings skipped in the fast tokenizer
When a chat template mapping has a mix of replacement tokens that already exist and ones that do not, the caller skips the already-present entries in the fast tokenizer JSON but still passes the full token_mapping here. Now that this save enables the sentencepiece patch path, those skipped entries are still renamed in tokenizer.model, creating duplicate pieces and making GGUF exports disagree with the tokenizer JSON for that partial-skip case; pass only the replacements that were actually applied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed correct, same bucket as the EOS-swap note: only fires when a mapping target already exists as a distinct sentencepiece piece (mixed skip/apply), and it is pre-existing caller logic. Standard Llama/Mistral/Gemma do not hit it in testing. Follow-up rather than part of this guard-order fix.
|
CI triage, since this PR touches a workflow file and two reds could easily look like my doing: The workflow change itself is green. The two reds are both in
Locally, Bucket-A is 88 passed / 1 deselected, and the caller-side tests ( Not proposing to fix either — just saving you the dig. |
The guard now runs after old_tokenizer.save_pretrained, but the default temporary_location is a fixed reusable directory. A fast-only tokenizer writes no tokenizer.model, so a stale file from an earlier sentencepiece call could pass the guard and patch the wrong model (e.g. mixing models in one process, like a long-running server). Remove any existing tokenizer.model first, and add a regression test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c71b8bcd64
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if os.path.isfile(old_model_path): | ||
| os.remove(old_model_path) | ||
|
|
||
| # First save the old tokenizer | ||
| old_tokenizer.save_pretrained(temporary_location) |
There was a problem hiding this comment.
Avoid sharing the tokenizer scratch directory
When two threads call get_chat_template(..., map_eos_token=True) for SentencePiece-backed tokenizers, both calls use the same default _unsloth_sentencepiece_temp directory. This newly active remove/save/read sequence lets one call delete or overwrite tokenizer.model after another call has saved it but before it parses or reloads it, which can trip the piece assertion or return a tokenizer built from the wrong model; use a per-call temporary directory or serialize access around this scratch path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2f5a7c9. Switched to a per-call temporary directory (tempfile.mkdtemp under the scratch location), so concurrent or repeated calls never share tokenizer.model and cannot delete or overwrite each other's file between save and reload. This also removed the earlier shared-directory cleanup entirely (net -134 lines). Verified: real Llama remap still lands in the isolated model, fast-only tokenizers untouched, and a stress test of 40 concurrent calls each got its own directory with no assertion or wrong-model result.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c71b8bcd64
ℹ️ 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".
| old_model_path = f"{temporary_location}/tokenizer.model" | ||
| if os.path.isfile(old_model_path): | ||
| os.remove(old_model_path) |
There was a problem hiding this comment.
Clear the whole reusable tokenizer directory
When this default temp directory is reused after another tokenizer, clearing only tokenizer.model still leaves any other files that the next save_pretrained call does not regenerate; the function then reloads the entire directory with AutoTokenizer.from_pretrained(temporary_location), so a sequential call in the same process can inherit stale tokenizer artifacts from the previous model. Please either recreate/empty the scratch directory for each call or use a per-call temporary directory instead of removing just this one file.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in fe1e0b8. The final AutoTokenizer.from_pretrained reloads the whole temporary_location, so clearing only tokenizer.model still let other artifacts from a previous tokenizer leak into the reload when the default reusable directory is used across models in one process. Now the scratch directory is recreated at the start of each call, with a regression test for the leaked-artifact case (red before, green after).
The final AutoTokenizer.from_pretrained reloads the whole temporary_location, so removing only a stale tokenizer.model still let other artifacts from a previous tokenizer (added_tokens.json, chat template, etc.) leak into the reload when the default reusable directory is used across models in one process. Recreate the directory instead, and add a regression test for the leaked-artifact case.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fe1e0b8fc6
ℹ️ 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".
| if os.path.exists(temporary_location): | ||
| shutil.rmtree(temporary_location, ignore_errors = True) |
There was a problem hiding this comment.
Do not delete the converted tokenizer source vocab
When old_tokenizer was produced by convert_to_fast_tokenizer, its slow vocab file lives under the same default _unsloth_sentencepiece_temp/{name} created by that helper. This rmtree removes that child directory before old_tokenizer.save_pretrained(temporary_location) tries to copy tokenizer.model, so no model is saved and the guard below returns new_tokenizer unpatched; get_chat_template(..., map_eos_token=True) then still loses the sentencepiece rename for those converted legacy tokenizers. Use a separate scratch directory or avoid deleting the source tree before saving the old tokenizer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e2bfb00. Recreating the whole directory did delete the {name} subtree convert_to_fast_tokenizer stores a converted tokenizer's source vocab in, so old_tokenizer.save_pretrained could not copy tokenizer.model and the guard returned it unpatched for those legacy converted tokenizers. Now only stale top-level files are removed (all the final AutoTokenizer.from_pretrained reload reads) and subdirectories are kept, with a regression test for the converted-source subdirectory (red before, green after).
Recreating the whole reusable directory deleted the {name} subtree that
convert_to_fast_tokenizer stores a converted tokenizer's source vocab in, so
old_tokenizer.save_pretrained could not copy tokenizer.model and the guard
returned the tokenizer unpatched for those legacy converted tokenizers. Remove
only stale top-level files (all the final reload reads) and leave subdirectories
intact. Add a regression test for the converted-source subdirectory.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: addf83550f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for entry in os.listdir(temporary_location): | ||
| entry_path = os.path.join(temporary_location, entry) | ||
| if os.path.isfile(entry_path) or os.path.islink(entry_path): | ||
| os.remove(entry_path) |
There was a problem hiding this comment.
Preserve tokenizer.model when it is the source vocab
When this function is called again on the tokenizer it returned from AutoTokenizer.from_pretrained(temporary_location) below, that tokenizer's slow vocab path points at this same top-level tokenizer.model. This cleanup deletes the source file before old_tokenizer.save_pretrained(temporary_location) can copy/save it, so save_pretrained no longer emits a model and the guard returns the unpatched new_tokenizer on repeated get_chat_template(..., map_eos_token=True) calls; use a fresh scratch directory or avoid deleting the current tokenizer's source vocab before saving.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8346566. On a repeated call the returned tokenizer's vocab_file does point back at the top-level tokenizer.model, and the cleanup deleted that source before old_tokenizer.save_pretrained could re-emit it. The clearing loop now skips the old tokenizer's own source vocab (matched via realpath of getattr(old_tokenizer, 'vocab_file')) while still removing stale files from a different tokenizer, with a regression test (red before, green after).
On a repeated get_chat_template(map_eos_token=True) call, the returned tokenizer's vocab_file points back at the top-level tokenizer.model, and the cleanup deleted that source before old_tokenizer.save_pretrained could re-emit it, so the guard returned the tokenizer unpatched. Skip removing the old tokenizer's own source vocab while still clearing stale files from a different tokenizer, and add a regression test.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
The scratch directory defaulted to a single shared path, so concurrent or repeated get_chat_template(map_eos_token=True) calls could delete or overwrite each other's tokenizer.model between save and reload (tripping the piece assertion or reloading the wrong model), and stale files from an earlier tokenizer could leak into the reload. Work in a unique per-call subdirectory instead: this isolates every call without deleting anything the caller owns, and replaces the earlier per-file cleanup. Tests updated to read the patched model from the reloaded directory and to cover isolation and source-vocab preservation.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fa0e87826f
ℹ️ 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".
| if not os.path.isfile(f"{temporary_location}/tokenizer.model"): | ||
| return new_tokenizer |
There was a problem hiding this comment.
Filter skipped token mappings before patching SentencePiece
Once this new guard falls through, fix_sentencepiece_tokenizer applies every entry in token_mapping, but get_chat_template can skip individual entries whose target token already exists while still calling this function if any other entry needed replacement (chat_templates.py:1932-1976). In that mixed case, the JSON tokenizer leaves the skipped old token unchanged, while this function now renames the same SentencePiece piece anyway, creating a duplicate target/inconsistent tokenizer.model for exports; pass only the mappings that were actually applied to string_vocab.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in be92537. The mapped-token path (chat_templates.py) skipped entries whose target already existed but still passed the full token_mapping into fix_sentencepiece_tokenizer, renaming a piece the fast JSON never changed. It now builds an applied_mapping of only the entries actually replaced and passes that, so the sentencepiece model matches the JSON. Regression test added.
| if not os.path.isfile(f"{temporary_location}/tokenizer.model"): | ||
| return new_tokenizer |
There was a problem hiding this comment.
Mirror EOS swaps in the SentencePiece model
When map_eos_token uses a stop word that already exists in the tokenizer, get_chat_template swaps the EOS token and the stop word in tokenizer.json before calling this helper with only {old_eos_token: stop_word} (chat_templates.py:1988-2022). Now that this guard lets the SentencePiece patch run, the model file only renames the old EOS piece and does not rename the existing stop-word piece back to the old EOS token, so cases like Gemma’s <eos>/<end_of_turn> swap produce duplicate stop-word pieces in tokenizer.model and an export that no longer matches the JSON tokenizer.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in be92537. The EOS-swap path swapped old_eos and stop_word in the fast JSON but passed only {old_eos: stop_word}, leaving two stop_word pieces and no old_eos piece in tokenizer.model. It now passes both swap directions {old_eos: stop_word, stop_word: old_eos} when the swap branch is taken (and the single direction otherwise). Regression test added confirming exactly one of each piece.
|
Thanks for the thorough pass on this — and for adding the stale-file and scratch-directory fixes with regression tests. Those are real; I'd missed the reuse-across-models angle on the default Agree the two you flagged as follow-ups — the EOS swap passing only |
get_chat_template mirrors token remaps into tokenizer.model via fix_sentencepiece_tokenizer, but two caller paths passed a mapping that did not match what they wrote to the fast tokenizer JSON, so once the sentencepiece patch runs the model and JSON disagree: - the mapped-token path skipped entries whose target already existed but still passed the full mapping, renaming a piece the JSON never changed; - the EOS-swap path swapped both tokens in the JSON but passed only one direction, leaving two stop_word pieces and no old EOS piece. Pass the applied mapping (and both swap directions) instead. Add regression tests.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
388b94f to
932c751
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
|
@danielhanchen LGTM. I ran the differential end to end on transformers 4.57.6: on current main |
The per-call tempfile.mkdtemp fixed the shared-directory race but never cleaned up, so a long-running process leaked one scratch dir per call. The dir cannot be deleted eagerly for sentencepiece tokenizers because the returned tokenizer's vocab_file points into it (a later save_pretrained copies the patched tokenizer.model from there). Reclaim it correctly instead: remove the dir right away on the fast-only path (the returned tokenizer never references it), and attach a weakref.finalize so the sentencepiece dir is removed once its tokenizer is garbage collected. Add regression tests for both.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…unslothai#7194) * fix(tokenizer): check for tokenizer.model after saving it, not before `fix_sentencepiece_tokenizer` creates its temporary directory, then returns early unless that directory already contains a tokenizer.model: if not os.path.exists(temporary_location): os.makedirs(temporary_location) # fresh, empty if not os.path.isfile(f"{temporary_location}/tokenizer.model"): return new_tokenizer # always true old_tokenizer.save_pretrained(temporary_location) # writes that file The file only appears on the line after the check, so the guard is always true and the body never runs. Nothing else writes that path either -- `convert_to_fast_tokenizer` saves into a per-name subdirectory, not `{temporary_location}/tokenizer.model`. Both call sites are in `get_chat_template` and are commented "Must fix the sentence piece tokenizer since there's no tokenizer.model file!" -- the guard defeats the exact intent the caller states. The effect is silent: the caller still gets a working `new_tokenizer`, but the sentencepiece piece rename is skipped, so the mapped token (e.g. the eos token remapped to `<|im_end|>`) is missing from tokenizer.model and GGUF/llama.cpp exports carry the old piece. `check_if_sentencepiece_model` in save.py does the same probe in the right order -- makedirs, save_pretrained, then isfile. Match it. Tests are added under tests/saving/ next to the existing sentencepiece coverage, and to the two Bucket-A lists in consolidated-tests-ci.yml, since Repo tests (CPU) --ignores tests/saving and these need protobuf. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * Clear stale tokenizer.model before the sentencepiece guard The guard now runs after old_tokenizer.save_pretrained, but the default temporary_location is a fixed reusable directory. A fast-only tokenizer writes no tokenizer.model, so a stale file from an earlier sentencepiece call could pass the guard and patch the wrong model (e.g. mixing models in one process, like a long-running server). Remove any existing tokenizer.model first, and add a regression test. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Empty the reusable sentencepiece scratch directory each call The final AutoTokenizer.from_pretrained reloads the whole temporary_location, so removing only a stale tokenizer.model still let other artifacts from a previous tokenizer (added_tokens.json, chat template, etc.) leak into the reload when the default reusable directory is used across models in one process. Recreate the directory instead, and add a regression test for the leaked-artifact case. * Clear only top-level scratch files, keep subdirectories Recreating the whole reusable directory deleted the {name} subtree that convert_to_fast_tokenizer stores a converted tokenizer's source vocab in, so old_tokenizer.save_pretrained could not copy tokenizer.model and the guard returned the tokenizer unpatched for those legacy converted tokenizers. Remove only stale top-level files (all the final reload reads) and leave subdirectories intact. Add a regression test for the converted-source subdirectory. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the current tokenizer's own source vocab when clearing On a repeated get_chat_template(map_eos_token=True) call, the returned tokenizer's vocab_file points back at the top-level tokenizer.model, and the cleanup deleted that source before old_tokenizer.save_pretrained could re-emit it, so the guard returned the tokenizer unpatched. Skip removing the old tokenizer's own source vocab while still clearing stale files from a different tokenizer, and add a regression test. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use a per-call temporary directory for the sentencepiece fix The scratch directory defaulted to a single shared path, so concurrent or repeated get_chat_template(map_eos_token=True) calls could delete or overwrite each other's tokenizer.model between save and reload (tripping the piece assertion or reloading the wrong model), and stale files from an earlier tokenizer could leak into the reload. Work in a unique per-call subdirectory instead: this isolates every call without deleting anything the caller owns, and replaces the earlier per-file cleanup. Tests updated to read the patched model from the reloaded directory and to cover isolation and source-vocab preservation. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pass only the applied token mappings into the sentencepiece fix get_chat_template mirrors token remaps into tokenizer.model via fix_sentencepiece_tokenizer, but two caller paths passed a mapping that did not match what they wrote to the fast tokenizer JSON, so once the sentencepiece patch runs the model and JSON disagree: - the mapped-token path skipped entries whose target already existed but still passed the full mapping, renaming a piece the JSON never changed; - the EOS-swap path swapped both tokens in the JSON but passed only one direction, leaving two stop_word pieces and no old EOS piece. Pass the applied mapping (and both swap directions) instead. Add regression tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten sentencepiece guard comments * Add SPDX license identifier to sentencepiece guard test * Reclaim the per-call sentencepiece scratch directory The per-call tempfile.mkdtemp fixed the shared-directory race but never cleaned up, so a long-running process leaked one scratch dir per call. The dir cannot be deleted eagerly for sentencepiece tokenizers because the returned tokenizer's vocab_file points into it (a later save_pretrained copies the patched tokenizer.model from there). Reclaim it correctly instead: remove the dir right away on the fast-only path (the returned tokenizer never references it), and attach a weakref.finalize so the sentencepiece dir is removed once its tokenizer is garbage collected. Add regression tests for both. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the scratch-dir reclaim comment --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]>
Summary
fix_sentencepiece_tokenizercreates its own temporary directory, then returns early unless that directory already contains atokenizer.model:The file only appears on the line after the check, so the guard is always true and the body never runs. Nothing else writes that path either —
convert_to_fast_tokenizersaves into a per-name subdirectory ({temporary_location}/{name}), not{temporary_location}/tokenizer.model.Both call sites (
chat_templates.py:1976,:2022, reached viaget_chat_template(..., map_eos_token=True)) are commented:# Must fix the sentence piece tokenizer since there's no tokenizer.model file!The guard skips the body for precisely the reason the caller wants it called.
check_if_sentencepiece_modelinsave.py:421-425does the same probe in the working order —makedirs→save_pretrained→isfile. This makesfix_sentencepiece_tokenizermatch it.Impact
Silent, and not a crash: the caller still gets a usable
new_tokenizerwith the right chat template and eos token. What is lost is the sentencepiece piece rename, so the remapped token (e.g. eos →<|im_end|>) never lands intokenizer.model, and GGUF/llama.cpp exports carry the old piece. I'd frame this as export fidelity rather than a hot-path bug.Testing
New
tests/saving/test_fix_sentencepiece_tokenizer_guard.py— the two bug tests fail onmainand pass here; the third (a fast-only tokenizer with notokenizer.modelis still returned untouched) passes on both, pinning the behaviour the guard is legitimately there for.Placed under
tests/saving/next totest_fix_sentencepiece_gguf_robustness.pybecause it needs protobuf, and added to both Bucket-A lists inconsolidated-tests-ci.yml—Repo tests (CPU)--ignorestests/saving, so a file dropped there would never run. Happy to drop the workflow change if you'd rather wire it up yourself.Bucket-A locally: 88 passed, 1 deselected. Caller-side (
test_gemma4_chat_template,test_ignored_tokenizer_casing,test_remove_special_tokens_no_bos,test_to_sharegpt_optional_none): 25 passed.ruff checkclean;scripts/run_ruff_format.pyleaves the diff unchanged.Disclosure: written with Claude Code. I verified the reproduction, the dead-code claim, and the test red/green myself.