Skip to content

fix(tokenizer): check for tokenizer.model after saving it, not before - #7194

Merged
danielhanchen merged 17 commits into
unslothai:mainfrom
chuenchen309:fix/sentencepiece-guard-order
Jul 18, 2026
Merged

danielhanchen merged 17 commits into
unslothai:mainfrom
chuenchen309:fix/sentencepiece-guard-order

Conversation

@chuenchen309

Copy link
Copy Markdown
Contributor

Summary

fix_sentencepiece_tokenizer creates its own 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

# Check if tokenizer.model exists
if not os.path.isfile(f"{temporary_location}/tokenizer.model"):
    return new_tokenizer                     # always true

# First save the old tokenizer
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 ({temporary_location}/{name}), not {temporary_location}/tokenizer.model.

Both call sites (chat_templates.py:1976, :2022, reached via get_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_model in save.py:421-425 does the same probe in the working order — makedirs → save_pretrained → isfile. This makes fix_sentencepiece_tokenizer match it.

Impact

Silent, and not a crash: the caller still gets a usable new_tokenizer with 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 in tokenizer.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 on main and pass here; the third (a fast-only tokenizer with no tokenizer.model is still returned untouched) passes on both, pinning the behaviour the guard is legitimately there for.

Placed under tests/saving/ next to test_fix_sentencepiece_gguf_robustness.py because it needs protobuf, and added to both Bucket-A lists in consolidated-tests-ci.yml — Repo tests (CPU) --ignores tests/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 check clean; scripts/run_ruff_format.py leaves the diff unchanged.

Disclosure: written with Claude Code. I verified the reproduction, the dead-code claim, and the test red/green myself.

`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]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@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: 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"):

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

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.

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)

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

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.

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)

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

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.

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.

@chuenchen309

Copy link
Copy Markdown
Contributor Author

CI triage, since this PR touches a workflow file and two reds could easily look like my doing:

The workflow change itself is green. Sanity — collection only and unsloth Bucket-A both pass on all three Core matrix cells, so the new tests/saving/test_fix_sentencepiece_tokenizer_guard.py is being collected and run where I added it.

The two reds are both in studio-backend-ci.yml, which I don't touch:

  • Repo tests (CPU) — test_sidebar_account_block_uses_leading_tight, the same pre-existing failure I described on fix(save): unsloth_push_to_hub_gguf(save_method="lora") raises NameError #7193: its regex no longer matches the current app-sidebar.tsx markup, and it reproduces on a clean main with no changes applied.
  • (Python 3.11) → Backend tests — studio/backend/tests/test_training_stop_watchdog.py::test_new_run_gets_its_own_watchdog, failing on assert first_wd.is_alive(). That step runs with working-directory: studio/backend, so it can't see anything in this diff. It also passes on fix(save): unsloth_push_to_hub_gguf(save_method="lora") raises NameError #7193, which shares this base — a thread-liveness assertion going red on one run and green on another looks like a timing flake rather than anything a PR did.

Locally, Bucket-A is 88 passed / 1 deselected, and the caller-side tests (test_gemma4_chat_template, test_ignored_tokenizer_casing, test_remove_special_tokens_no_bos, test_to_sharegpt_optional_none) are 25 passed.

Not proposing to fix either — just saving you the dig.

danielhanchen and others added 2 commits July 17, 2026 12:25
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.

@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: 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".

Comment thread unsloth/tokenizer_utils.py Outdated
Comment on lines 378 to 382
if os.path.isfile(old_model_path):
os.remove(old_model_path)

# First save the old tokenizer
old_tokenizer.save_pretrained(temporary_location)

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

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/tokenizer_utils.py Outdated
Comment on lines +377 to +379
old_model_path = f"{temporary_location}/tokenizer.model"
if os.path.isfile(old_model_path):
os.remove(old_model_path)

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

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.

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

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/tokenizer_utils.py Outdated
Comment on lines +376 to +377
if os.path.exists(temporary_location):
shutil.rmtree(temporary_location, ignore_errors = 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 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 👍 / 👎.

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.

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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/tokenizer_utils.py Outdated
Comment on lines +381 to +384
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)

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

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.

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

danielhanchen and others added 2 commits July 17, 2026 14:07
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: ce44796850

ℹ️ 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 and others added 2 commits July 17, 2026 15:01
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment on lines +386 to +387
if not os.path.isfile(f"{temporary_location}/tokenizer.model"):
return new_tokenizer

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

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.

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.

Comment on lines +386 to +387
if not os.path.isfile(f"{temporary_location}/tokenizer.model"):
return new_tokenizer

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

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.

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.

@chuenchen309

Copy link
Copy Markdown
Contributor Author

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 _unsloth_sentencepiece_temp directory entirely.

Agree the two you flagged as follow-ups — the EOS swap passing only {old_eos_token: stop_word}, and the partial-skip mapping not being filtered to what the fast-tokenizer JSON actually applied — are pre-existing caller-side issues in chat_templates.py rather than this guard-order change. Happy to open a separate PR for those two if it'd help, or leave them to you; whichever you prefer.

danielhanchen and others added 2 commits July 17, 2026 16:24
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 6fea95ffe6

ℹ️ 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
danielhanchen force-pushed the fix/sentencepiece-guard-order branch from 388b94f to 932c751 Compare July 17, 2026 17:36
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 932c751bb4

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

@oobabooga

Copy link
Copy Markdown
Member

@danielhanchen LGTM. I ran the differential end to end on transformers 4.57.6: on current main get_chat_template(..., map_eos_token=True) drops the sentencepiece model entirely, and on this branch it emits a tokenizer.model with the remapped piece and nothing stale. Both call sites check out, including a real Gemma <eos>/<end_of_turn> swap landing exactly one piece of each, and the per-call mkdtemp rewrite retires the whole shared-scratch saga cleanly.

danielhanchen and others added 2 commits July 17, 2026 23:32
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 7e01702ce6

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

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 658e6b063d

ℹ️ 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
danielhanchen merged commit 4e09328 into unslothai:main Jul 18, 2026
46 of 47 checks passed
VectorCipher pushed a commit to VectorCipher/unsloth that referenced this pull request Jul 20, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants