Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Rebuild CohereTokenizer from tokenizer.json when transformers v5 changes its ids (#12130)

Daniel Han12b6dbfc7c31
diff --git a/tests/test_tokenizer_bytelevel_roundtrip.py b/tests/test_tokenizer_bytelevel_roundtrip.py
index 13a2845778e..8d35adddad2 100644
--- a/tests/test_tokenizer_bytelevel_roundtrip.py
+++ b/tests/test_tokenizer_bytelevel_roundtrip.py
@@ -7,7 +7,16 @@ import pytest
from packaging.version import Version
import transformers
-from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, trainers
+from tokenizers import (
+ Regex,
+ Tokenizer,
+ decoders,
+ models,
+ normalizers,
+ pre_tokenizers,
+ processors,
+ trainers,
+)
from transformers import AutoTokenizer
import unsloth.tokenizer_utils as tu
@@ -196,3 +205,87 @@ def test_saved_repaired_tokenizer_reloads_with_plain_transformers(byte_level_lla
assert _ids(reloaded) == _reference_ids(byte_level_llama_dir)
assert reloaded(PROBE).input_ids == tok(PROBE).input_ids
assert reloaded.chat_template == tok.chat_template
+
+
+# tiny-aya: v5 CohereTokenizer swaps its Split regex pre-tokenizer for Digits + ByteLevel.
+COHERE_SPECIALS = ["<PAD>", "<UNK>", "<BOS_TOKEN>", "<|END_OF_TURN_TOKEN|>"]
+COHERE_REGEX = (
+ r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+"
+ r"|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*"
+ r"|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+"
+)
+COHERE_CORPUS = ["with open(path) as f: read(path) 123 456 789", "नमस्ते दुनिया (path)"] * 30
+COHERE_PROBE = "with open(path) as f: 123456 नमस्ते"
+
+
+def _cohere_like_tokenizer(split_regex = True):
+ tok = Tokenizer(models.BPE())
+ byte_level = pre_tokenizers.ByteLevel(add_prefix_space = False, use_regex = not split_regex)
+ if split_regex:
+ tok.pre_tokenizer = pre_tokenizers.Sequence(
+ [pre_tokenizers.Split(Regex(COHERE_REGEX), behavior = "isolated"), byte_level]
+ )
+ else:
+ tok.pre_tokenizer = pre_tokenizers.Sequence(
+ [pre_tokenizers.Digits(individual_digits = True), byte_level]
+ )
+ tok.decoder = decoders.ByteLevel()
+ trainer = trainers.BpeTrainer(
+ vocab_size = 500,
+ special_tokens = COHERE_SPECIALS,
+ initial_alphabet = pre_tokenizers.ByteLevel.alphabet(),
+ )
+ tok.train_from_iterator(COHERE_CORPUS, trainer = trainer)
+ bos = tok.token_to_id("<BOS_TOKEN>")
+ tok.post_processor = processors.TemplateProcessing(
+ single = "<BOS_TOKEN> $A", pair = "<BOS_TOKEN> $A $B", special_tokens = [("<BOS_TOKEN>", bos)]
+ )
+ return tok
+
+
+def _write_cohere_dir(path, tokenizer):
+ path.mkdir(parents = True, exist_ok = True)
+ tokenizer.save(str(path / "tokenizer.json"))
+ config = {
+ "tokenizer_class": "CohereTokenizerFast",
+ "bos_token": "<BOS_TOKEN>",
+ "eos_token": "<|END_OF_TURN_TOKEN|>",
+ "unk_token": "<UNK>",
+ "pad_token": "<PAD>",
+ "add_bos_token": True,
+ "add_eos_token": False,
+ "chat_template": CHAT_TEMPLATE,
+ }
+ (path / "tokenizer_config.json").write_text(json.dumps(config))
+ return str(path)
+
+
+def test_cohere_split_regex_ids_match_tokenizer_json(tmp_path):
+ path = _write_cohere_dir(tmp_path / "aya", _cohere_like_tokenizer(split_regex = True))
+ loaded = AutoTokenizer.from_pretrained(path)
+ reference = _reference_ids(path, COHERE_PROBE)
+ if TRANSFORMERS_V5:
+ assert loaded.decode(_ids(loaded, COHERE_PROBE)) == COHERE_PROBE
+ assert _ids(loaded, COHERE_PROBE) != reference
+ for tok in (
+ tu._apply_post_load_tokenizer_fixes(loaded, fix_tokenizer = False),
+ tu.load_correct_tokenizer(path),
+ ):
+ assert _ids(tok, COHERE_PROBE) == reference
+ assert tok.decode(_ids(tok, COHERE_PROBE)) == COHERE_PROBE
+ assert tok(COHERE_PROBE).input_ids[0] == tok.convert_tokens_to_ids("<BOS_TOKEN>")
+ assert (tok.bos_token, tok.eos_token, tok.pad_token) == (
+ "<BOS_TOKEN>",
+ "<|END_OF_TURN_TOKEN|>",
+ "<PAD>",
+ )
+
+
+def test_cohere_matching_tokenizer_json_is_untouched(tmp_path):
+ path = _write_cohere_dir(tmp_path / "expanse", _cohere_like_tokenizer(split_regex = False))
+ loaded = AutoTokenizer.from_pretrained(path)
+ before = loaded.backend_tokenizer.to_str()
+ fixed = tu._apply_post_load_tokenizer_fixes(loaded, fix_tokenizer = True)
+ assert fixed.backend_tokenizer.to_str() == before
+ assert not getattr(fixed, "_unsloth_tokenizer_json_repaired", False)
+ assert _ids(fixed, COHERE_PROBE) == _reference_ids(path, COHERE_PROBE)
diff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.py
index cc8fcff0ac6..36820cc4b4e 100644
--- a/unsloth/tokenizer_utils.py
+++ b/unsloth/tokenizer_utils.py
@@ -216,7 +216,11 @@ def _fix_gemma4_base_bos_token(tokenizer, config = None):
# v5 loads byte-level BPE repos declaring LlamaTokenizerFast with Metaspace, dropping spaces (transformers#45488, #48206).
_BACKEND_ROUNDTRIP_PROBE = "Hello world, this is a test."
-_BACKEND_IDS_PROBE = "Hello world! def f(x): return x**2 # code\n你好 éè Αβγ 12345.678"
+_BACKEND_IDS_PROBE = (
+ "Hello world! def f(x): return x**2 # code\n你好 éè Αβγ 12345.678 नमस्ते दुनिया open(path):\n"
+)
+# v5 __init__ overwrites tokenizer.json's pre-tokenizer: text round-trips but ids differ (tiny-aya).
+_V5_REBUILT_PRETOKENIZER_CLASSES = frozenset(("CohereTokenizer",))
def _backend_roundtrip(backend, text):
@@ -264,7 +268,7 @@ def _repair_one_tokenizer_backend(
if backend is None or not hasattr(backend, "pre_tokenizer"):
return False
ok, _ = _backend_roundtrip(backend, _BACKEND_ROUNDTRIP_PROBE)
- if ok is not False:
+ if ok is None or (ok and type(tokenizer).__name__ not in _V5_REBUILT_PRETOKENIZER_CLASSES):
return False
path = _resolve_tokenizer_json(tokenizer, cache_dir = cache_dir, revision = revision)
if path is None:
@@ -285,6 +289,8 @@ def _repair_one_tokenizer_backend(
except Exception:
return False
_, ref_ids = _backend_roundtrip(reference, _BACKEND_IDS_PROBE)
+ if ok and _backend_roundtrip(backend, _BACKEND_IDS_PROBE)[1] == ref_ids:
+ return False
saved = (backend.model, backend.normalizer, backend.pre_tokenizer, backend.decoder)
try:
# Keep the loaded post_processor, padding, truncation and added tokens.
@@ -317,8 +323,8 @@ def _repair_tokenizer_backend_from_json(
obj._unsloth_tokenizer_json_repaired = True
getattr(logger, "warning_once", logger.warning)(
f"Unsloth: {type(obj).__name__} for {getattr(obj, 'name_or_path', '')} did not "
- "round-trip text (transformers v5 replaced the byte-level pre-tokenizer from "
- "tokenizer.json), so it was rebuilt from tokenizer.json."
+ "match tokenizer.json (transformers v5 replaced its pre-tokenizer), so it was "
+ "rebuilt from tokenizer.json."
)
return tokenizer